From a72d36819b3ca89b2750a6a85912dbf3b895f20b Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 18:32:51 -0800 Subject: [PATCH 001/203] Ontology: a data property can be marked as its class's display name Adds isDisplayName to ontologyProperty and createOntologyProperty, absent when unset so existing release digests do not change. Only a data property may set it, and a class has at most one such property, refused by the structure check with DUPLICATE_DISPLAY_NAME. Turtle export writes om:displayNameIntent and the importer reads it back. --- ...s-has-at-most-one-display-name-property.md | 34 +++++++ .../IndependentOntologyReleaseExportIT.java | 8 +- .../it/tests/OntologyPropertyResourceIT.java | 63 +++++++++++++ .../jdbi3/OntologyPropertyRepository.java | 2 +- .../service/jdbi3/OntologyWorkingModel.java | 32 +++++++ .../ontology/OntologyPropertyRules.java | 9 +- .../ontology/OntologyReleaseContent.java | 1 + .../ontology/OntologyStructureValidator.java | 33 +++++++ .../rdf/NativeOntologyRdfImporter.java | 2 + .../service/rdf/NativeOntologyRdfReader.java | 9 +- .../rdf/OntologyPropertyRdfWriter.java | 5 ++ .../service/rdf/OntologyRdfVocabulary.java | 11 ++- .../service/rdf/RdfSourceNormalizer.java | 3 +- .../ontology/OntologyPropertyMapper.java | 1 + .../ontology/NativeOntologyCsvCodecTest.java | 2 +- .../ontology/OntologyPropertyRulesTest.java | 23 +++++ .../OntologyReleaseContentDigestTest.java | 90 +++++++++++++++++++ .../OntologyStructureValidatorTest.java | 33 +++++++ .../rdf/NativeOntologyRdfImporterTest.java | 38 ++++++++ .../rdf/OntologyReleaseProjectionTest.java | 32 +++++++ .../api/data/createOntologyProperty.json | 3 + .../schema/entity/data/ontologyProperty.json | 4 + .../schema/type/ontologyProfileViolation.json | 3 +- .../resources/rdf/ontology/openmetadata.ttl | 8 ++ 24 files changed, 438 insertions(+), 11 deletions(-) create mode 100644 docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java diff --git a/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md b/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md new file mode 100644 index 000000000000..3785b348bdad --- /dev/null +++ b/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md @@ -0,0 +1,34 @@ +# A class has at most one display-name property, marked by om:displayNameIntent + +- **Status:** Accepted +- **Revisions:** v1 2026-11-21 (initial) +- **Deciders:** Ontology maintainers +- **Guard:** `OntologyStructureValidatorTest#aClassHasAtMostOneDisplayNameProperty`, + `OntologyReleaseContentDigestTest` and + `OntologyPropertyResourceIT#aDataPropertyCanBeItsClassDisplayNameAndEachClassHasOne` +- **Related:** ADR:2026-11-07-ontology-property-hierarchies-are-superproperty-fields + +## Context +A data property can say it is an identifier (`isIdentifier`). Clients also need to know which data +property holds the human-readable name of a class's instances, and exactly one answer per class, +or they have to guess. Release digests seal every property, so a new field must not change the +digest of a property that never sets it. + +## Decision +`ontologyProperty` gains `isDisplayName`, a boolean that only a data property may set. It has no +schema default: an unset flag is absent, so a property that never sets it seals the same content +and digest as before. `false` and absent mean the same to every reader. + +The RDF term is the annotation property `https://open-metadata.org/ontology/displayNameIntent`, +written as `"true"^^xsd:boolean` only when the flag is set, and read like `identifierIntent`: any +other value is a 400, and a missing statement imports as no flag. + +Within one ontology, two undeleted data properties that share a domain class cannot both set the flag. +The ontology structure check enforces it on every write, on import apply and on release capture, +and reports `DUPLICATE_DISPLAY_NAME` at `/isDisplayName` naming both properties. The second write +is refused instead of moving the flag, so no write changes a property its author did not touch. + +## Consequences +Moving the flag to another property takes two writes: clear it, then set it. A property with +several domain classes conflicts with any other flagged property on any of them. Revisit the +refusal if an author needs an atomic swap. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseExportIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseExportIT.java index ed25a0c6a7da..2c6cb0a3aca4 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseExportIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseExportIT.java @@ -131,7 +131,8 @@ void exportsFrozenDefinitionsWithoutAnRdfServer(RdfSerializationFormat format, T new OntologyLiteral().withValue("Gold"), new OntologyLiteral().withValue("Silver"))) .withUnit("kg") - .withIsIdentifier(true)); + .withIsIdentifier(true) + .withIsDisplayName(true)); var subclass = client.ontologyAxioms().create(axiom(ontology)); OntologyRelease release = capture(ontology); client.ontologyConcepts().update(concept.getId(), concept.withDisplayName("Later label")); @@ -187,6 +188,11 @@ void exportsFrozenDefinitionsWithoutAnRdfServer(RdfSerializationFormat format, T model.getResource("urn:example:customerCode"), model.createProperty("https://open-metadata.org/ontology/unitAnnotation"), "kg")); + assertTrue( + model.contains( + model.getResource("urn:example:customerCode"), + model.createProperty("https://open-metadata.org/ontology/displayNameIntent"), + model.createTypedLiteral(true))); assertFalse( model.contains( model.getResource("urn:example:customerCode"), RDF.type, OWL2.FunctionalProperty)); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java index bed150f37bbd..a51d8241f073 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java @@ -78,6 +78,69 @@ void dataValuesRoundTripAndEditsCreateANewVersion(TestNamespace ns) { assertTrue(updated.getVersion() > created.getVersion()); } + @Test + void aDataPropertyCanBeItsClassDisplayNameAndEachClassHasOne(TestNamespace ns) { + final var request = createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA); + final var ontology = SdkClients.adminClient().ontologies().getByName(request.getOntology()); + final URI customer = + URI.create("https://example.org/display/" + ns.shortPrefix() + "/Customer"); + final URI order = URI.create("https://example.org/display/" + ns.shortPrefix() + "/Order"); + BaseOntologyApprovalIT.declareClass(ontology, "Customer", customer); + BaseOntologyApprovalIT.declareClass(ontology, "Order", order); + + final OntologyProperty first = + createEntity(request.withDomain(List.of(customer)).withIsDisplayName(true)); + assertEquals(true, getEntity(first.getId().toString()).getIsDisplayName()); + + final CreateOntologyProperty second = + createRequest(ns.prefix("secondName"), ns) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(customer)) + .withIsDisplayName(true); + final OpenMetadataException rejected = + assertThrows(OpenMetadataException.class, () -> createEntity(second)); + assertEquals(400, rejected.getStatusCode()); + assertTrue(rejected.getMessage().contains("at most one display-name property")); + + final OntologyProperty other = createEntity(second.withDomain(List.of(order))); + assertEquals(true, getEntity(other.getId().toString()).getIsDisplayName()); + other.setDomain(List.of(customer)); + assertPropertyFieldRejected(other, "domain", List.of(customer)); + assertEquals(List.of(order), getEntity(other.getId().toString()).getDomain()); + + final OntologyProperty cleared = getEntity(first.getId().toString()); + cleared.setIsDisplayName(null); + final OntologyProperty updated = entityService().update(cleared.getId().toString(), cleared); + assertEquals(null, updated.getIsDisplayName()); + final var move = JsonUtils.getObjectMapper().createArrayNode(); + move.addObject() + .put("op", "replace") + .put("path", "/domain/0") + .put("value", customer.toString()); + assertEquals( + customer.toString(), + entityService().patch(other.getId(), move).getDomain().getFirst().toString()); + } + + @Test + void onlyADataPropertyMayBeADisplayName(TestNamespace ns) { + final var request = createMinimalRequest(ns).withIsDisplayName(true); + for (final OntologyPropertyKind kind : + List.of(OntologyPropertyKind.OBJECT, OntologyPropertyKind.ANNOTATION)) { + assertEquals( + 400, + assertThrows(OpenMetadataException.class, () -> createEntity(request.withKind(kind))) + .getStatusCode()); + } + } + + @Test + void aPropertyWithoutTheFlagReadsBackWithoutIt(TestNamespace ns) { + final OntologyProperty created = + createEntity(createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA)); + assertEquals(null, getEntity(created.getId().toString()).getIsDisplayName()); + } + @Test void enumerationMetadataIsValidatedOnEveryWrite(TestNamespace ns) { final CreateOntologyProperty request = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java index b50805512073..69f355860859 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java @@ -83,7 +83,7 @@ public OntologyPropertyRepository() { OntologyProperty.class, Entity.getCollectionDAO().ontologyPropertyDAO(), COLLECTION_PATH, - "ontology,iri,kind,domain,range,enumValues,unit,isIdentifier,inverse,characteristics,propertyChain,disjointWith,superProperties,deprecated,replacedBy"); + "ontology,iri,kind,domain,range,enumValues,unit,isIdentifier,isDisplayName,inverse,characteristics,propertyChain,disjointWith,superProperties,deprecated,replacedBy"); } @Override diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java index 95575117329f..598c1b31384b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java @@ -14,6 +14,7 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; import org.apache.commons.codec.digest.DigestUtils; import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.OntologyEntityInterface; @@ -45,6 +46,7 @@ final class OntologyWorkingModel { "kind", "domain", "range", + "isDisplayName", "inverse", "propertyChain", "disjointWith", @@ -83,6 +85,10 @@ void requireValid(final UUID ontologyId, final List changes) { && !Boolean.TRUE.equals(axiom.getDeleted())) { changedRules.add(axiom); } + if (change.after() instanceof OntologyProperty property + && Boolean.TRUE.equals(property.getIsDisplayName())) { + context.displayNameSiblings(property); + } if (change.before() instanceof OntologyEntityInterface declaration) { context.dependents(Set.of(declaration.getIri().toString())); } else if (change.after() instanceof OntologyEntityInterface declaration) { @@ -274,6 +280,32 @@ void dependents(final Set iris) { } } + /** The other display-name properties of the classes this one names, so the rule sees them. */ + void displayNameSiblings(final OntologyProperty property) { + final Set domain = + listOrEmpty(property.getDomain()).stream().map(URI::toString).collect(Collectors.toSet()); + if (domain.isEmpty()) { + return; + } + final var references = + dao.ontologyReferenceDAO() + .referencingForUpdate( + ontologyId, domain.stream().map(DigestUtils::sha256Hex).toList(), LIMIT + 1); + requireBound(references.size()); + for (final var reference : references) { + final var source = reference.getSource(); + if (domain.contains(reference.getIri().toString()) + && Entity.ONTOLOGY_PROPERTY.equals(source.getType()) + && !definitions.containsKey(source.getId())) { + final String json = + dao.ontologyPropertyDAO().findJsonByIdForUpdate(source.getId(), Include.NON_DELETED); + if (json != null) { + add(JsonUtils.readValue(json, OntologyProperty.class), false); + } + } + } + } + private void includeInversePartners(final Set iris, final Set next) { final var entities = dao.ontologyPropertyDAO(); final var rows = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPropertyRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPropertyRules.java index a22113f266c7..f6ed6e18740e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPropertyRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPropertyRules.java @@ -171,7 +171,9 @@ private static Violation dataMetadata(final OntologyProperty property) { final String field = dataOnlyField(property); if (field != null) { return new Violation( - field, "Only data properties can define enum values, units or identifier intent"); + field, + "Only data properties can define enum values, units, identifier intent or display-name" + + " intent"); } } if (unit != null && (unit.isBlank() || unit.length() > MAX_UNIT_LENGTH)) { @@ -194,7 +196,10 @@ private static String dataOnlyField(final OntologyProperty property) { if (property.getUnit() != null) { return "unit"; } - return Boolean.TRUE.equals(property.getIsIdentifier()) ? "isIdentifier" : null; + if (Boolean.TRUE.equals(property.getIsIdentifier())) { + return "isIdentifier"; + } + return Boolean.TRUE.equals(property.getIsDisplayName()) ? "isDisplayName" : null; } private static Violation literal(final OntologyLiteral literal) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java index 5c397695c903..232668f2b164 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java @@ -47,6 +47,7 @@ private static List semanticFields(final OntologyDefinition definition) "enumValues", "unit", "isIdentifier", + "isDisplayName", "inverse", "characteristics", "propertyChain", diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java index f02aea4ad94e..d303818d28bb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java @@ -371,6 +371,7 @@ private void validateProperty( "/kind", "The closure declares incompatible property kinds for " + property.getIri()); } + validateDisplayName(member, property); if (property.getInverse() != null) { requireProperty(member, property.getInverse(), OntologyPropertyKind.OBJECT, "/inverse"); } @@ -401,6 +402,38 @@ private void validateProperty( } } + /** A class has at most one data property that names its instances. */ + private void validateDisplayName( + final OntologyReleaseMember member, final OntologyProperty property) { + if (!Boolean.TRUE.equals(property.getIsDisplayName())) { + return; + } + final Set domain = + listOrEmpty(property.getDomain()).stream().map(URI::toString).collect(Collectors.toSet()); + properties.values().stream() + .flatMap(List::stream) + .filter(other -> !other.getId().equals(property.getId())) + .filter(other -> Boolean.TRUE.equals(other.getIsDisplayName())) + .filter(other -> !Boolean.TRUE.equals(other.getDeleted())) + .filter( + other -> + listOrEmpty(other.getDomain()).stream() + .map(URI::toString) + .anyMatch(domain::contains)) + .findFirst() + .ifPresent( + other -> + add( + member, + OntologyProfileViolationCode.DUPLICATE_DISPLAY_NAME, + "/isDisplayName", + "A class has at most one display-name property, but " + + property.getIri() + + " and " + + other.getIri() + + " both name the same class")); + } + private void validateSimplePropertyUse( final OntologyReleaseMember member, final OntologyProperty property) { if (propertyHierarchy.isNonSimple(property.getIri()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java index c3c590f5c2dd..e0421698e6f9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java @@ -450,6 +450,7 @@ private static Outcome classifyProperty( .withEnumValues(parsed.getEnumValues()) .withUnit(parsed.getUnit()) .withIsIdentifier(parsed.getIsIdentifier()) + .withIsDisplayName(parsed.getIsDisplayName()) .withInverse(parsed.getInverse()) .withCharacteristics(parsed.getCharacteristics()) .withPropertyChain(parsed.getPropertyChain()) @@ -1329,6 +1330,7 @@ && listOrEmpty(a.getEnumValues()).stream() .toList()) && Objects.equals(a.getUnit(), b.getUnit()) && Objects.equals(a.getIsIdentifier(), b.getIsIdentifier()) + && Boolean.TRUE.equals(a.getIsDisplayName()) == Boolean.TRUE.equals(b.getIsDisplayName()) && Objects.equals(iriText(a.getInverse()), iriText(b.getInverse())) && setOrEmpty(a.getCharacteristics()).equals(setOrEmpty(b.getCharacteristics())) && listOrEmpty(a.getPropertyChain()).stream() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfReader.java index 61d5b36bd6a8..d9a0d0924067 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfReader.java @@ -370,7 +370,10 @@ private OntologyProperty property(final Resource subject, final OntologyProperty .withDeprecated(flag(subject, OWL2.deprecated)) .withReplacedBy(annotationIri(subject, DCTerms.isReplacedBy)); final RDFNode identifier = expressions.one(subject, OntologyRdfVocabulary.IDENTIFIER_INTENT); - property.withIsIdentifier(identifier != null && booleanValue(identifier)); + property.withIsIdentifier(identifier != null && booleanValue(identifier, "Identifier intent")); + final RDFNode displayName = expressions.one(subject, OntologyRdfVocabulary.DISPLAY_NAME_INTENT); + property.withIsDisplayName( + displayName != null && booleanValue(displayName, "Display-name intent") ? true : null); property.withCharacteristics(characteristics(subject, kind)); property.withPropertyChain( kind == OntologyPropertyKind.OBJECT ? propertyChain(subject) : List.of()); @@ -957,12 +960,12 @@ private boolean flag(final Resource subject, final Property predicate) { }; } - private static boolean booleanValue(final RDFNode value) { + private static boolean booleanValue(final RDFNode value, final String label) { if (!value.isLiteral() || !value.asLiteral().getLanguage().isEmpty() || !XSD.xboolean.getURI().equals(value.asLiteral().getDatatypeURI()) || !"true".equals(value.asLiteral().getLexicalForm())) { - throw new BadRequestException("Identifier intent must be true"); + throw new BadRequestException(label + " must be true"); } return true; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyPropertyRdfWriter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyPropertyRdfWriter.java index 51e9a86151e5..b9d2e2b3eadd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyPropertyRdfWriter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyPropertyRdfWriter.java @@ -122,6 +122,11 @@ private static void writeDataMetadata( model, OntologyRdfVocabulary.IDENTIFIER_INTENT, EntityKind.ANNOTATION_PROPERTY); property.addLiteral(OntologyRdfVocabulary.IDENTIFIER_INTENT, true); } + if (Boolean.TRUE.equals(definition.getIsDisplayName())) { + OwlEntityDeclarations.declare( + model, OntologyRdfVocabulary.DISPLAY_NAME_INTENT, EntityKind.ANNOTATION_PROPERTY); + property.addLiteral(OntologyRdfVocabulary.DISPLAY_NAME_INTENT, true); + } } private static RDFNode enumLiteral(final Model model, final OntologyLiteral value) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyRdfVocabulary.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyRdfVocabulary.java index e9e53a9cdd0b..3dd88ad0784c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyRdfVocabulary.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyRdfVocabulary.java @@ -16,10 +16,19 @@ final class OntologyRdfVocabulary { ResourceFactory.createProperty("https://open-metadata.org/ontology/unitAnnotation"); static final Property IDENTIFIER_INTENT = ResourceFactory.createProperty("https://open-metadata.org/ontology/identifierIntent"); + static final Property DISPLAY_NAME_INTENT = + ResourceFactory.createProperty(NAMESPACE + "displayNameIntent"); static final Property ABSTRACT = ResourceFactory.createProperty(NAMESPACE + "abstract"); static final Property BOUND_ASSET = ResourceFactory.createProperty(NAMESPACE + "boundAsset"); static final Set ANNOTATIONS = - Set.of(DCTerms.source, DCTerms.isReplacedBy, UNIT, IDENTIFIER_INTENT, ABSTRACT, BOUND_ASSET); + Set.of( + DCTerms.source, + DCTerms.isReplacedBy, + UNIT, + IDENTIFIER_INTENT, + DISPLAY_NAME_INTENT, + ABSTRACT, + BOUND_ASSET); private OntologyRdfVocabulary() {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSourceNormalizer.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSourceNormalizer.java index 8cd373db96cc..cd06f19fb7ec 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSourceNormalizer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSourceNormalizer.java @@ -47,7 +47,8 @@ final class RdfSourceNormalizer { OWL2.versionIRI, OntologyRdfVocabulary.ABSTRACT, OntologyRdfVocabulary.UNIT, - OntologyRdfVocabulary.IDENTIFIER_INTENT); + OntologyRdfVocabulary.IDENTIFIER_INTENT, + OntologyRdfVocabulary.DISPLAY_NAME_INTENT); private static final List DESCRIPTIONS = List.of(SKOS.definition, RDFS.comment); private static final Set MARKUP_DATATYPES = Set.of(RDF.HTML.getURI(), RDF.xmlLiteral.getURI()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyPropertyMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyPropertyMapper.java index e1e1933c353f..3b437ad97833 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyPropertyMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyPropertyMapper.java @@ -21,6 +21,7 @@ public OntologyProperty createToEntity(final CreateOntologyProperty request, fin .withEnumValues(request.getEnumValues()) .withUnit(request.getUnit()) .withIsIdentifier(request.getIsIdentifier()) + .withIsDisplayName(request.getIsDisplayName()) .withInverse(request.getInverse()) .withCharacteristics(request.getCharacteristics()) .withPropertyChain(request.getPropertyChain()) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyCsvCodecTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyCsvCodecTest.java index e697dcf01fd2..9b14dc81881d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyCsvCodecTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyCsvCodecTest.java @@ -487,7 +487,7 @@ void metadataIsRejectedOnInapplicableRowKinds() { @Test void previewRefusesPropertyMetadataTheKindCannotCarryNamingTheColumn() { final String dataOnly = - "Only data properties can define enum values, units or identifier intent"; + "Only data properties can define enum values, units, identifier intent or display-name intent"; assertEquals( "CSV row 2, column unit: " + dataOnly, previewErrorOf( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPropertyRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPropertyRulesTest.java index f2ebd796ea79..d3607f1d84cc 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPropertyRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPropertyRulesTest.java @@ -42,6 +42,29 @@ void everyPropertyKindMayNameSuperproperties() { } } + @Test + void onlyADataPropertyMayBeADisplayName() { + final OntologyProperty property = + new OntologyProperty() + .withIri(PROPERTY) + .withKind(OntologyPropertyKind.DATA) + .withIsDisplayName(true); + assertNull(OntologyPropertyRules.firstViolation(property, () -> false)); + for (final OntologyPropertyKind kind : + List.of(OntologyPropertyKind.OBJECT, OntologyPropertyKind.ANNOTATION)) { + assertEquals( + new OntologyPropertyRules.Violation( + "isDisplayName", + "Only data properties can define enum values, units, identifier intent or" + + " display-name intent"), + OntologyPropertyRules.firstViolation(property.withKind(kind), () -> false), + kind.toString()); + } + assertNull( + OntologyPropertyRules.firstViolation( + property.withKind(OntologyPropertyKind.OBJECT).withIsDisplayName(null), () -> false)); + } + private static OntologyPropertyRules.Violation violation(final List superProperties) { return OntologyPropertyRules.firstViolation( new OntologyProperty() diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java new file mode 100644 index 000000000000..7b348e74b462 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java @@ -0,0 +1,90 @@ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.utils.JsonUtils; + +class OntologyReleaseContentDigestTest { + private static final UUID RELEASE = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); + + /** The fields a property member sealed before display-name intent existed. */ + private static final List SEALED_BEFORE = + List.of( + "id", + "name", + "fullyQualifiedName", + "displayName", + "description", + "ontology", + "iri", + "kind", + "domain", + "range", + "enumValues", + "unit", + "isIdentifier", + "inverse", + "characteristics", + "propertyChain", + "disjointWith", + "superProperties", + "deprecated", + "replacedBy"); + + @Test + void aPropertyWithoutTheFlagSealsTheDigestItAlwaysHad() { + final OntologyProperty property = property(); + final ObjectNode earlier = JsonUtils.getObjectMapper().valueToTree(property); + earlier.retain(SEALED_BEFORE); + earlier.with("ontology").retain("id", "type"); + + assertFalse(OntologyReleaseContent.project(property).has("isDisplayName")); + assertEquals(earlier, OntologyReleaseContent.project(property)); + assertEquals(digest(earlier), digest(OntologyReleaseContent.project(property))); + assertEquals( + digest(earlier), digest(OntologyReleaseContent.project(property.withIsDisplayName(null)))); + } + + @Test + void aPropertyWithTheFlagSealsItAndChangesTheDigest() { + final OntologyProperty property = property(); + final String without = digest(OntologyReleaseContent.project(property)); + final ObjectNode with = OntologyReleaseContent.project(property.withIsDisplayName(true)); + + assertTrue(with.path("isDisplayName").asBoolean()); + assertNotEquals(without, digest(with)); + } + + private static OntologyProperty property() { + return new OntologyProperty() + .withId(UUID.fromString("00000000-0000-0000-0000-0000000000b1")) + .withName("name") + .withIri(URI.create("https://example.org/name")) + .withKind(OntologyPropertyKind.DATA) + .withOntology( + new org.openmetadata.schema.type.EntityReference() + .withId(UUID.fromString("00000000-0000-0000-0000-0000000000c1")) + .withType("ontology")); + } + + private static String digest(final ObjectNode payload) { + return OntologyReleaseManifest.digest( + List.of( + OntologyReleaseManifest.member( + RELEASE, + MemberKind.PROPERTY, + UUID.fromString("00000000-0000-0000-0000-0000000000b1"), + payload))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java index 10f151b7129f..97f95665476a 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java @@ -793,6 +793,33 @@ void draftValidationReportsEveryClashAsAnErrorThatASingleSaveCouldNotSee() { .getValid()); } + @Test + void aClassHasAtMostOneDisplayNameProperty() { + final var customer = concept("Customer"); + final var order = concept("Order"); + final var name = displayName("name", customer); + final var label = displayName("label", customer); + final var orderName = displayName("orderName", order); + final var both = displayName("both", customer, order); + + assertEquals(List.of(), violations(customer, order, name, orderName)); + assertEquals( + List.of("DUPLICATE_DISPLAY_NAME /isDisplayName", "DUPLICATE_DISPLAY_NAME /isDisplayName"), + violations(customer, name, label)); + assertEquals( + List.of("DUPLICATE_DISPLAY_NAME /isDisplayName", "DUPLICATE_DISPLAY_NAME /isDisplayName"), + violations(customer, order, orderName, both)); + final String pair = + "A class has at most one display-name property, but %s and %s both name the same class"; + assertEquals( + List.of( + pair.formatted(label.getIri(), name.getIri()), + pair.formatted(name.getIri(), label.getIri())), + messages(customer, name, label)); + assertEquals(List.of(), violations(customer, name, label.withIsDisplayName(null))); + assertEquals(List.of(), violations(customer, name, label.withIsDisplayName(false))); + } + private static OntologyReleaseStructureReport validate(OntologyDefinition... definitions) { return OntologyStructureValidator.validate( RELEASE, Arrays.stream(definitions).map(value -> member(RELEASE.getId(), value)).toList()); @@ -833,6 +860,12 @@ private static OntologyProperty property(URI iri, OntologyPropertyKind kind) { return new OntologyProperty().withId(UUID.randomUUID()).withIri(iri).withKind(kind); } + private static OntologyProperty displayName(String name, OntologyConcept... classes) { + return property(URI.create("urn:property:" + name), OntologyPropertyKind.DATA) + .withDomain(Arrays.stream(classes).map(OntologyConcept::getIri).toList()) + .withIsDisplayName(true); + } + private static OntologyConcept concept(String name) { return new OntologyConcept() .withId(UUID.randomUUID()) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java index 6e5f75f58411..ae5d5a73afc5 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java @@ -434,6 +434,44 @@ void anAxiomNamingAPropertyThePlanRefusesIsRefusedWithIt() { assertEquals(1, preview.getSummary().getCounts().getSkippedRelations()); } + @Test + void aDisplayNameFlagIsReadAndAbsenceLeavesNoFlag() { + final var document = + readDocument( + """ + ex:name a owl:DatatypeProperty ; + true . + ex:code a owl:DatatypeProperty . + """); + + final var byIri = + document.properties().stream() + .collect(java.util.stream.Collectors.toMap(p -> p.getIri().toString(), p -> p)); + assertEquals(true, byIri.get("https://example.org/name").getIsDisplayName()); + assertNull(byIri.get("https://example.org/code").getIsDisplayName()); + } + + @Test + void aDisplayNameFlagThatIsNotTrueIsRefused() { + for (final String value : List.of("false", "\"true\"", "\"true\"^^xsd:string")) { + final var model = + importer.parse( + TURTLE_PREFIXES + + "ex:name a owl:DatatypeProperty ;" + + " " + + value + + " .", + RdfSerializationFormat.TURTLE); + try { + final var thrown = + assertThrows(BadRequestException.class, () -> NativeOntologyRdfImporter.read(model)); + assertEquals("Display-name intent must be true", thrown.getMessage(), value); + } finally { + model.close(); + } + } + } + @Test void skippedReportStaysSmallWhateverTheSourceStates() { final var document = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java index a5c88b7a82d7..823a9eb34eee 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -533,6 +534,37 @@ void dataEnumerationsRetainTypedValuesAndIdentifierIntent(final List p.getIri().toString(), p -> String.valueOf(p.getIsDisplayName()))); + assertEquals(Map.of(EX + "name", "true", EX + "code", "null"), flags); + } finally { + parsed.close(); + } + } finally { + exported.close(); + } + assertNativeReimportIsNoOp(bundle, RdfSerializationFormat.TURTLE); + } + private static Stream> enumeratedValues() { return Stream.of( List.of(new OntologyLiteral().withValue(""), new OntologyLiteral().withValue("Gold")), diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyProperty.json b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyProperty.json index 7d9fb55a09da..28a75925e47a 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyProperty.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyProperty.json @@ -46,6 +46,9 @@ "isIdentifier": { "$ref": "../../entity/data/ontologyProperty.json#/properties/isIdentifier" }, + "isDisplayName": { + "$ref": "../../entity/data/ontologyProperty.json#/properties/isDisplayName" + }, "inverse": { "$ref": "../../entity/data/ontologyProperty.json#/properties/inverse" }, diff --git a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyProperty.json b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyProperty.json index aeedf17dfca1..aa1165944dee 100644 --- a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyProperty.json +++ b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyProperty.json @@ -127,6 +127,10 @@ "type": "boolean", "default": false }, + "isDisplayName": { + "description": "Marks a DATA property as the one whose value names its class's instances. This annotation does not assert functionality or uniqueness. A class has at most one such property, and the field is absent when unset.", + "type": "boolean" + }, "inverse": { "description": "Semantic IRI of the inverse object property.", "$ref": "../../type/ontologyIri.json" diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json index 46f2a1074aea..43e1e94b71d7 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json @@ -31,7 +31,8 @@ "INVALID_CLASS_KIND", "SUBCLASS_CYCLE", "SUBPROPERTY_CYCLE", - "DISJOINT_CLASH" + "DISJOINT_CLASH", + "DUPLICATE_DISPLAY_NAME" ] } }, diff --git a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl index ec7c7d3df04c..54cfa54c0892 100644 --- a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl +++ b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl @@ -4183,6 +4183,10 @@ om:isIdentifier a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "isIdentifier" . +om:isDisplayName a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "isDisplayName" . + om:abstract a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "abstract" . @@ -4199,6 +4203,10 @@ om:identifierIntent a owl:AnnotationProperty ; rdfs:label "identifier intent" ; rdfs:comment "Authored identifier intent, without asserting functionality, an OWL key or source-data uniqueness." . +om:displayNameIntent a owl:AnnotationProperty ; + rdfs:label "display name intent" ; + rdfs:comment "Marks a data property whose value names its class's instances, without asserting functionality or source-data uniqueness." . + om:tableSharding a owl:DatatypeProperty ; om:projectionStatus om:Stored ; rdfs:domain om:Table ; From ffd1dc12e9ed90c80465c6ad214b255528488c55 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 18:49:33 -0800 Subject: [PATCH 002/203] Return latest table profile facts on native graph cluster assets Each table asset gains rowCount, profiledAt and sampled, read in one batched query from the latest stored profile and returned only to callers holding ViewDataProfile on the table. --- ...table-assets-carry-latest-profile-facts.md | 30 +++++ .../NativeOntologyDataGraphProfileIT.java | 121 ++++++++++++++++++ .../NativeOntologyDataGraphService.java | 81 +++++++++++- .../service/ontology/TableProfileFacts.java | 55 ++++++++ .../security/ViewPermissionFilter.java | 8 ++ .../ontology/TableProfileFactsTest.java | 70 ++++++++++ .../api/data/nativeOntologyAssetCluster.json | 15 +++ 7 files changed, 379 insertions(+), 1 deletion(-) create mode 100644 docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java diff --git a/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md b/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md new file mode 100644 index 000000000000..4661aaf39fd0 --- /dev/null +++ b/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md @@ -0,0 +1,30 @@ +# Table assets in a native graph page carry the facts of their latest stored profile + +- **Status:** Accepted +- **Revisions:** v1 2026-11-21 (initial) +- **Deciders:** Ontology Studio team +- **Guard:** `TableProfileFactsTest`, `NativeOntologyDataGraphProfileIT` +- **Related:** 2.1 Ontology Studio release testing + +## Context +A cluster asset in a native graph page named its table and column count, so a client that wanted a +table's size or the age of its profile made one profile request per table. A page holds up to 12 +clusters of several assets each, and profile reads are guarded by `ViewDataProfile`, a narrower +right than viewing the table. + +## Decision +Each table asset gains `rowCount`, `profiledAt` and `sampled`, read from the latest stored table +profile of every table on the page with one batched query. They are returned only for a table the +caller holds `ViewDataProfile` on; otherwise the table is returned without them. A table with no +stored profile has none of the three, so a missing profile is never reported as zero rows. +`rowCount` is returned only when the profile holds an exact non-negative whole number. + +`sampled` describes the stored profile, not the table's current profiler settings: it is true when +the profile records a percentage below 100, or a row sample smaller than the table (or a row sample +on a profile with no row count). A profile that records no sample is not sampled. `rowCount` itself +is always measured on the whole table, whatever `sampled` says. + +## Consequences +One extra read per page, constant in the number of tables. A client tells "no profile" from "not +permitted" only by not needing to: both leave the three fields absent. Changing a table's profiler +settings does not alter `sampled` for profiles already stored. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java new file mode 100644 index 000000000000..3ae16830674b --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java @@ -0,0 +1,121 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.clusterPage; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.graphPage; +import static org.openmetadata.it.tests.OntologyBindingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyBindingFixtures.admin; +import static org.openmetadata.it.tests.OntologyBindingFixtures.bindAll; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.tables; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateTableProfile; +import org.openmetadata.schema.api.data.NativeOntologyClusterAsset; +import org.openmetadata.schema.api.data.NativeOntologyDataGraphPage; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** Profile facts on the tables of {@code POST /dataGraph/pages}, and who may see them. */ +@ExtendWith(TestNamespaceExtension.class) +class NativeOntologyDataGraphProfileIT extends BaseOntologyApprovalIT { + private static final long PROFILED_AT = 1_700_000_000_000L; + private static final long ROW_COUNT = 1234L; + + @Test + void aViewableProfiledTableReturnsItsFactsAndAnUnprofiledOneReturnsNone(final TestNamespace ns) { + final var fixture = profiledFixture(ns); + final var assets = assetsById(graphPage(admin(), fixture.ontology(), List.of(), page())); + final var sampled = assets.get(fixture.sampled().getId()); + assertEquals(ROW_COUNT, sampled.getRowCount()); + assertEquals(PROFILED_AT, sampled.getProfiledAt()); + assertTrue(sampled.getSampled()); + final var whole = assets.get(fixture.whole().getId()); + assertEquals(7L, whole.getRowCount()); + assertEquals(PROFILED_AT, whole.getProfiledAt()); + assertFalse(whole.getSampled()); + assertNoFacts(assets.get(fixture.unprofiled().getId())); + } + + @Test + void aReaderWithoutProfileViewSeesTheTablesWithoutTheFacts(final TestNamespace ns) { + final var fixture = profiledFixture(ns); + try (var fixtures = new RdfAccessFixtures("profileDenied" + ns.shortPrefix())) { + final var denied = fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE); + final OpenMetadataClient reader = + client(fixtures.userToken("reader", List.of(denied.getId()))); + final var assets = assetsById(graphPage(reader, fixture.ontology(), List.of(), page())); + assertEquals(3, assets.size()); + assets.values().forEach(NativeOntologyDataGraphProfileIT::assertNoFacts); + } + } + + private static void assertNoFacts(final NativeOntologyClusterAsset asset) { + assertNull(asset.getRowCount()); + assertNull(asset.getProfiledAt()); + assertNull(asset.getSampled()); + } + + private static Map assetsById( + final NativeOntologyDataGraphPage page) { + return page.getClusters().stream() + .flatMap(cluster -> cluster.getAssets().stream()) + .collect(Collectors.toMap(asset -> asset.getAsset().getId(), Function.identity())); + } + + private static org.openmetadata.schema.api.data.NativeOntologyGraphPageSelection page() { + return clusterPage(0, 12); + } + + private static Fixture profiledFixture(final TestNamespace ns) { + final var ontology = createOntology(ns, "profileFacts"); + final var concept = declareClass(ontology, "Customer", CUSTOMER); + final var schema = DatabaseSchemaTestFactory.createSimple(ns).getFullyQualifiedName(); + final var all = tables(ns, schema, 3); + bindAll(concept, all); + put(all.get(0), profile(PROFILED_AT - 60_000L, 5.0, null)); + put(all.get(0), profile(PROFILED_AT, (double) ROW_COUNT, 10.0)); + put(all.get(1), profile(PROFILED_AT, 7.0, null)); + return new Fixture(ontology, all.get(0), all.get(1), all.get(2)); + } + + private static TableProfile profile( + final long timestamp, final double rowCount, final Double profileSample) { + return new TableProfile() + .withTimestamp(timestamp) + .withRowCount(rowCount) + .withProfileSample(profileSample); + } + + private static void put(final Table table, final TableProfile profile) { + admin() + .getHttpClient() + .execute( + HttpMethod.PUT, + "/v1/tables/" + table.getId() + "/tableProfile", + new CreateTableProfile().withTableProfile(profile).withColumnProfile(List.of()), + Table.class); + } + + private record Fixture( + org.openmetadata.schema.entity.data.Ontology ontology, + Table sampled, + Table whole, + Table unprofiled) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java index bdc887514eab..5b6ac5c6f036 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java @@ -37,12 +37,15 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.Edge; +import org.openmetadata.schema.type.EntityProfile; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.type.OntologyExpression; import org.openmetadata.schema.type.Paging; import org.openmetadata.schema.type.Relationship; +import org.openmetadata.schema.type.TableProfile; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.CollectionDAO; @@ -54,10 +57,12 @@ import org.openmetadata.service.jdbi3.OntologyConceptRepository; import org.openmetadata.service.jdbi3.OntologyReferenceDAO.AxiomPosition; import org.openmetadata.service.jdbi3.OntologyReferenceDAO.EdgeAxiomRow; +import org.openmetadata.service.jdbi3.TimeSeriesDAOs.ProfilerDataTimeSeriesDAO; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.DefaultAuthorizer; import org.openmetadata.service.security.ViewPermissionFilter; +import org.openmetadata.service.util.FullyQualifiedName; import org.openmetadata.service.util.RestUtil; /** @@ -137,9 +142,76 @@ List clusters( clusters.add(new Cluster(concept, summary.resolve(concept, resolved))); } } + addProfileFacts(access, clusters); return List.copyOf(clusters); } + /** + * Tables the caller may view the data profile of gain the facts of their latest stored profile, + * read for all tables of the page with one query. A table without a profile, or one the caller + * may not profile-view, is left as it is. + */ + private void addProfileFacts(final Access access, final List clusters) { + final Map> tables = new LinkedHashMap<>(); + for (final var cluster : clusters) { + for (final var asset : cluster.response().getAssets()) { + final var reference = asset.getAsset(); + if (Entity.TABLE.equals(reference.getType()) + && !nullOrEmpty(reference.getFullyQualifiedName())) { + tables + .computeIfAbsent( + FullyQualifiedName.buildHash(reference.getFullyQualifiedName()), + hash -> new ArrayList<>()) + .add(asset); + } + } + } + final var permitted = + viewableIds( + access, + tables.values().stream().map(assets -> assets.getFirst().getAsset()).toList(), + MetadataOperation.VIEW_DATA_PROFILE); + final var fqns = + tables.values().stream() + .map(List::getFirst) + .filter(asset -> permitted.contains(asset.getAsset().getId())) + .map(asset -> asset.getAsset().getFullyQualifiedName()) + .toList(); + if (!fqns.isEmpty()) { + latestProfileFacts(fqns) + .forEach( + (hash, facts) -> + tables + .get(hash) + .forEach( + asset -> + asset + .withRowCount(facts.rowCount()) + .withProfiledAt(facts.profiledAt()) + .withSampled(facts.sampled()))); + } + } + + private Map latestProfileFacts(final List fqns) { + final Map facts = new HashMap<>(); + final Map newest = new HashMap<>(); + for (final var record : + dao.profilerDataTimeSeriesDao() + .getLatestExtensionsBatch(fqns, ProfilerDataTimeSeriesDAO.TABLE_PROFILE_EXTENSION)) { + final var profile = JsonUtils.readValue(record.json(), EntityProfile.class); + final var data = + profile == null || profile.getProfileData() == null + ? null + : TableProfileFacts.from( + JsonUtils.convertValue(profile.getProfileData(), TableProfile.class)); + if (data != null && data.profiledAt() >= newest.getOrDefault(record.entityFQNHash(), 0L)) { + newest.put(record.entityFQNHash(), data.profiledAt()); + facts.put(record.entityFQNHash(), data); + } + } + return facts; + } + private Map visibleBindings( final Access access, final Set conceptIds, final int previewSize) { final Map summaries = new LinkedHashMap<>(); @@ -190,13 +262,20 @@ Map visibleAssets(final Access access, final List r } Set viewableIds(final Access access, final List references) { + return viewableIds(access, references, MetadataOperation.VIEW_BASIC); + } + + Set viewableIds( + final Access access, + final List references, + final MetadataOperation operation) { if (references.isEmpty()) { return Set.of(); } if (DefaultAuthorizer.getSubjectContext(access.securityContext()).isAdmin()) { return references.stream().map(EntityReference::getId).collect(Collectors.toSet()); } - return visibility.viewableIds(access.securityContext(), references); + return visibility.viewableIds(access.securityContext(), operation, references); } private Map previewReferences(final Map summaries) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java new file mode 100644 index 000000000000..7ce1bed11265 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java @@ -0,0 +1,55 @@ +/* + * Copyright 2026 OpenMetadata + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import org.openmetadata.schema.type.TableProfile; + +/** + * What a stored table profile states about the table: its row count when that is an exact + * non-negative whole number, when it was taken, and whether its column metrics were computed on a + * sample. Sampling is read from the profile's own sample fields, never from the table's current + * profiler settings, which may have changed since. + */ +record TableProfileFacts(Long rowCount, long profiledAt, boolean sampled) { + private static final double FULL_PERCENTAGE = 100d; + + /** Null when the profile carries no timestamp, since such a profile cannot be placed in time. */ + static TableProfileFacts from(final TableProfile profile) { + if (profile == null || profile.getTimestamp() == null) { + return null; + } + final Long rowCount = exactRowCount(profile.getRowCount()); + return new TableProfileFacts(rowCount, profile.getTimestamp(), sampled(profile, rowCount)); + } + + private static Long exactRowCount(final Number rowCount) { + if (rowCount == null) { + return null; + } + final double value = rowCount.doubleValue(); + final boolean wholeAndNonNegative = value >= 0 && value == Math.rint(value); + return wholeAndNonNegative && value < Long.MAX_VALUE ? (long) value : null; + } + + private static boolean sampled(final TableProfile profile, final Long rowCount) { + final Number sample = profile.getProfileSample(); + if (sample == null) { + return false; + } + if (profile.getProfileSampleType() == TableProfile.ProfileSampleType.ROWS) { + return rowCount == null || sample.doubleValue() < rowCount; + } + return sample.doubleValue() < FULL_PERCENTAGE; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java index 3b3e377246ca..ce94ec52722c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java @@ -58,6 +58,14 @@ public Set viewableIds(SecurityContext securityContext, List viewableIds( + SecurityContext securityContext, + MetadataOperation operation, + List references) { + return viewableIds(requestCheck(securityContext, operation), references); + } + /** * Ids of the {@code references} {@code userName} may perform {@code operation} on, for work that * runs without the request's security context (e.g. an asynchronous export). Never throws. diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java new file mode 100644 index 000000000000..885203277968 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java @@ -0,0 +1,70 @@ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.schema.utils.JsonUtils; + +class TableProfileFactsTest { + @Test + void aProfileWithoutSampleFieldsIsNotSampled() { + final var facts = TableProfileFacts.from(profile("{\"timestamp\":42,\"rowCount\":1500.0}")); + assertEquals(new TableProfileFacts(1500L, 42L, false), facts); + } + + @Test + void aPercentageBelowOneHundredIsSampledAndOneHundredIsNot() { + assertTrue(TableProfileFacts.from(profile(percentage("10"))).sampled()); + assertTrue(TableProfileFacts.from(profile(percentage("99.5"))).sampled()); + assertFalse(TableProfileFacts.from(profile(percentage("100"))).sampled()); + } + + @Test + void aSampleWithNoTypeIsReadAsAPercentage() { + assertTrue(TableProfileFacts.from(profile("{\"timestamp\":1,\"profileSample\":50}")).sampled()); + } + + @Test + void aRowSampleIsSampledOnlyWhenSmallerThanTheTable() { + assertTrue(TableProfileFacts.from(profile(rows("100", "1000"))).sampled()); + assertFalse(TableProfileFacts.from(profile(rows("1000", "1000"))).sampled()); + assertTrue(TableProfileFacts.from(profile(rows("100", null))).sampled()); + } + + @Test + void aMissingOrInexactRowCountIsAbsentNeverZero() { + assertNull(TableProfileFacts.from(profile("{\"timestamp\":7}")).rowCount()); + assertNull(TableProfileFacts.from(profile("{\"timestamp\":7,\"rowCount\":12.5}")).rowCount()); + assertNull(TableProfileFacts.from(profile("{\"timestamp\":7,\"rowCount\":-3}")).rowCount()); + assertEquals( + 0L, TableProfileFacts.from(profile("{\"timestamp\":7,\"rowCount\":0}")).rowCount()); + } + + @Test + void aProfileWithoutATimestampOrNoProfileYieldsNoFacts() { + assertNull(TableProfileFacts.from(null)); + assertNull(TableProfileFacts.from(new TableProfile().withRowCount(9.0))); + } + + private static String percentage(final String sample) { + return "{\"timestamp\":1,\"rowCount\":10,\"profileSample\":" + + sample + + ",\"profileSampleType\":\"PERCENTAGE\"}"; + } + + private static String rows(final String sample, final String rowCount) { + return "{\"timestamp\":1," + + (rowCount == null ? "" : "\"rowCount\":" + rowCount + ",") + + "\"profileSample\":" + + sample + + ",\"profileSampleType\":\"ROWS\"}"; + } + + private static TableProfile profile(final String json) { + return JsonUtils.readValue(json, TableProfile.class); + } +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json index 2d4daa7e44b6..83f552c1ba0d 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json @@ -21,6 +21,21 @@ "description": "Number of column paths bound on this asset.", "type": "integer", "minimum": 0 + }, + "rowCount": { + "description": "Row count of the asset's latest stored profile, always measured on the whole table. Present only for a table the caller may view the data profile of, whose latest profile records a row count.", + "type": "integer", + "existingJavaType": "java.lang.Long", + "format": "int64", + "minimum": 0 + }, + "profiledAt": { + "description": "Time the asset's latest stored profile was taken. Present only for a table the caller may view the data profile of that has a stored profile.", + "$ref": "../../type/basic.json#/definitions/timestamp" + }, + "sampled": { + "description": "True when that profile's column metrics were computed on a sample, as the profile itself records. Present exactly when profiledAt is.", + "type": "boolean" } }, "required": ["asset", "columnCount"], From 335a09129fe4fba9ff81c6968b3c406f4fdb6e89 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 19:25:58 -0800 Subject: [PATCH 003/203] Prove the profile facts reader path, tidy sampled and tie handling A reader who owns one of two profiled tables gets the facts of that table only, on both the page and the graph endpoints. A row sample is compared with the raw row count, equal profile timestamps resolve deterministically, and the pager reads profile facts only for clusters it keeps. --- ...table-assets-carry-latest-profile-facts.md | 9 ++- .../NativeOntologyDataGraphProfileIT.java | 72 +++++++++++++++---- .../NativeOntologyDataGraphPager.java | 1 + .../NativeOntologyDataGraphService.java | 10 ++- .../service/ontology/TableProfileFacts.java | 24 +++++-- ...tiveOntologyDataGraphPagerRequestTest.java | 17 +++++ .../ontology/TableProfileFactsTest.java | 34 +++++++++ .../api/data/nativeOntologyAssetCluster.json | 2 +- 8 files changed, 142 insertions(+), 27 deletions(-) diff --git a/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md b/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md index 4661aaf39fd0..960498abe561 100644 --- a/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md +++ b/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md @@ -4,7 +4,6 @@ - **Revisions:** v1 2026-11-21 (initial) - **Deciders:** Ontology Studio team - **Guard:** `TableProfileFactsTest`, `NativeOntologyDataGraphProfileIT` -- **Related:** 2.1 Ontology Studio release testing ## Context A cluster asset in a native graph page named its table and column count, so a client that wanted a @@ -22,7 +21,13 @@ stored profile has none of the three, so a missing profile is never reported as `sampled` describes the stored profile, not the table's current profiler settings: it is true when the profile records a percentage below 100, or a row sample smaller than the table (or a row sample on a profile with no row count). A profile that records no sample is not sampled. `rowCount` itself -is always measured on the whole table, whatever `sampled` says. +is always measured on the whole table, whatever `sampled` says. `sampled` reads only +`profileSample` and `profileSampleType`, so a profile computed on a partition or a custom query +reports `false`. A row sample is compared with the stored row count as it is, whole number or not. + +When one table has several latest profiles with the same timestamp, the one with the larger row +count wins (a missing count is smallest), then a sampled one over a whole one, so the result does +not depend on read order. ## Consequences One extra read per page, constant in the number of tables. A client tells "no profile" from "not diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java index 3ae16830674b..bf464b2821e3 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java @@ -10,10 +10,13 @@ import static org.openmetadata.it.tests.OntologyBindingFixtures.admin; import static org.openmetadata.it.tests.OntologyBindingFixtures.bindAll; import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.graph; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; import static org.openmetadata.it.tests.OntologyBindingFixtures.tables; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; @@ -24,8 +27,10 @@ import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.data.CreateTableProfile; import org.openmetadata.schema.api.data.NativeOntologyClusterAsset; +import org.openmetadata.schema.api.data.NativeOntologyDataGraph; import org.openmetadata.schema.api.data.NativeOntologyDataGraphPage; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.TableProfile; import org.openmetadata.sdk.client.OpenMetadataClient; @@ -41,16 +46,38 @@ class NativeOntologyDataGraphProfileIT extends BaseOntologyApprovalIT { @Test void aViewableProfiledTableReturnsItsFactsAndAnUnprofiledOneReturnsNone(final TestNamespace ns) { final var fixture = profiledFixture(ns); - final var assets = assetsById(graphPage(admin(), fixture.ontology(), List.of(), page())); - final var sampled = assets.get(fixture.sampled().getId()); - assertEquals(ROW_COUNT, sampled.getRowCount()); - assertEquals(PROFILED_AT, sampled.getProfiledAt()); - assertTrue(sampled.getSampled()); - final var whole = assets.get(fixture.whole().getId()); - assertEquals(7L, whole.getRowCount()); - assertEquals(PROFILED_AT, whole.getProfiledAt()); - assertFalse(whole.getSampled()); - assertNoFacts(assets.get(fixture.unprofiled().getId())); + for (final var assets : bothEndpoints(admin(), fixture)) { + final var sampled = assets.get(fixture.sampled().getId()); + assertEquals(ROW_COUNT, sampled.getRowCount()); + assertEquals(PROFILED_AT, sampled.getProfiledAt()); + assertTrue(sampled.getSampled()); + final var whole = assets.get(fixture.whole().getId()); + assertEquals(7L, whole.getRowCount()); + assertEquals(PROFILED_AT, whole.getProfiledAt()); + assertFalse(whole.getSampled()); + assertNoFacts(assets.get(fixture.unprofiled().getId())); + } + } + + @Test + void aReaderGetsTheFactsOfTheProfiledTableTheyOwnAndNoneOfTheOthers(final TestNamespace ns) { + final var fixture = profiledFixture(ns); + try (var fixtures = new RdfAccessFixtures("profileOwner" + ns.shortPrefix())) { + final var denied = + fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE, "!isOwner()"); + final OpenMetadataClient reader = + client(fixtures.userToken("owner", List.of(denied.getId()))); + ownBy(fixture.sampled(), readerReference(reader)); + for (final var assets : bothEndpoints(reader, fixture)) { + assertEquals(3, assets.size()); + final var owned = assets.get(fixture.sampled().getId()); + assertEquals(ROW_COUNT, owned.getRowCount()); + assertEquals(PROFILED_AT, owned.getProfiledAt()); + assertTrue(owned.getSampled()); + assertNoFacts(assets.get(fixture.whole().getId())); + assertNoFacts(assets.get(fixture.unprofiled().getId())); + } + } } @Test @@ -60,19 +87,36 @@ void aReaderWithoutProfileViewSeesTheTablesWithoutTheFacts(final TestNamespace n final var denied = fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE); final OpenMetadataClient reader = client(fixtures.userToken("reader", List.of(denied.getId()))); - final var assets = assetsById(graphPage(reader, fixture.ontology(), List.of(), page())); - assertEquals(3, assets.size()); - assets.values().forEach(NativeOntologyDataGraphProfileIT::assertNoFacts); + for (final var assets : bothEndpoints(reader, fixture)) { + assertEquals(3, assets.size()); + assets.values().forEach(NativeOntologyDataGraphProfileIT::assertNoFacts); + } } } + /** The assets of {@code POST /dataGraph/pages} and of {@code GET /dataGraph}, in that order. */ + private static List> bothEndpoints( + final OpenMetadataClient caller, final Fixture fixture) { + final NativeOntologyDataGraph graph = graph(caller, fixture.ontology(), "?limit=12"); + return List.of( + assetsById(graphPage(caller, fixture.ontology(), List.of(), page())), + graph.getClusters().stream() + .flatMap(cluster -> cluster.getAssets().stream()) + .collect(Collectors.toMap(asset -> asset.getAsset().getId(), Function.identity()))); + } + + private static void ownBy(final Table table, final EntityReference owner) { + final var current = admin().tables().get(table.getId().toString()); + admin().tables().update(table.getId().toString(), current.withOwners(List.of(owner))); + } + private static void assertNoFacts(final NativeOntologyClusterAsset asset) { assertNull(asset.getRowCount()); assertNull(asset.getProfiledAt()); assertNull(asset.getSampled()); } - private static Map assetsById( + private static Map assetsById( final NativeOntologyDataGraphPage page) { return page.getClusters().stream() .flatMap(cluster -> cluster.getAssets().stream()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java index e8657688595c..92b655b2f7b5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java @@ -114,6 +114,7 @@ private Map clusters( final var revisions = store.revisions(ranked.stream().map(ConceptAssetCount::conceptId).toList()); final var clusters = unloaded(graph.clusters(scope.access(), ranked, 4), scope.loaded()); + graph.addProfileFacts(scope.access(), clusters); final var added = load(clusters, revisions, scope.loaded()); response .withClusters(clusters.stream().map(Cluster::response).toList()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java index 5b6ac5c6f036..41953981c34c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java @@ -110,6 +110,7 @@ public NativeOntologyDataGraph graph( access, store.boundConcepts(ontologyId, query.limit(), query.offset()), query.assetsPerConcept()); + addProfileFacts(access, clusters); return new NativeOntologyDataGraph() .withClusters(clusters.stream().map(Cluster::response).toList()) .withEdges(edges(access, ontologyId, clusters, query.edgeLimit())) @@ -142,7 +143,6 @@ List clusters( clusters.add(new Cluster(concept, summary.resolve(concept, resolved))); } } - addProfileFacts(access, clusters); return List.copyOf(clusters); } @@ -151,7 +151,7 @@ List clusters( * read for all tables of the page with one query. A table without a profile, or one the caller * may not profile-view, is left as it is. */ - private void addProfileFacts(final Access access, final List clusters) { + void addProfileFacts(final Access access, final List clusters) { final Map> tables = new LinkedHashMap<>(); for (final var cluster : clusters) { for (final var asset : cluster.response().getAssets()) { @@ -194,7 +194,6 @@ private void addProfileFacts(final Access access, final List clusters) private Map latestProfileFacts(final List fqns) { final Map facts = new HashMap<>(); - final Map newest = new HashMap<>(); for (final var record : dao.profilerDataTimeSeriesDao() .getLatestExtensionsBatch(fqns, ProfilerDataTimeSeriesDAO.TABLE_PROFILE_EXTENSION)) { @@ -204,9 +203,8 @@ private Map latestProfileFacts(final List fqn ? null : TableProfileFacts.from( JsonUtils.convertValue(profile.getProfileData(), TableProfile.class)); - if (data != null && data.profiledAt() >= newest.getOrDefault(record.entityFQNHash(), 0L)) { - newest.put(record.entityFQNHash(), data.profiledAt()); - facts.put(record.entityFQNHash(), data); + if (data != null) { + facts.merge(record.entityFQNHash(), data, TableProfileFacts::latest); } } return facts; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java index 7ce1bed11265..8781aebbebb1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java @@ -1,5 +1,5 @@ /* - * Copyright 2026 OpenMetadata + * Copyright 2026 Collate * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,6 +13,7 @@ package org.openmetadata.service.ontology; +import java.util.Comparator; import org.openmetadata.schema.type.TableProfile; /** @@ -23,6 +24,20 @@ */ record TableProfileFacts(Long rowCount, long profiledAt, boolean sampled) { private static final double FULL_PERCENTAGE = 100d; + private static final Comparator RECENCY = + Comparator.comparingLong(TableProfileFacts::profiledAt) + .thenComparing( + TableProfileFacts::rowCount, Comparator.nullsFirst(Comparator.naturalOrder())) + .thenComparing(TableProfileFacts::sampled); + + /** + * The later of two profiles of one table. Equal timestamps, which differing operations can + * produce, are broken by the larger row count (absent is smallest), then by sampled over whole, + * so the outcome never depends on the order rows are read in. + */ + static TableProfileFacts latest(final TableProfileFacts first, final TableProfileFacts second) { + return RECENCY.compare(second, first) > 0 ? second : first; + } /** Null when the profile carries no timestamp, since such a profile cannot be placed in time. */ static TableProfileFacts from(final TableProfile profile) { @@ -30,7 +45,7 @@ static TableProfileFacts from(final TableProfile profile) { return null; } final Long rowCount = exactRowCount(profile.getRowCount()); - return new TableProfileFacts(rowCount, profile.getTimestamp(), sampled(profile, rowCount)); + return new TableProfileFacts(rowCount, profile.getTimestamp(), sampled(profile)); } private static Long exactRowCount(final Number rowCount) { @@ -42,13 +57,14 @@ private static Long exactRowCount(final Number rowCount) { return wholeAndNonNegative && value < Long.MAX_VALUE ? (long) value : null; } - private static boolean sampled(final TableProfile profile, final Long rowCount) { + private static boolean sampled(final TableProfile profile) { final Number sample = profile.getProfileSample(); if (sample == null) { return false; } if (profile.getProfileSampleType() == TableProfile.ProfileSampleType.ROWS) { - return rowCount == null || sample.doubleValue() < rowCount; + final Number rowCount = profile.getRowCount(); + return rowCount == null || sample.doubleValue() < rowCount.doubleValue(); } return sample.doubleValue() < FULL_PERCENTAGE; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPagerRequestTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPagerRequestTest.java index 678bafa4bef4..f110487dd309 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPagerRequestTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPagerRequestTest.java @@ -12,6 +12,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.macasaet.fernet.Key; @@ -173,6 +174,22 @@ void aClampedClusterPageAdvertisesTheOffsetAfterItsClampedRanks() { assertEquals(53, page.getNextClusterOffset()); } + @Test + void profileFactsAreComputedOnlyForTheClustersNotAlreadyLoaded() { + final var loaded = List.of(prefix(1, null)); + givenVisible(1, 2); + final var ranked = List.of(new ConceptAssetCount(id(1), 1), new ConceptAssetCount(id(2), 1)); + when(store.boundConcepts(ONTOLOGY, 2, 0)).thenReturn(ranked); + when(store.countBoundConcepts(ONTOLOGY)).thenReturn(2); + final var repeated = cluster(concept(1)); + final var fresh = cluster(concept(2)); + when(graph.clusters(any(), eq(ranked), eq(4))).thenReturn(List.of(repeated, fresh)); + final NativeOntologyDataGraphPage page = + pager().page(READER, ONTOLOGY, request(loaded, clusters(0, 2))); + assertEquals(1, page.getClusters().size()); + verify(graph).addProfileFacts(any(), eq(List.of(fresh))); + } + private NativeOntologyDataGraphPager pager() { return pager(CODEC); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java index 885203277968..12a8976417d0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java @@ -35,6 +35,32 @@ void aRowSampleIsSampledOnlyWhenSmallerThanTheTable() { assertTrue(TableProfileFacts.from(profile(rows("100", null))).sampled()); } + @Test + void aRowSampleIsComparedWithTheRawRowCountEvenWhenItIsNotAWholeNumber() { + final var small = TableProfileFacts.from(profile(rowsOf("100", "1000.5"))); + assertTrue(small.sampled()); + assertNull(small.rowCount()); + assertFalse(TableProfileFacts.from(profile(rowsOf("2000", "1000.5"))).sampled()); + } + + @Test + void ofTwoProfilesTheLaterWinsAndATieGoesToTheLargerRowCountInEitherOrder() { + final var older = new TableProfileFacts(99L, 10L, false); + final var newer = new TableProfileFacts(5L, 20L, true); + assertEquals(newer, TableProfileFacts.latest(older, newer)); + assertEquals(newer, TableProfileFacts.latest(newer, older)); + final var small = new TableProfileFacts(5L, 20L, false); + final var large = new TableProfileFacts(50L, 20L, false); + final var uncounted = new TableProfileFacts(null, 20L, false); + assertEquals(large, TableProfileFacts.latest(small, large)); + assertEquals(large, TableProfileFacts.latest(large, small)); + assertEquals(small, TableProfileFacts.latest(uncounted, small)); + assertEquals(small, TableProfileFacts.latest(small, uncounted)); + final var whole = new TableProfileFacts(5L, 20L, false); + assertEquals(newer, TableProfileFacts.latest(whole, newer)); + assertEquals(newer, TableProfileFacts.latest(newer, whole)); + } + @Test void aMissingOrInexactRowCountIsAbsentNeverZero() { assertNull(TableProfileFacts.from(profile("{\"timestamp\":7}")).rowCount()); @@ -64,6 +90,14 @@ private static String rows(final String sample, final String rowCount) { + ",\"profileSampleType\":\"ROWS\"}"; } + private static String rowsOf(final String sample, final String rowCount) { + return "{\"timestamp\":1,\"rowCount\":" + + rowCount + + ",\"profileSample\":" + + sample + + ",\"profileSampleType\":\"ROWS\"}"; + } + private static TableProfile profile(final String json) { return JsonUtils.readValue(json, TableProfile.class); } diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json index 83f552c1ba0d..ac9c7d481499 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json @@ -34,7 +34,7 @@ "$ref": "../../type/basic.json#/definitions/timestamp" }, "sampled": { - "description": "True when that profile's column metrics were computed on a sample, as the profile itself records. Present exactly when profiledAt is.", + "description": "True when that profile's column metrics were computed on a sample, as the profile itself records through its profileSample and profileSampleType. Nothing else is read, so a profile computed on a partition or a custom query reports false. Present exactly when profiledAt is.", "type": "boolean" } }, From 8c37cbc56496806e2499818a53d57c6046b92dea Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 19:26:55 -0800 Subject: [PATCH 004/203] Ontology: keep the display-name flag through CSV import and read siblings in one query A CSV import leaves the stored display-name flag as it is, because the format has no column for it. An explicit false is stored as absent so it seals like an unset flag. The sibling check reads only the flagged properties whose domain includes the class, in one query, instead of every reference to the class. The sealed-content test asserts a literal digest. Integration tests cover setting the flag by PATCH, a second flag by PUT and by import apply, and restoring a flagged property. --- ...s-has-at-most-one-display-name-property.md | 4 +- ...NativeOntologyPartialImportPropertyIT.java | 66 ++++++++++++ .../it/tests/OntologyPropertyResourceIT.java | 101 ++++++++++++++++++ .../jdbi3/OntologyPropertyRepository.java | 9 ++ .../service/jdbi3/OntologyReferenceDAO.java | 27 +++++ .../service/jdbi3/OntologyWorkingModel.java | 37 ++++--- .../rdf/NativeOntologyRdfImporter.java | 29 +++-- .../OntologyReleaseContentDigestTest.java | 47 +++----- .../rdf/NativeOntologyRdfImporterTest.java | 56 ++++++++++ 9 files changed, 318 insertions(+), 58 deletions(-) diff --git a/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md b/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md index 3785b348bdad..29a5c1413878 100644 --- a/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md +++ b/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md @@ -17,7 +17,9 @@ digest of a property that never sets it. ## Decision `ontologyProperty` gains `isDisplayName`, a boolean that only a data property may set. It has no schema default: an unset flag is absent, so a property that never sets it seals the same content -and digest as before. `false` and absent mean the same to every reader. +and digest as before. `false` and absent mean the same to every reader, so a write that states `false` stores it as absent. +The CSV format has no column for the flag, so a CSV import keeps the stored flag and a Turtle import +takes it from the file. The RDF term is the annotation property `https://open-metadata.org/ontology/displayNameIntent`, written as `"true"^^xsd:boolean` only when the flag is set, and read like `identifierIntent`: any diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java index 6775a83dcf20..ba98058873b2 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java @@ -4,6 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.net.URI; +import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; @@ -17,6 +19,7 @@ import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.data.NativeOntologyImportFormat; import org.openmetadata.schema.api.data.NativeOntologyImportItem; +import org.openmetadata.schema.api.data.NativeOntologyImportItemStatus; import org.openmetadata.schema.api.data.NativeOntologyImportPreview; import org.openmetadata.schema.api.data.PreviewNativeOntologyImport; import org.openmetadata.schema.entity.data.Ontology; @@ -24,6 +27,7 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeSetState; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.models.ListParams; @@ -41,6 +45,18 @@ public class NativeOntologyPartialImportPropertyIT extends BaseOntologyApprovalI ex:owns a owl:ObjectProperty ; rdfs:label "owns" ; rdfs:domain ex:Account ; rdfs:range ex:Ledger . """; + private static final String NAMES = + """ + @prefix owl: . + @prefix rdfs: . + @prefix xsd: . + @prefix ex: . + ex:Account a owl:Class ; rdfs:label "Account" . + ex:%s a owl:DatatypeProperty ; rdfs:label "% true . + """; + @Test void anAppliedPropertyWhoseDomainConceptWasLeftOutIsRefusedNamingTheOperationAndConcept( TestNamespace ns) { @@ -94,6 +110,56 @@ void droppingThePropertyWithItsConceptOrKeepingEverythingApplies(TestNamespace n assertEquals(Set.of("owns"), propertyNames(whole)); } + @Test + void aSecondDisplayNamePropertyForAClassIsSkippedByPreviewAndRefusedOnApply(TestNamespace ns) { + final var client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "displayNames"); + final NativeOntologyImportPreview first = + client.ontologies().previewImport(ontology.getId(), names(ns, "accountName")); + apply(ns, ontology, first, first.getChangeSet().getOperations(), "firstName"); + assertEquals(Set.of("accountName"), propertyNames(ontology)); + + final NativeOntologyImportPreview second = + client.ontologies().previewImport(ontology.getId(), names(ns, "accountLabel")); + final NativeOntologyImportItem skipped = + second.getSummary().getItems().stream() + .filter(item -> item.getLabel().equals("accountLabel")) + .findFirst() + .orElseThrow(); + assertEquals(NativeOntologyImportItemStatus.SKIPPED, skipped.getStatus()); + assertTrue(skipped.getReason().contains("at most one display-name property")); + assertEquals(0, second.getChangeSet().getOperations().size()); + + final OntologyChangeOperation forged = + JsonUtils.deepCopy( + first.getChangeSet().getOperations().stream() + .filter(operation -> operation.getProperty() != null) + .findFirst() + .orElseThrow(), + OntologyChangeOperation.class); + forged.setId(UUID.randomUUID()); + forged + .getProperty() + .withId(UUID.randomUUID()) + .withName("accountLabel") + .withFullyQualifiedName(ontology.getFullyQualifiedName() + ".accountLabel") + .withIri(URI.create(forged.getProperty().getIri() + "Label")); + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> apply(ns, ontology, second, List.of(forged), "secondName")); + + assertTrue( + refusal.getMessage().contains("at most one display-name property"), refusal.getMessage()); + assertEquals(Set.of("accountName"), propertyNames(ontology)); + } + + private static PreviewNativeOntologyImport names(TestNamespace ns, String property) { + return new PreviewNativeOntologyImport() + .withFormat(NativeOntologyImportFormat.TURTLE) + .withData(NAMES.formatted(ns.shortPrefix(), property)); + } + private static Set propertyNames(Ontology ontology) { return SdkClients.adminClient() .ontologyProperties() diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java index a51d8241f073..072b3d53a923 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java @@ -1,13 +1,16 @@ package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.net.URI; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @@ -19,12 +22,15 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.OntologyLiteral; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.RelationshipCharacteristic; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.models.ListParams; import org.openmetadata.sdk.models.ListResponse; import org.openmetadata.sdk.services.ontology.OntologyPropertyService; +import org.openmetadata.service.ontology.OntologyReleaseContent; +import org.openmetadata.service.ontology.OntologyReleaseManifest; @Execution(ExecutionMode.CONCURRENT) public class OntologyPropertyResourceIT @@ -122,6 +128,101 @@ void aDataPropertyCanBeItsClassDisplayNameAndEachClassHasOne(TestNamespace ns) { entityService().patch(other.getId(), move).getDomain().getFirst().toString()); } + @Test + void theFlagCanBeSetOnAnExistingPropertyAndASecondOneIsRefusedOnEveryWrite(TestNamespace ns) { + final var request = createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA); + final var ontology = SdkClients.adminClient().ontologies().getByName(request.getOntology()); + final URI customer = URI.create("https://example.org/display/" + ns.shortPrefix() + "/Buyer"); + BaseOntologyApprovalIT.declareClass(ontology, "Buyer", customer); + final OntologyProperty first = createEntity(request.withDomain(List.of(customer))); + final OntologyProperty second = + createEntity( + createRequest(ns.prefix("buyerCode"), ns) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(customer))); + assertEquals(null, getEntity(first.getId().toString()).getIsDisplayName()); + + final var flag = JsonUtils.getObjectMapper().createArrayNode(); + flag.addObject().put("op", "add").put("path", "/isDisplayName").put("value", true); + assertEquals(true, entityService().patch(first.getId(), flag).getIsDisplayName()); + assertEquals(true, getEntity(first.getId().toString()).getIsDisplayName()); + + final OntologyProperty flagged = getEntity(second.getId().toString()).withIsDisplayName(true); + final OpenMetadataException put = + assertThrows( + OpenMetadataException.class, + () -> entityService().update(flagged.getId().toString(), flagged)); + assertTrue(put.getMessage().contains("at most one display-name property"), put.getMessage()); + final OpenMetadataException patch = + assertThrows( + OpenMetadataException.class, () -> entityService().patch(second.getId(), flag)); + assertEquals(400, patch.getStatusCode()); + assertEquals(null, getEntity(second.getId().toString()).getIsDisplayName()); + } + + @Test + void restoringAFlaggedPropertyIntoAClassThatAlreadyHasOneIsRefused(TestNamespace ns) { + final var request = createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA); + final var ontology = SdkClients.adminClient().ontologies().getByName(request.getOntology()); + final URI shop = URI.create("https://example.org/display/" + ns.shortPrefix() + "/Shop"); + BaseOntologyApprovalIT.declareClass(ontology, "Shop", shop); + final OntologyProperty original = + createEntity(request.withDomain(List.of(shop)).withIsDisplayName(true)); + deleteEntity(original.getId().toString()); + final OntologyProperty replacement = + createEntity( + createRequest(ns.prefix("shopName"), ns) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(shop)) + .withIsDisplayName(true)); + + final OpenMetadataException refused = + assertThrows(OpenMetadataException.class, () -> restoreEntity(original.getId().toString())); + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains("at most one display-name property")); + assertEquals(true, getEntity(replacement.getId().toString()).getIsDisplayName()); + } + + @Test + void anExplicitFalseIsStoredAndSealedLikeAnAbsentFlag(TestNamespace ns) { + final OntologyProperty explicit = + createEntity( + createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA).withIsDisplayName(false)); + final OntologyProperty absent = + createEntity( + createRequest(ns.prefix("absentFlag"), ns).withKind(OntologyPropertyKind.DATA)); + final OntologyProperty storedExplicit = getEntity(explicit.getId().toString()); + final OntologyProperty storedAbsent = getEntity(absent.getId().toString()); + + assertEquals(null, storedExplicit.getIsDisplayName()); + assertFalse(JsonUtils.valueToTree(storedExplicit).has("isDisplayName")); + assertEquals(sealedDigest(storedAbsent), sealedDigest(storedExplicit)); + + final OntologyProperty flagged = storedExplicit.withIsDisplayName(true); + assertEquals( + true, entityService().update(flagged.getId().toString(), flagged).getIsDisplayName()); + final OntologyProperty cleared = getEntity(flagged.getId().toString()).withIsDisplayName(false); + assertEquals( + null, entityService().update(cleared.getId().toString(), cleared).getIsDisplayName()); + } + + /** The digest of the sealed content of a property, with the identity fields made equal. */ + private static String sealedDigest(OntologyProperty property) { + final ObjectNode content = OntologyReleaseContent.project(property); + content.put("id", "00000000-0000-0000-0000-0000000000b1"); + content.put("name", "sealed"); + content.put("fullyQualifiedName", "sealed"); + content.put("iri", "https://example.org/sealed"); + content.with("ontology").put("id", "00000000-0000-0000-0000-0000000000c1"); + return OntologyReleaseManifest.digest( + List.of( + OntologyReleaseManifest.member( + UUID.fromString("00000000-0000-0000-0000-0000000000a1"), + OntologyReleaseMember.MemberKind.PROPERTY, + UUID.fromString("00000000-0000-0000-0000-0000000000b1"), + content))); + } + @Test void onlyADataPropertyMayBeADisplayName(TestNamespace ns) { final var request = createMinimalRequest(ns).withIsDisplayName(true); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java index 69f355860859..d044996ba5e9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java @@ -86,6 +86,15 @@ public OntologyPropertyRepository() { "ontology,iri,kind,domain,range,enumValues,unit,isIdentifier,isDisplayName,inverse,characteristics,propertyChain,disjointWith,superProperties,deprecated,replacedBy"); } + /** Not being a display name has one stored form, an absent flag, so false never seals apart. */ + @Override + public void prepare(final OntologyProperty entity, final boolean update) { + if (Boolean.FALSE.equals(entity.getIsDisplayName())) { + entity.setIsDisplayName(null); + } + super.prepare(entity, update); + } + @Override protected void validateDefinition(final OntologyProperty entity) { final OntologyPropertyRules.Violation violation = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java index 95386b63eaa6..4c02c2077c44 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java @@ -105,6 +105,33 @@ List referencingForUpdate( @BindList("iriHashes") List iriHashes, @Bind("limit") int limit); + String SIBLINGS_FROM = + "SELECT p.json FROM ontology_property_entity p WHERE p.ontologyId = :ontologyId " + + "AND p.deleted = FALSE AND "; + String SIBLINGS_WHERE = + " AND EXISTS (SELECT 1 FROM ontology_reference r " + + "WHERE r.sourceType = 'ontologyProperty' AND r.sourceId = p.id " + + "AND r.ontologyId = p.ontologyId AND r.role = 'DOMAIN' AND r.iriHash IN ()) " + + "ORDER BY p.id LIMIT :limit FOR UPDATE"; + + /** + * The undeleted properties flagged as a display name whose domain includes one of the classes, + * in one read, whatever else references those classes. + */ + @ConnectionAwareSqlQuery( + value = + SIBLINGS_FROM + + "JSON_UNQUOTE(JSON_EXTRACT(p.json, '$.isDisplayName')) = 'true'" + + SIBLINGS_WHERE, + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = SIBLINGS_FROM + "p.json ->> 'isDisplayName' = 'true'" + SIBLINGS_WHERE, + connectionType = POSTGRES) + List displayNameSiblings( + @BindUUID("ontologyId") UUID ontologyId, + @BindList("iriHashes") List iriHashes, + @Bind("limit") int limit); + @SqlQuery( "SELECT a.json FROM ontology_axiom_entity a JOIN ontology_reference r " + "ON r.sourceId = a.id AND r.ontologyId = a.ontologyId " diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java index 598c1b31384b..3fc83eafed0f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java @@ -14,7 +14,6 @@ import java.util.Map; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; import org.apache.commons.codec.digest.DigestUtils; import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.OntologyEntityInterface; @@ -280,28 +279,28 @@ void dependents(final Set iris) { } } - /** The other display-name properties of the classes this one names, so the rule sees them. */ + /** + * The stored display-name properties of the classes this one names, so the rule sees them. One + * read returns only those rows, so a heavily referenced class costs nothing extra and the + * write cannot fail on its reference count. The per-ontology lock every write takes before it + * validates serializes two writes that flag different properties of one class, and the locking + * read is a current read of what the first one committed. + */ void displayNameSiblings(final OntologyProperty property) { - final Set domain = - listOrEmpty(property.getDomain()).stream().map(URI::toString).collect(Collectors.toSet()); + final List domain = + listOrEmpty(property.getDomain()).stream() + .map(URI::toString) + .distinct() + .map(DigestUtils::sha256Hex) + .toList(); if (domain.isEmpty()) { return; } - final var references = - dao.ontologyReferenceDAO() - .referencingForUpdate( - ontologyId, domain.stream().map(DigestUtils::sha256Hex).toList(), LIMIT + 1); - requireBound(references.size()); - for (final var reference : references) { - final var source = reference.getSource(); - if (domain.contains(reference.getIri().toString()) - && Entity.ONTOLOGY_PROPERTY.equals(source.getType()) - && !definitions.containsKey(source.getId())) { - final String json = - dao.ontologyPropertyDAO().findJsonByIdForUpdate(source.getId(), Include.NON_DELETED); - if (json != null) { - add(JsonUtils.readValue(json, OntologyProperty.class), false); - } + for (final String json : + dao.ontologyReferenceDAO().displayNameSiblings(ontologyId, domain, LIMIT)) { + final OntologyProperty sibling = JsonUtils.readValue(json, OntologyProperty.class); + if (!definitions.containsKey(sibling.getId())) { + add(sibling, false); } } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java index e0421698e6f9..6f3ab9900976 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java @@ -147,7 +147,10 @@ private NativeOntologyImportPreview preview( requireApplicable(source.document(), stored, source.propertyRows()); final RdfSkipLedger dropped = RdfSkipLedger.continuing(source.document().skipped()); final Outcomes outcomes = - reject(classify(source.document(), stored, maxChanged), stored, dropped); + reject( + classify(source.document(), stored, maxChanged, SourceFamily.of(source.format())), + stored, + dropped); final Plan plan = new Plan(stored, working, SourceFamily.of(source.format())); final CreateOntologyChangeSet changeSet = plan.of(outcomes); return new NativeOntologyImportPreview() @@ -172,7 +175,10 @@ NativeOntologyImportSummary summarize(final Source source, final int maxChanged) requireApplicable(source.document(), Stored.EMPTY, source.propertyRows()); final RdfSkipLedger dropped = RdfSkipLedger.continuing(source.document().skipped()); final Outcomes outcomes = - reject(classify(source.document(), Stored.EMPTY, maxChanged), Stored.EMPTY, dropped); + reject( + classify(source.document(), Stored.EMPTY, maxChanged, SourceFamily.of(source.format())), + Stored.EMPTY, + dropped); final Plan plan = new Plan(Stored.EMPTY, PREVIEW_TARGET, SourceFamily.of(source.format())); plan.of(outcomes); final List items = plan.itemsWithClashes(); @@ -239,7 +245,10 @@ public CreateOntologyChangeSet reconcileUnbounded( final Stored stored = Stored.index(working); requireApplicable(document, stored, Map.of()); return plan( - reject(classify(document, stored, Integer.MAX_VALUE), stored, new RdfSkipLedger()), + reject( + classify(document, stored, Integer.MAX_VALUE, SourceFamily.RDF), + stored, + new RdfSkipLedger()), stored, working, SourceFamily.RDF); @@ -381,11 +390,14 @@ static SourceFamily of(final NativeOntologyImportFormat format) { } private static Outcomes classify(final NativeOntologyDocument document, final Stored stored) { - return classify(document, stored, MAX_CHANGED_DEFINITIONS); + return classify(document, stored, MAX_CHANGED_DEFINITIONS, SourceFamily.RDF); } private static Outcomes classify( - final NativeOntologyDocument document, final Stored stored, final int maxChanged) { + final NativeOntologyDocument document, + final Stored stored, + final int maxChanged, + final SourceFamily family) { final Outcomes outcomes = new Outcomes( firstOccurrences( @@ -398,7 +410,7 @@ private static Outcomes classify( property -> property.getIri().toString(), property -> classifyProperty( - property, stored.properties().get(property.getIri().toString()))), + property, stored.properties().get(property.getIri().toString()), family)), classifyAxioms(document.axioms(), stored.axioms())); if (outcomes.changed() > maxChanged) { throw new BadRequestException("A native import accepts at most 1000 changed definitions"); @@ -438,7 +450,7 @@ private static Outcome classifyConcept( } private static Outcome classifyProperty( - final OntologyProperty parsed, final OntologyProperty current) { + final OntologyProperty parsed, final OntologyProperty current, final SourceFamily family) { if (current == null) { return new Added<>(parsed, parsed.getIri().toString()); } @@ -450,7 +462,8 @@ private static Outcome classifyProperty( .withEnumValues(parsed.getEnumValues()) .withUnit(parsed.getUnit()) .withIsIdentifier(parsed.getIsIdentifier()) - .withIsDisplayName(parsed.getIsDisplayName()) + .withIsDisplayName( + family == SourceFamily.CSV ? current.getIsDisplayName() : parsed.getIsDisplayName()) .withInverse(parsed.getInverse()) .withCharacteristics(parsed.getCharacteristics()) .withPropertyChain(parsed.getPropertyChain()) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java index 7b348e74b462..7cca6a3a8cd6 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java @@ -13,47 +13,34 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.OntologyPropertyKind; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; -import org.openmetadata.schema.utils.JsonUtils; class OntologyReleaseContentDigestTest { private static final UUID RELEASE = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); - /** The fields a property member sealed before display-name intent existed. */ - private static final List SEALED_BEFORE = - List.of( - "id", - "name", - "fullyQualifiedName", - "displayName", - "description", - "ontology", - "iri", - "kind", - "domain", - "range", - "enumValues", - "unit", - "isIdentifier", - "inverse", - "characteristics", - "propertyChain", - "disjointWith", - "superProperties", - "deprecated", - "replacedBy"); + /** + * The sealed content and digest of this property, computed on the commit before display-name + * intent existed. Both are literals, so a change to the generated classes or to the sealed fields + * that touches an unflagged property fails here. + */ + private static final String SEALED_BEFORE = + "{\"id\":\"00000000-0000-0000-0000-0000000000b1\",\"name\":\"name\"," + + "\"ontology\":{\"id\":\"00000000-0000-0000-0000-0000000000c1\",\"type\":\"ontology\"}," + + "\"iri\":\"https://example.org/name\",\"kind\":\"DATA\",\"domain\":[],\"range\":[]," + + "\"enumValues\":[],\"isIdentifier\":false,\"characteristics\":[],\"propertyChain\":[]," + + "\"disjointWith\":[],\"superProperties\":[],\"deprecated\":false}"; + + private static final String DIGEST_BEFORE = + "21498bea62f55ff6341537c8a8344d8f9b8628ce4fd5a3bbaf80485961fe2f3a"; @Test void aPropertyWithoutTheFlagSealsTheDigestItAlwaysHad() { final OntologyProperty property = property(); - final ObjectNode earlier = JsonUtils.getObjectMapper().valueToTree(property); - earlier.retain(SEALED_BEFORE); - earlier.with("ontology").retain("id", "type"); assertFalse(OntologyReleaseContent.project(property).has("isDisplayName")); - assertEquals(earlier, OntologyReleaseContent.project(property)); - assertEquals(digest(earlier), digest(OntologyReleaseContent.project(property))); + assertEquals(SEALED_BEFORE, OntologyReleaseContent.project(property).toString()); + assertEquals(DIGEST_BEFORE, digest(OntologyReleaseContent.project(property))); assertEquals( - digest(earlier), digest(OntologyReleaseContent.project(property.withIsDisplayName(null)))); + DIGEST_BEFORE, digest(OntologyReleaseContent.project(property.withIsDisplayName(null)))); } @Test diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java index ae5d5a73afc5..8043c3bb0102 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java @@ -43,6 +43,7 @@ import org.openmetadata.schema.type.RelationshipCharacteristic; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.NativeOntologyCsvCodec; import org.openmetadata.service.ontology.NativeOntologyDocument; import org.openmetadata.service.ontology.OntologyPackCatalog; import org.openmetadata.service.ontology.OntologyPackContentLoader; @@ -451,6 +452,53 @@ void aDisplayNameFlagIsReadAndAbsenceLeavesNoFlag() { assertNull(byIri.get("https://example.org/code").getIsDisplayName()); } + @Test + void reimportingACsvExportKeepsTheStoredDisplayNameFlag() { + final var stored = imported(root(), FLAGGED_NAME); + + final var preview = importer.preview(importer.read(csvRequest(FLAGGED_NAME)), stored); + + assertEquals(0, preview.getChangeSet().getOperations().size()); + assertEquals(0, preview.getSummary().getCounts().getUpdatedProperties()); + final var edited = + importer.preview( + importer.read( + csvRequest(FLAGGED_NAME.replace("rdfs:label \"name\"", "rdfs:label \"given\""))), + stored); + final var property = edited.getChangeSet().getOperations().getFirst().getProperty(); + assertEquals("given", property.getDisplayName()); + assertEquals(true, property.getIsDisplayName()); + } + + private PreviewNativeOntologyImport csvRequest(String turtle) { + return new PreviewNativeOntologyImport() + .withFormat(NativeOntologyImportFormat.CSV) + .withData(NativeOntologyCsvCodec.write(importer.read(turtleRequest(turtle)).document())); + } + + @Test + void aTurtleImportTakesTheDisplayNameFlagFromTheFile() { + final var root = root(); + final var stored = imported(root, FLAGGED_NAME); + final String unflagged = + TURTLE_PREFIXES + + """ + ex:Customer a owl:Class ; rdfs:label "Customer" . + ex:name a owl:DatatypeProperty ; rdfs:label "name" ; rdfs:domain ex:Customer . + """; + + assertEquals( + 0, + importer + .preview(importer.read(turtleRequest(FLAGGED_NAME)), stored) + .getChangeSet() + .getOperations() + .size()); + final var cleared = importer.preview(importer.read(turtleRequest(unflagged)), stored); + assertEquals(1, cleared.getChangeSet().getOperations().size()); + assertNull(cleared.getChangeSet().getOperations().getFirst().getProperty().getIsDisplayName()); + } + @Test void aDisplayNameFlagThatIsNotTrueIsRefused() { for (final String value : List.of("false", "\"true\"", "\"true\"^^xsd:string")) { @@ -1538,6 +1586,14 @@ void aRequestWithoutARecognizableFormatNamesTheFiveFormats() { @prefix ex: . """; + private static final String FLAGGED_NAME = + TURTLE_PREFIXES + + """ + ex:Customer a owl:Class ; rdfs:label "Customer" . + ex:name a owl:DatatypeProperty ; rdfs:label "name" ; rdfs:domain ex:Customer ; + true . + """; + private NativeOntologyDocument readDocument(final String turtle) { return readRaw(TURTLE_PREFIXES + turtle); } From dd3e09f09de20c6178ea4340fd4f8678581f0736 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 20:09:49 -0800 Subject: [PATCH 005/203] Ontology: a CSV row that changes a property's kind drops the display-name flag, and the sibling read is a join A CSV row keeps the stored display-name flag only while the property stays a data property. The sibling lookup joins the property and reference tables so that FOR UPDATE reads and locks both as current reads on MySQL. The put test sends a real PUT and the false-flag test is named for what it proves. --- ...NativeOntologyPartialImportPropertyIT.java | 114 ++++++++++++++++++ .../it/tests/OntologyPropertyResourceIT.java | 22 +++- .../service/jdbi3/OntologyReferenceDAO.java | 14 ++- .../service/jdbi3/OntologyWorkingModel.java | 5 +- .../rdf/NativeOntologyRdfImporter.java | 15 ++- .../rdf/NativeOntologyRdfImporterTest.java | 20 +++ 6 files changed, 175 insertions(+), 15 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java index ba98058873b2..a76885f494b9 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java @@ -1,6 +1,7 @@ package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -27,9 +28,12 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeSetState; +import org.openmetadata.schema.type.OntologyPropertyKind; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.models.ListParams; +import org.openmetadata.service.ontology.NativeOntologyCsvCodec; +import org.openmetadata.service.rdf.NativeOntologyRdfImporter; /** A partial import never leaves a property whose domain or range is a concept that was not kept. */ @Execution(ExecutionMode.CONCURRENT) @@ -154,6 +158,116 @@ void aSecondDisplayNamePropertyForAClassIsSkippedByPreviewAndRefusedOnApply(Test assertEquals(Set.of("accountName"), propertyNames(ontology)); } + @Test + void aCsvRowThatMakesTheFlaggedPropertyAnObjectPropertyIsPreviewedAndAppliedWithoutTheFlag( + TestNamespace ns) { + final var client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "kindChange"); + final NativeOntologyImportPreview first = + client.ontologies().previewImport(ontology.getId(), names(ns, "accountName")); + apply(ns, ontology, first, first.getChangeSet().getOperations(), "flagged"); + assertEquals(true, storedProperty(ontology, "accountName").getIsDisplayName()); + + final NativeOntologyImportPreview preview = + client + .ontologies() + .previewImport( + ontology.getId(), + csvOf( + ns, + """ + ex:Account a owl:Class ; rdfs:label "Account" . + ex:accountName a owl:ObjectProperty ; rdfs:label "accountName" ; + rdfs:domain ex:Account ; rdfs:range ex:Account . + """)); + + assertEquals(1, preview.getSummary().getCounts().getUpdatedProperties()); + assertEquals(1, preview.getChangeSet().getOperations().size()); + apply(ns, ontology, preview, preview.getChangeSet().getOperations(), "toObject"); + final OntologyProperty stored = storedProperty(ontology, "accountName"); + assertEquals(OntologyPropertyKind.OBJECT, stored.getKind()); + assertNull(stored.getIsDisplayName()); + } + + @Test + void aCsvRowThatAddsADomainClassWithADisplayNamePropertyIsRefusedByPreviewAndApply( + TestNamespace ns) { + final var client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "domainSibling"); + final String both = + """ + ex:Account a owl:Class ; rdfs:label "Account" . + ex:Ledger a owl:Class ; rdfs:label "Ledger" . + ex:accountName a owl:DatatypeProperty ; rdfs:label "accountName" ; + rdfs:domain ex:Account ; rdfs:range xsd:string ; + true . + ex:ledgerName a owl:DatatypeProperty ; rdfs:label "ledgerName" ; + rdfs:domain ex:Ledger ; rdfs:range xsd:string ; + true . + """; + final NativeOntologyImportPreview first = + client.ontologies().previewImport(ontology.getId(), turtleOf(ns, both)); + apply(ns, ontology, first, first.getChangeSet().getOperations(), "twoClasses"); + + final NativeOntologyImportPreview preview = + client + .ontologies() + .previewImport( + ontology.getId(), + csvOf( + ns, + both.replace("rdfs:domain ex:Account", "rdfs:domain ex:Account, ex:Ledger"))); + + final NativeOntologyImportItem item = + preview.getSummary().getItems().stream() + .filter(candidate -> candidate.getLabel().equals("accountName")) + .findFirst() + .orElseThrow(); + assertEquals(NativeOntologyImportItemStatus.SKIPPED, item.getStatus()); + assertTrue(item.getReason().contains("at most one display-name property"), item.getReason()); + assertEquals(0, preview.getChangeSet().getOperations().size()); + assertEquals( + List.of(URI.create("https://example.org/displayNames/" + ns.shortPrefix() + "/Account")), + storedProperty(ontology, "accountName").getDomain()); + } + + private static OntologyProperty storedProperty(Ontology ontology, String name) { + final var client = SdkClients.adminClient(); + final UUID id = + client + .ontologyProperties() + .list(new ListParams().addFilter("ontology", ontology.getFullyQualifiedName())) + .getData() + .stream() + .filter(item -> item.getName().equals(name)) + .findFirst() + .orElseThrow() + .getId(); + return client.ontologyProperties().get(id); + } + + private static final String PREFIXES = + """ + @prefix owl: . + @prefix rdfs: . + @prefix xsd: . + @prefix ex: . + """; + + private static PreviewNativeOntologyImport turtleOf(TestNamespace ns, String body) { + return new PreviewNativeOntologyImport() + .withFormat(NativeOntologyImportFormat.TURTLE) + .withData(PREFIXES.formatted(ns.shortPrefix()) + body); + } + + private static PreviewNativeOntologyImport csvOf(TestNamespace ns, String body) { + return new PreviewNativeOntologyImport() + .withFormat(NativeOntologyImportFormat.CSV) + .withData( + NativeOntologyCsvCodec.write( + new NativeOntologyRdfImporter().read(turtleOf(ns, body)).document())); + } + private static PreviewNativeOntologyImport names(TestNamespace ns, String property) { return new PreviewNativeOntologyImport() .withFormat(NativeOntologyImportFormat.TURTLE) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java index 072b3d53a923..adaac37d55ca 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java @@ -129,7 +129,7 @@ void aDataPropertyCanBeItsClassDisplayNameAndEachClassHasOne(TestNamespace ns) { } @Test - void theFlagCanBeSetOnAnExistingPropertyAndASecondOneIsRefusedOnEveryWrite(TestNamespace ns) { + void theFlagCanBeSetOnAnExistingPropertyAndASecondOneIsRefusedByPutAndPatch(TestNamespace ns) { final var request = createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA); final var ontology = SdkClients.adminClient().ontologies().getByName(request.getOntology()); final URI customer = URI.create("https://example.org/display/" + ns.shortPrefix() + "/Buyer"); @@ -147,12 +147,24 @@ void theFlagCanBeSetOnAnExistingPropertyAndASecondOneIsRefusedOnEveryWrite(TestN assertEquals(true, entityService().patch(first.getId(), flag).getIsDisplayName()); assertEquals(true, getEntity(first.getId().toString()).getIsDisplayName()); - final OntologyProperty flagged = getEntity(second.getId().toString()).withIsDisplayName(true); + final CreateOntologyProperty flagSecond = + createRequest(second.getName(), ns) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(customer)) + .withIsDisplayName(true); final OpenMetadataException put = assertThrows( OpenMetadataException.class, - () -> entityService().update(flagged.getId().toString(), flagged)); - assertTrue(put.getMessage().contains("at most one display-name property"), put.getMessage()); + () -> SdkClients.adminClient().ontologyProperties().upsert(flagSecond)); + assertEquals(400, put.getStatusCode()); + assertEquals( + "Ontology validation failed: A class has at most one display-name property, but " + + flagSecond.getIri() + + " and " + + first.getIri() + + " both name the same class", + put.getMessage()); + assertEquals(null, getEntity(second.getId().toString()).getIsDisplayName()); final OpenMetadataException patch = assertThrows( OpenMetadataException.class, () -> entityService().patch(second.getId(), flag)); @@ -184,7 +196,7 @@ void restoringAFlaggedPropertyIntoAClassThatAlreadyHasOneIsRefused(TestNamespace } @Test - void anExplicitFalseIsStoredAndSealedLikeAnAbsentFlag(TestNamespace ns) { + void aFalseFlagIsStoredAsAnAbsentFlagAndProjectsLikeOne(TestNamespace ns) { final OntologyProperty explicit = createEntity( createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA).withIsDisplayName(false)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java index 4c02c2077c44..9a5f09976f1b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java @@ -106,17 +106,19 @@ List referencingForUpdate( @Bind("limit") int limit); String SIBLINGS_FROM = - "SELECT p.json FROM ontology_property_entity p WHERE p.ontologyId = :ontologyId " - + "AND p.deleted = FALSE AND "; + "SELECT p.json FROM ontology_property_entity p JOIN ontology_reference r " + + "ON r.sourceId = p.id AND r.ontologyId = p.ontologyId " + + "WHERE p.ontologyId = :ontologyId AND p.deleted = FALSE AND "; String SIBLINGS_WHERE = - " AND EXISTS (SELECT 1 FROM ontology_reference r " - + "WHERE r.sourceType = 'ontologyProperty' AND r.sourceId = p.id " - + "AND r.ontologyId = p.ontologyId AND r.role = 'DOMAIN' AND r.iriHash IN ()) " + " AND r.sourceType = 'ontologyProperty' AND r.role = 'DOMAIN' AND r.iriHash IN () " + "ORDER BY p.id LIMIT :limit FOR UPDATE"; /** * The undeleted properties flagged as a display name whose domain includes one of the classes, - * in one read, whatever else references those classes. + * in one read, whatever else references those classes. It is a join with {@code FOR UPDATE}, so + * on MySQL both tables are read as current reads and locked, not as the transaction's snapshot. + * A property with several matching domain classes comes back once per match, and the caller drops + * the repeats, because Postgres rejects {@code FOR UPDATE} with {@code DISTINCT}. */ @ConnectionAwareSqlQuery( value = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java index 3fc83eafed0f..0064639fa36e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java @@ -283,8 +283,9 @@ void dependents(final Set iris) { * The stored display-name properties of the classes this one names, so the rule sees them. One * read returns only those rows, so a heavily referenced class costs nothing extra and the * write cannot fail on its reference count. The per-ontology lock every write takes before it - * validates serializes two writes that flag different properties of one class, and the locking - * read is a current read of what the first one committed. + * validates serializes two writes that flag different properties of one class. The read is a join + * under {@code FOR UPDATE}, so on MySQL it sees what the first write committed in both the + * property table and the reference table, whatever the transaction's snapshot holds. */ void displayNameSiblings(final OntologyProperty property) { final List domain = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java index 6f3ab9900976..4ae9b453dacb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java @@ -449,6 +449,18 @@ private static Outcome classifyConcept( : new Updated<>(current, proposed); } + /** + * A CSV has no column for the flag, so a row keeps the stored one, but only while the row leaves + * the property a data property: no other kind can hold it. + */ + private static Boolean displayNameFlag( + final OntologyProperty parsed, final OntologyProperty current, final SourceFamily family) { + if (family != SourceFamily.CSV) { + return parsed.getIsDisplayName(); + } + return parsed.getKind() == OntologyPropertyKind.DATA ? current.getIsDisplayName() : null; + } + private static Outcome classifyProperty( final OntologyProperty parsed, final OntologyProperty current, final SourceFamily family) { if (current == null) { @@ -462,8 +474,7 @@ private static Outcome classifyProperty( .withEnumValues(parsed.getEnumValues()) .withUnit(parsed.getUnit()) .withIsIdentifier(parsed.getIsIdentifier()) - .withIsDisplayName( - family == SourceFamily.CSV ? current.getIsDisplayName() : parsed.getIsDisplayName()) + .withIsDisplayName(displayNameFlag(parsed, current, family)) .withInverse(parsed.getInverse()) .withCharacteristics(parsed.getCharacteristics()) .withPropertyChain(parsed.getPropertyChain()) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java index 8043c3bb0102..11baec06ed30 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java @@ -470,6 +470,26 @@ void reimportingACsvExportKeepsTheStoredDisplayNameFlag() { assertEquals(true, property.getIsDisplayName()); } + @Test + void aCsvRowThatStopsTheFlaggedPropertyBeingADataPropertyDropsTheFlag() { + final var stored = imported(root(), FLAGGED_NAME); + final String asObject = + TURTLE_PREFIXES + + """ + ex:Customer a owl:Class ; rdfs:label "Customer" . + ex:name a owl:ObjectProperty ; rdfs:label "name" ; + rdfs:domain ex:Customer ; rdfs:range ex:Customer . + """; + + final var preview = importer.preview(importer.read(csvRequest(asObject)), stored); + + assertEquals(1, preview.getChangeSet().getOperations().size()); + assertEquals(1, preview.getSummary().getCounts().getUpdatedProperties()); + final var property = preview.getChangeSet().getOperations().getFirst().getProperty(); + assertEquals(OntologyPropertyKind.OBJECT, property.getKind()); + assertNull(property.getIsDisplayName()); + } + private PreviewNativeOntologyImport csvRequest(String turtle) { return new PreviewNativeOntologyImport() .withFormat(NativeOntologyImportFormat.CSV) From 42c3dbe758316fb16b8580f471efbb696a9f541b Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 20:32:02 -0800 Subject: [PATCH 006/203] ontology: shapes as a native entity, sealed in releases and exchanged as SHACL Adds the ontologyShape entity with typed constraints, release capture and validation, SHACL Turtle export and import, and the storage migration. --- .../native/2.1.0/mysql/schemaChanges.sql | 19 + .../native/2.1.0/postgres/schemaChanges.sql | 19 + ...es-hold-the-supported-shacl-constraints.md | 55 ++ .../IndependentOntologyShapeReleaseIT.java | 332 +++++++++++ .../it/tests/OntologyShapeResourceIT.java | 439 ++++++++++++++ .../sdk/client/OpenMetadataClient.java | 7 + .../ontology/OntologyShapeService.java | 49 ++ .../java/org/openmetadata/service/Entity.java | 1 + .../governance/approval/ApprovalGate.java | 1 + .../service/jdbi3/ListFilter.java | 2 + .../jdbi3/OntologyShapeRepository.java | 45 ++ .../service/jdbi3/OntologyWorkingModel.java | 9 + .../service/jdbi3/RdfInfraDAOs.java | 21 + .../service/ontology/OntologyReferences.java | 5 +- .../ontology/OntologyReleaseContent.java | 2 + .../ontology/OntologyReleaseReader.java | 4 +- .../service/ontology/OntologyShapeRules.java | 202 +++++++ .../ontology/OntologyStructureValidator.java | 39 ++ .../ontology/OntologyUnpublishedChanges.java | 3 +- .../ontology/OntologyWorkingSnapshot.java | 4 +- .../service/rdf/OntologyExportFormat.java | 11 +- .../service/rdf/OntologyReleaseExporter.java | 22 +- .../rdf/OntologyReleaseProjection.java | 2 + .../service/rdf/OntologyShaclReader.java | 556 ++++++++++++++++++ .../service/rdf/OntologyShaclVocabulary.java | 85 +++ .../service/rdf/OntologyShaclWriter.java | 147 +++++ .../service/rdf/RdfExcludedEntities.java | 1 + .../resources/ontology/OntologyResource.java | 5 +- .../ontology/OntologyShapeMapper.java | 38 ++ .../ontology/OntologyShapeResource.java | 297 ++++++++++ .../service/security/DefaultAuthorizer.java | 1 + .../data/policy/OntologyAuthorPolicy.json | 2 +- .../data/policy/OntologyReviewerPolicy.json | 2 +- .../ontology/OntologyShapeRulesTest.java | 174 ++++++ .../ontology/OntologyShapeValidationTest.java | 201 +++++++ .../rdf/OntologyReleaseExportFixture.java | 2 + .../rdf/OntologyReleaseProjectionTest.java | 2 +- .../rdf/OntologyReleaseShapeExportTest.java | 152 +++++ .../rdf/OntologyShaclRoundTripTest.java | 203 +++++++ .../org/openmetadata/schema/EntityLink.g4 | 1 + .../schema/api/data/createOntologyShape.json | 51 ++ .../schema/api/data/importOntologyShapes.json | 29 + .../api/data/ontologyShapeImportResult.json | 96 +++ .../schema/entity/data/ontologyShape.json | 104 ++++ .../type/nativeOntologyExportFormat.json | 4 +- .../schema/type/ontologyProfileViolation.json | 5 +- .../schema/type/ontologyShapeConstraint.json | 74 +++ .../resources/rdf/ontology/openmetadata.ttl | 12 + 48 files changed, 3523 insertions(+), 14 deletions(-) create mode 100644 docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeReleaseIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java create mode 100644 openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyShapeService.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyShapeRepository.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclVocabulary.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclWriter.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeMapper.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseShapeExportTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclRoundTripTest.java create mode 100644 openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyShape.json create mode 100644 openmetadata-spec/src/main/resources/json/schema/api/data/importOntologyShapes.json create mode 100644 openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeImportResult.json create mode 100644 openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyShape.json create mode 100644 openmetadata-spec/src/main/resources/json/schema/type/ontologyShapeConstraint.json diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql index 5d603c4caa68..71856cfa3971 100644 --- a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql @@ -1240,3 +1240,22 @@ DEALLOCATE PREPARE context_file_visibility_stmt; -- Flowable schema upgrades run after this migration and inherit the database default. Existing -- ACT_* tables are aligned to the same collation by FlowableCharsetMigration. ALTER DATABASE CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci; + +-- Shapes: SHACL node shapes of an ontology, each targeting one class and listing constraints on +-- its properties. They are working content, sealed into releases as SHAPE members. +-- ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints +CREATE TABLE IF NOT EXISTS ontology_shape_entity ( + id varchar(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.id'))) STORED NOT NULL, + name varchar(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.name'))) STORED NOT NULL, + fqnHash varchar(768) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + json json NOT NULL, + ontologyId varchar(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.ontology.id'))) STORED NOT NULL, + updatedAt bigint unsigned GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.updatedAt'))) STORED NOT NULL, + updatedBy varchar(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.updatedBy'))) STORED NOT NULL, + deleted tinyint(1) GENERATED ALWAYS AS (json_extract(json, '$.deleted')) STORED, + PRIMARY KEY (id), + UNIQUE KEY ontology_shape_fqn_hash_unique (fqnHash), + KEY ontology_shape_name_index (name), + KEY ontology_shape_listing_index (ontologyId, deleted, name, id), + KEY ontology_shape_deleted_index (deleted) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql index ae5a9d4cd6a9..697a7b4f013f 100644 --- a/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql @@ -938,3 +938,22 @@ ALTER TABLE mcp_pending_auth_requests ALTER TABLE context_file ADD COLUMN IF NOT EXISTS visibility VARCHAR(16) GENERATED ALWAYS AS (json -> 'shareConfig' ->> 'visibility') STORED; CREATE INDEX IF NOT EXISTS idx_context_file_visibility ON context_file (visibility); + +-- Shapes: SHACL node shapes of an ontology, each targeting one class and listing constraints on +-- its properties. They are working content, sealed into releases as SHAPE members. +-- ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints +CREATE TABLE IF NOT EXISTS ontology_shape_entity ( + id VARCHAR(36) GENERATED ALWAYS AS (json ->> 'id') STORED NOT NULL, + name VARCHAR(256) GENERATED ALWAYS AS (json ->> 'name') STORED NOT NULL, + fqnHash VARCHAR(768) NOT NULL, + json JSONB NOT NULL, + ontologyId VARCHAR(36) GENERATED ALWAYS AS (json -> 'ontology' ->> 'id') STORED NOT NULL, + updatedAt BIGINT GENERATED ALWAYS AS ((json ->> 'updatedAt')::bigint) STORED NOT NULL, + updatedBy VARCHAR(256) GENERATED ALWAYS AS (json ->> 'updatedBy') STORED NOT NULL, + deleted BOOLEAN GENERATED ALWAYS AS ((json ->> 'deleted')::boolean) STORED, + PRIMARY KEY (id), + CONSTRAINT ontology_shape_fqn_hash_unique UNIQUE (fqnHash) +); +CREATE INDEX IF NOT EXISTS ontology_shape_name_index ON ontology_shape_entity (name); +CREATE INDEX IF NOT EXISTS ontology_shape_listing_index ON ontology_shape_entity (ontologyId, deleted, name, id); +CREATE INDEX IF NOT EXISTS ontology_shape_deleted_index ON ontology_shape_entity (deleted); diff --git a/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md b/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md new file mode 100644 index 000000000000..9347a6f85451 --- /dev/null +++ b/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md @@ -0,0 +1,55 @@ +# Ontology shapes hold eight SHACL constraints, and report every other construct instead of refusing the file + +- **Status:** Accepted +- **Revisions:** v1 2026-11-21 (initial) +- **Deciders:** Ontology Studio team +- **Guard:** `OntologyShapeRulesTest`, `OntologyShaclRoundTripTest`, `OntologyShapeValidationTest`, `OntologyShapeResourceIT`, `IndependentOntologyShapeReleaseIT` +- **Related:** ADR:2026-10-14-ontology-definitions-have-independent-entity-storage, ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights + +## Context +An ontology states what exists, not what a well-formed instance of a class looks like. SHACL is the +standard way to say the second, and ontology files in the wild carry SHACL node shapes next to the +OWL. The ontology release already reserved the member kind `SHAPE`, but nothing wrote it. Importing +a SHACL file whole is out of reach: SHACL has logical combinations, SPARQL constraints, property +paths and recursion, and a stored model that held all of that would need a validator of its own. + +## Decision +- A shape is a native ontology entity, `ontologyShape`, owned by one ontology and living in its + working draft like an axiom. It has a `targetConcept` (the full IRI of one class), a `severity` + (`Violation`, `Warning` or `Info`, as SHACL defines them) and an ordered list of constraints. +- A constraint has an `id` that is unique inside its shape and does not change when the constraint + is edited, a `path` that is the full IRI of one property, and any of `minCount`, `maxCount`, + `classIri` (SHACL `sh:class`), `datatypeIri` (`sh:datatype`), `minInclusive`, `maxInclusive`, + `in` and `pattern`. At least one must be present. These eight are the supported constraints. +- A shape is sealed in a release as a `SHAPE` member with the fields `targetConcept`, `severity` + and `constraints`, and the release digest covers it. A release without shapes has the digest it + had before. +- Release validation fails a shape whose target class or constraint path is not declared in the + release (`UNDECLARED_CLASS`, `UNDECLARED_PROPERTY`), whose `classIri` names a class that is not + declared (`UNDECLARED_CLASS`), whose `minCount` is above its `maxCount` + (`SHAPE_CARDINALITY_CONFLICT`), whose `in` list is empty (`SHAPE_EMPTY_VALUE_LIST`), or that is + otherwise malformed, such as a repeated constraint id or a pattern that does not compile + (`SHAPE_INVALID_CONSTRAINT`). Saving a shape applies the checks that need no other definition; + the checks that name other definitions wait for the release, because the class or property may + be declared a moment later. +- SHACL is a Turtle export of the shapes (`format=shacl`) and an import (`POST + /v1/ontologyShapes/import`). Each shape is an `sh:NodeShape` named by `sh:name`, with one + `sh:property` node per constraint. The node is named by its shape's IRI, `#` and the constraint + id, so a re-import reads every id back, and `sh:order` keeps the authored order. A node that is + not named that way, such as a blank node in a file from elsewhere, gets `c1`, `c2` and so on in + the order the constraints are held. +- Import takes every shape with one IRI `sh:targetClass` and the supported constraints of its + property nodes with a single-IRI `sh:path`. Every other SHACL construct, such as `sh:or`, + `sh:sparql`, `sh:qualifiedValueShape`, `sh:closed`, a path that is not a single IRI, or a + second kind of target, is named in the response and left out. It is a report, not an error. A + shape the rules above would refuse fails the whole request before anything is written. +- Shapes are left out of the OWL graph projection and of the reference index. They do not change + what the ontology means, so the graph and its disjointness and hierarchy checks stay as they were. + +## Consequences +A file with constructs the model does not hold still gives its owner the supported part at once, +and the response lists what to do by hand, which refusing the file would not. The cost is that the +imported shape can be weaker than the file's: the report is the only record of the difference, and +exporting does not bring the lost constructs back. Widening the model later adds fields and +reports fewer constructs; it does not change a stored id. A literal written with no datatype and +one written as `xsd:string` are the same RDF term, so an export and an import give the first form. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeReleaseIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeReleaseIT.java new file mode 100644 index 000000000000..9e1933d2fd96 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeReleaseIT.java @@ -0,0 +1,332 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.ImportOntologyShapes; +import org.openmetadata.schema.api.data.OntologyValidationError; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.EntityStatus; +import org.openmetadata.schema.type.OntologyProfileViolationCode; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; + +/** A shape through capture, review, activation, export and release validation. */ +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyShapeReleaseIT extends BaseOntologyApprovalIT { + private static final HttpClient HTTP = HttpClient.newHttpClient(); + + @Test + void aShapeSurvivesCaptureReviewAndActivationWithTheSameConstraintIds(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final OntologyShape draft = client.ontologyShapes().create(shape(ontology, "PersonShape")); + + final OntologyRelease release = activate(ns, ontology); + + final JsonNode sealed = sealedShapes(release); + assertEquals(1, sealed.size()); + final JsonNode member = sealed.get(0); + assertEquals(draft.getId().toString(), member.path("memberId").asText()); + assertEquals(draft.getId().toString(), member.path("payload").path("id").asText()); + assertEquals( + List.of("has-name", "address-class"), ids(member.path("payload").path("constraints"))); + assertEquals( + model("Person"), URI.create(member.path("payload").path("targetConcept").asText())); + assertEquals("Info", member.path("payload").path("severity").asText()); + assertTrue(client.ontologyReleases().structure(release.getId()).getValid()); + assertEquals( + EntityStatus.APPROVED, client.ontologyReleases().get(release.getId()).getEntityStatus()); + } + + @Test + void editingTheWorkingShapeAfterActivationDoesNotChangeTheSealedOne(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final CreateOntologyShape request = shape(ontology, "PersonShape"); + client.ontologyShapes().create(request); + final OntologyRelease release = activate(ns, ontology); + + request.getConstraints().getFirst().setId("renamed"); + client.ontologyShapes().upsert(request); + + assertEquals( + List.of("has-name", "address-class"), + ids(sealedShapes(release).get(0).path("payload").path("constraints"))); + } + + @Test + void aShapeNamingADefinitionTheOntologyLacksBlocksCaptureUntilItIsDeclared( + final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Person", model("Person")); + client + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("name") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("name")) + .withKind(OntologyPropertyKind.DATA)); + final CreateOntologyShape request = shape(ontology, "PersonShape"); + final OntologyShape stored = client.ontologyShapes().create(request); + + final OntologyValidationError error = refusedCapture(ontology); + + assertEquals( + List.of( + OntologyProfileViolationCode.UNDECLARED_PROPERTY + " /constraints/1/path", + OntologyProfileViolationCode.UNDECLARED_CLASS + " /constraints/1/classIri"), + error.getViolations().stream() + .map(issue -> issue.getViolation().getCode() + " " + issue.getViolation().getPath()) + .toList()); + assertEquals(stored.getId(), error.getViolations().getFirst().getMemberId()); + + declareClass(ontology, "Address", model("Address")); + client + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("livesAt") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("livesAt")) + .withKind(OntologyPropertyKind.OBJECT)); + assertNotNull(capture(ontology).getId()); + } + + @Test + void aShapeTargetingAClassTheOntologyLacksBlocksCapture(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final CreateOntologyShape request = + shape(ontology, "GhostShape").withTargetConcept(model("Ghost")); + client.ontologyShapes().create(request); + + final OntologyValidationError error = refusedCapture(ontology); + + assertEquals( + List.of(OntologyProfileViolationCode.UNDECLARED_CLASS + " /targetConcept"), + error.getViolations().stream() + .map(issue -> issue.getViolation().getCode() + " " + issue.getViolation().getPath()) + .toList()); + } + + @Test + void aSealedReleaseExportsItsShapesAsShaclThatImportsBackWithEveryId(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "shapeExportSource"); + final Ontology fresh = createOntology(ns, "shapeExportFresh"); + declareModel(ontology); + client.ontologyShapes().create(shape(ontology, "PersonShape")); + final OntologyRelease release = activate(ns, ontology); + + final String shacl = + client + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologyReleases/" + release.getId() + "/export?format=shacl", + null, + RequestOptions.builder().header("Accept", "*/*").build()); + final var imported = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(fresh.getFullyQualifiedName()) + .withContent(shacl)); + + assertEquals(List.of(), imported.getUnsupported()); + assertEquals( + List.of("has-name", "address-class"), imported.getShapes().getFirst().getConstraintIds()); + final String turtle = + client + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologyReleases/" + release.getId() + "/export?format=turtle", + null, + RequestOptions.builder().header("Accept", "*/*").build()); + assertTrue(!turtle.contains("NodeShape"), "the OWL graph does not carry shapes"); + } + + @Test + void aConsumerReadsTheSealedShapesAndNoWorkingDraftOnes(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareModel(ontology); + client.ontologyShapes().create(shape(ontology, "PersonShape")); + final OntologyRelease release = activate(ns, ontology); + final String name = ns.shortPrefix("shapeReleaseConsumer"); + final User consumer = + ns.trackRoot( + Entity.USER, + client + .users() + .create( + new CreateUser() + .withName(name) + .withEmail(name + "@test.om.org") + .withDescription("v7 user") + .withRoles(List.of(client.roles().getByName("DataConsumer").getId())))); + + assertEquals( + 200, status(consumer, "/v1/ontologyReleases/" + release.getId() + "/members/shape")); + assertEquals( + 200, status(consumer, "/v1/ontologyReleases/" + release.getId() + "/export?format=shacl")); + assertEquals(403, status(consumer, "/v1/ontologyShapes?ontologyId=" + ontology.getId())); + assertEquals( + 403, status(consumer, "/v1/ontologies/" + ontology.getId() + "/export?format=shacl")); + } + + private static JsonNode sealedShapes(final OntologyRelease release) { + final String body = + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologyReleases/" + release.getId() + "/members/shape", + null, + RequestOptions.builder().header("Accept", "application/json").build()); + return JsonUtils.readTree(body).path("data"); + } + + private static List ids(final JsonNode constraints) { + final List ids = new ArrayList<>(); + constraints.forEach(constraint -> ids.add(constraint.path("id").asText())); + return ids; + } + + private static void declareModel(final Ontology ontology) { + declareClass(ontology, "Person", model("Person")); + declareClass(ontology, "Address", model("Address")); + SdkClients.adminClient() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("name") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("name")) + .withKind(OntologyPropertyKind.DATA)); + SdkClients.adminClient() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("livesAt") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("livesAt")) + .withKind(OntologyPropertyKind.OBJECT)); + } + + private static CreateOntologyShape shape(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("Shape of a person") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(model("Person")) + .withSeverity(OntologyShapeSeverity.INFO) + .withConstraints( + new ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("has-name") + .withPath(model("name")) + .withMinCount(1), + new OntologyShapeConstraint() + .withId("address-class") + .withPath(model("livesAt")) + .withClassIri(model("Address"))))); + } + + private static URI model(final String name) { + return URI.create("https://example.org/model/" + name); + } + + private static OntologyValidationError refusedCapture(final Ontology ontology) { + final long revision = + SdkClients.adminClient().ontologies().state(ontology.getId()).getWorkingRevision(); + try { + final HttpResponse response = + HTTP.send( + HttpRequest.newBuilder() + .uri( + URI.create( + SdkClients.getServerUrl() + + "/v1/ontologies/" + + ontology.getId() + + "/releases")) + .header("Authorization", "Bearer " + SdkClients.getAdminToken()) + .header("Content-Type", "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + "{\"expectedWorkingRevision\":" + revision + "}")) + .build(), + HttpResponse.BodyHandlers.ofString()); + assertEquals(400, response.statusCode(), response.body()); + return JsonUtils.readValue(response.body(), OntologyValidationError.class); + } catch (java.io.IOException | InterruptedException e) { + throw new IllegalStateException(e); + } + } + + private static int status(final User user, final String path) { + final String token = + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 600); + try { + return HTTP.send( + HttpRequest.newBuilder() + .uri(URI.create(SdkClients.getServerUrl() + path)) + .header("Authorization", "Bearer " + token) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()) + .statusCode(); + } catch (java.io.IOException | InterruptedException e) { + throw new IllegalStateException(path, e); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java new file mode 100644 index 000000000000..2527d0ebd142 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java @@ -0,0 +1,439 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.ImportOntologyShapes; +import org.openmetadata.schema.api.data.OntologyShapeImportAction; +import org.openmetadata.schema.api.data.OntologyShapeImportResult; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.models.ListParams; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; + +/** Persistence, SHACL exchange and authorization of ontology shapes in a working draft. */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +public class OntologyShapeResourceIT extends BaseOntologyApprovalIT { + private static final HttpClient HTTP = HttpClient.newHttpClient(); + private static final String MODEL = "https://example.org/model/"; + private static final URI PERSON = URI.create(MODEL + "Person"); + private static final URI NAME = URI.create(MODEL + "name"); + private static final URI AGE = URI.create(MODEL + "age"); + private static final URI XSD_INTEGER = URI.create("http://www.w3.org/2001/XMLSchema#integer"); + + @Test + void aShapeIsCreatedReadUpdatedAndDeletedWithItsConstraintsIntact(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + final CreateOntologyShape request = shapeRequest(ontology, "PersonShape"); + + final OntologyShape created = client.ontologyShapes().create(request); + final OntologyShape stored = client.ontologyShapes().get(created.getId().toString()); + + assertEquals(PERSON, stored.getTargetConcept()); + assertEquals(OntologyShapeSeverity.VIOLATION, stored.getSeverity()); + assertEquals( + List.of("name-count", "age-range", "name-values"), + stored.getConstraints().stream().map(OntologyShapeConstraint::getId).toList()); + assertEquals( + JsonUtils.pojoToJson(request.getConstraints()), + JsonUtils.pojoToJson(stored.getConstraints())); + assertEquals(ontology.getFullyQualifiedName() + ".PersonShape", stored.getFullyQualifiedName()); + + request.setSeverity(OntologyShapeSeverity.WARNING); + request.getConstraints().getFirst().setMaxCount(2); + final OntologyShape updated = client.ontologyShapes().upsert(request); + + assertEquals(created.getId(), updated.getId()); + assertEquals(OntologyShapeSeverity.WARNING, updated.getSeverity()); + assertEquals("name-count", updated.getConstraints().getFirst().getId()); + assertEquals(Integer.valueOf(2), updated.getConstraints().getFirst().getMaxCount()); + + client.ontologyShapes().delete(created.getId().toString()); + assertTrue(client.ontologyShapes().get(created.getId().toString(), null, "all").getDeleted()); + } + + @Test + void aShapeThatCanNeverBeSatisfiedIsRefusedWhenItIsSaved(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + + final var cardinality = shapeRequest(ontology, "Cardinality"); + cardinality.getConstraints().getFirst().withMinCount(3).withMaxCount(2); + final var emptyList = shapeRequest(ontology, "EmptyList"); + emptyList.getConstraints().get(2).setIn(List.of()); + final var repeatedId = shapeRequest(ontology, "RepeatedId"); + repeatedId.getConstraints().get(1).setId("name-count"); + final var relative = shapeRequest(ontology, "Relative"); + relative.getConstraints().getFirst().setPath(URI.create("name")); + + assertRefused(client, cardinality, "minCount 3 is above maxCount 2"); + assertRefused(client, emptyList, "An in list names at least one value"); + assertRefused(client, repeatedId, "A constraint id is unique within its shape: name-count"); + assertRefused(client, relative, "An IRI must be absolute: name"); + assertEquals( + 0, + client + .ontologyShapes() + .list(new ListParams().addFilter("ontologyId", ontology.getId().toString())) + .getData() + .size()); + } + + @Test + void exportedShaclImportsIntoAFreshOntologyWithEveryShapeAndConstraintId(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology source = createOntology(ns, "shapeSource"); + final Ontology target = createOntology(ns, "shapeTarget"); + final var first = client.ontologyShapes().create(shapeRequest(source, "PersonShape")); + final var second = + client + .ontologyShapes() + .create( + new CreateOntologyShape() + .withName("EmptyShape") + .withDisplayName("EmptyShape") + .withDescription("No constraints yet") + .withOntology(source.getFullyQualifiedName()) + .withTargetConcept(URI.create(MODEL + "Other")) + .withSeverity(OntologyShapeSeverity.INFO)); + + final String shacl = exportDraft(source); + final OntologyShapeImportResult imported = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(target.getFullyQualifiedName()) + .withContent(shacl)); + + assertEquals(List.of(), imported.getUnsupported()); + assertEquals( + List.of("EmptyShape", "PersonShape"), + imported.getShapes().stream().map(shape -> shape.getName()).toList()); + assertTrue( + imported.getShapes().stream() + .allMatch(s -> s.getAction() == OntologyShapeImportAction.CREATED)); + final OntologyShape copy = + client.ontologyShapes().getByName(target.getFullyQualifiedName() + ".PersonShape"); + assertEquals( + JsonUtils.pojoToJson(first.getConstraints()), JsonUtils.pojoToJson(copy.getConstraints())); + assertEquals(first.getTargetConcept(), copy.getTargetConcept()); + assertEquals(first.getSeverity(), copy.getSeverity()); + final OntologyShape copyOfSecond = + client.ontologyShapes().getByName(target.getFullyQualifiedName() + ".EmptyShape"); + assertEquals(second.getTargetConcept(), copyOfSecond.getTargetConcept()); + assertEquals(OntologyShapeSeverity.INFO, copyOfSecond.getSeverity()); + + final OntologyShapeImportResult again = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(target.getFullyQualifiedName()) + .withContent(shacl)); + assertTrue( + again.getShapes().stream() + .allMatch(s -> s.getAction() == OntologyShapeImportAction.UPDATED), + "importing the same file again updates by name"); + } + + @Test + void aFileWithUnsupportedConstructsImportsItsSupportedPartsAndNamesTheRest( + final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + final String file = + """ + @prefix sh: . + @prefix ex: . + + ex:PersonShape a sh:NodeShape ; + sh:targetClass ex:Person ; + sh:closed true ; + sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:maxCount 1 ; sh:minLength 2 ] ; + sh:property [ sh:path [ sh:inversePath ex:knows ] ; sh:minCount 1 ] ; + sh:or ( [ sh:class ex:A ] [ sh:class ex:B ] ) . + """; + + final OntologyShapeImportResult result = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(file)); + + assertEquals( + List.of("sh:closed", "sh:minLength", "sh:or", "sh:path"), + result.getUnsupported().stream() + .map(item -> item.getConstruct()) + .distinct() + .sorted() + .toList()); + final OntologyShape stored = + client.ontologyShapes().getByName(ontology.getFullyQualifiedName() + ".PersonShape"); + assertEquals(1, stored.getConstraints().size()); + assertEquals(NAME, stored.getConstraints().getFirst().getPath()); + assertEquals(Integer.valueOf(1), stored.getConstraints().getFirst().getMinCount()); + assertEquals(Integer.valueOf(1), stored.getConstraints().getFirst().getMaxCount()); + assertEquals(List.of("c1"), result.getShapes().getFirst().getConstraintIds()); + } + + @Test + void aDryRunImportWritesNothingAndAnUnsatisfiableFileWritesNothing(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + final String valid = + """ + @prefix sh: . + @prefix ex: . + ex:A a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] . + """; + final String refused = + """ + @prefix sh: . + @prefix ex: . + ex:A a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] . + ex:B a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 3 ; sh:maxCount 2 ] . + """; + + final var dry = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(valid) + .withDryRun(true)); + final OpenMetadataException failure = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(refused))); + + assertTrue(dry.getDryRun()); + assertEquals( + List.of("A:CREATED"), + dry.getShapes().stream().map(s -> s.getName() + ":" + s.getAction()).toList()); + assertEquals(400, failure.getStatusCode()); + assertTrue(failure.getMessage().contains("minCount 3 is above maxCount 2")); + assertEquals( + 0, + client + .ontologyShapes() + .list(new ListParams().addFilter("ontologyId", ontology.getId().toString())) + .getData() + .size()); + } + + @Test + void textThatIsNotTurtleIsRefused(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + + final OpenMetadataException failure = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent("this is { not turtle"))); + + assertEquals(400, failure.getStatusCode()); + } + + @Test + void aConsumerCannotWriteOrReadTheWorkingDraftShapesAndAnAuthorCan(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(shapeRequest(ontology, "PersonShape")); + final User consumer = createUser(ns, "shapeConsumer", "DataConsumer"); + final User author = createUser(ns, "shapeAuthor", "OntologyAuthor"); + final String id = ontology.getId().toString(); + final String body = JsonUtils.pojoToJson(shapeRequest(ontology, "ByCaller")); + final String importBody = + JsonUtils.pojoToJson( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent( + "@prefix sh: . " + + " a sh:NodeShape ; sh:targetClass ; " + + "sh:property [ sh:path ; sh:minCount 1 ] .")); + + assertEquals(403, status(consumer, "GET", "/v1/ontologyShapes?ontologyId=" + id, null)); + assertEquals(403, status(consumer, "GET", "/v1/ontologyShapes", null)); + assertEquals( + 403, status(consumer, "GET", "/v1/ontologies/" + id + "/export?format=shacl", null)); + assertEquals(403, status(consumer, "POST", "/v1/ontologyShapes", body)); + assertEquals(403, status(consumer, "PUT", "/v1/ontologyShapes", body)); + assertEquals(403, status(consumer, "POST", "/v1/ontologyShapes/import", importBody)); + assertEquals( + 403, + status( + consumer, + "PATCH", + "/v1/ontologyShapes/" + shape.getId(), + "[{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"changed\"}]")); + assertEquals(403, status(consumer, "DELETE", "/v1/ontologyShapes/" + shape.getId(), null)); + + assertEquals(200, status(author, "GET", "/v1/ontologyShapes?ontologyId=" + id, null)); + assertEquals(200, status(author, "GET", "/v1/ontologies/" + id + "/export?format=shacl", null)); + assertEquals(201, status(author, "POST", "/v1/ontologyShapes", body)); + assertEquals(200, status(author, "POST", "/v1/ontologyShapes/import", importBody)); + assertEquals( + 200, + status(SdkClients.getAdminToken(), "GET", "/v1/ontologyShapes?ontologyId=" + id, null)); + } + + private static void assertRefused( + final OpenMetadataClient client, final CreateOntologyShape request, final String message) { + final OpenMetadataException failure = + assertThrows(OpenMetadataException.class, () -> client.ontologyShapes().create(request)); + assertEquals(400, failure.getStatusCode(), failure.getMessage()); + assertTrue(failure.getMessage().contains(message), failure.getMessage()); + assertFalse(failure.getMessage().isBlank()); + } + + private static CreateOntologyShape shapeRequest(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("A person has one name and a sensible age") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(PERSON) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + new java.util.ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("name-count") + .withPath(NAME) + .withMinCount(1) + .withMaxCount(1), + new OntologyShapeConstraint() + .withId("age-range") + .withPath(AGE) + .withDatatypeIri(XSD_INTEGER) + .withMinInclusive( + new OntologyLiteral().withValue("0").withDatatypeIri(XSD_INTEGER)) + .withMaxInclusive( + new OntologyLiteral().withValue("150").withDatatypeIri(XSD_INTEGER)), + new OntologyShapeConstraint() + .withId("name-values") + .withPath(NAME) + .withPattern("^[A-Z]") + .withIn( + List.of( + new OntologyShapeValue() + .withLiteral(new OntologyLiteral().withValue("Alice")), + new OntologyShapeValue() + .withLiteral(new OntologyLiteral().withValue("Bob"))))))); + } + + private static String exportDraft(final Ontology ontology) { + return SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologies/" + ontology.getId() + "/export?format=shacl", + null, + RequestOptions.builder().header("Accept", "*/*").build()); + } + + private static User createUser(final TestNamespace ns, final String base, final String role) { + final String name = ns.shortPrefix(base); + return ns.trackRoot( + Entity.USER, + SdkClients.adminClient() + .users() + .create( + new CreateUser() + .withName(name) + .withEmail(name + "@test.om.org") + .withDescription("v7 user") + .withRoles(List.of(SdkClients.adminClient().roles().getByName(role).getId())))); + } + + private static int status( + final User user, final String method, final String path, final String body) { + return status( + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 600), + method, + path, + body); + } + + private static int status( + final String token, final String method, final String path, final String body) { + final String contentType = + "PATCH".equals(method) ? "application/json-patch+json" : "application/json"; + try { + return HTTP.send( + HttpRequest.newBuilder() + .uri(URI.create(SdkClients.getServerUrl() + path)) + .header("Authorization", "Bearer " + token) + .header("Content-Type", contentType) + .timeout(Duration.ofSeconds(60)) + .method( + method, + body == null + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofString(body)) + .build(), + HttpResponse.BodyHandlers.ofString()) + .statusCode(); + } catch (java.io.IOException | InterruptedException e) { + throw new IllegalStateException(method + " " + path, e); + } + } +} diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java index 3a681d3808fd..b6b05d60ea65 100644 --- a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java @@ -65,6 +65,7 @@ import org.openmetadata.sdk.services.ontology.OntologyReasoningService; import org.openmetadata.sdk.services.ontology.OntologyReleaseService; import org.openmetadata.sdk.services.ontology.OntologyService; +import org.openmetadata.sdk.services.ontology.OntologyShapeService; import org.openmetadata.sdk.services.ontology.RelationshipTypeService; import org.openmetadata.sdk.services.policies.PolicyService; import org.openmetadata.sdk.services.search.SearchAPI; @@ -146,6 +147,7 @@ public class OpenMetadataClient { // Ontology private final RelationshipTypeService relationshipTypes; private final OntologyAxiomService ontologyAxioms; + private final OntologyShapeService ontologyShapes; private final OntologyService ontologies; private final OntologyConceptService ontologyConcepts; private final OntologyPropertyService ontologyProperties; @@ -291,6 +293,7 @@ public OpenMetadataClient(OpenMetadataConfig config) { // Initialize Ontology services this.relationshipTypes = new RelationshipTypeService(httpClient); this.ontologyAxioms = new OntologyAxiomService(httpClient); + this.ontologyShapes = new OntologyShapeService(httpClient); this.ontologies = new OntologyService(httpClient); this.ontologyConcepts = new OntologyConceptService(httpClient); this.ontologyProperties = new OntologyPropertyService(httpClient); @@ -512,6 +515,10 @@ public OntologyAxiomService ontologyAxioms() { return ontologyAxioms; } + public OntologyShapeService ontologyShapes() { + return ontologyShapes; + } + public OntologyService ontologies() { return ontologies; } diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyShapeService.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyShapeService.java new file mode 100644 index 000000000000..f3b7ab56bd85 --- /dev/null +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyShapeService.java @@ -0,0 +1,49 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.sdk.services.ontology; + +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.ImportOntologyShapes; +import org.openmetadata.schema.api.data.OntologyShapeImportResult; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.services.EntityServiceBase; + +/** Typed SDK client for ontology shapes and their SHACL import. */ +public final class OntologyShapeService extends EntityServiceBase { + public OntologyShapeService(final HttpClient httpClient) { + super(httpClient, "/v1/ontologyShapes"); + } + + public OntologyShape create(final CreateOntologyShape request) throws OpenMetadataException { + return httpClient.execute(HttpMethod.POST, basePath, request, OntologyShape.class); + } + + public OntologyShape upsert(final CreateOntologyShape request) throws OpenMetadataException { + return httpClient.execute(HttpMethod.PUT, basePath, request, OntologyShape.class); + } + + public OntologyShapeImportResult importShapes(final ImportOntologyShapes request) + throws OpenMetadataException { + return httpClient.execute( + HttpMethod.POST, basePath + "/import", request, OntologyShapeImportResult.class); + } + + @Override + protected Class getEntityClass() { + return OntologyShape.class; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/Entity.java b/openmetadata-service/src/main/java/org/openmetadata/service/Entity.java index dee493cb8b03..6e7eafdf5b7b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/Entity.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/Entity.java @@ -225,6 +225,7 @@ public final class Entity { public static final String ONTOLOGY_PROPERTY = "ontologyProperty"; public static final String ONTOLOGY_RELEASE = "ontologyRelease"; public static final String ONTOLOGY_AXIOM = "ontologyAxiom"; + public static final String ONTOLOGY_SHAPE = "ontologyShape"; public static final String ONTOLOGY_CHANGE_SET = "ontologyChangeSet"; public static final String TAG = "tag"; public static final String CLASSIFICATION = "classification"; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ApprovalGate.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ApprovalGate.java index c78c1a2fcac9..21a92e901363 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ApprovalGate.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ApprovalGate.java @@ -88,6 +88,7 @@ public final class ApprovalGate { Entity.ONTOLOGY_CONCEPT, Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_AXIOM, + Entity.ONTOLOGY_SHAPE, Entity.ONTOLOGY_RELEASE); private ApprovalGate() {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java index 488c39ae64e9..19bae6113333 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java @@ -54,6 +54,7 @@ public class ListFilter extends Filter { private static final String TASK_STATUS_GROUP_ACTIVE = "active"; private static final String TASK_STATUS_GROUP_CLOSED = "closed"; private static final String ONTOLOGY_AXIOM_TABLE = "ontology_axiom_entity"; + private static final String ONTOLOGY_SHAPE_TABLE = "ontology_shape_entity"; private static final String ONTOLOGY_CHANGE_SET_TABLE = "ontology_change_set_entity"; private static final String ONTOLOGY_CONCEPT_TABLE = "ontology_concept_entity"; private static final String ONTOLOGY_PROPERTY_TABLE = "ontology_property_entity"; @@ -200,6 +201,7 @@ private String getOntologyIdCondition(final String tableName) { if (!nullOrEmpty(ontologyId) && (tableMatches(tableName, ONTOLOGY_CONCEPT_TABLE) || tableMatches(tableName, ONTOLOGY_AXIOM_TABLE) + || tableMatches(tableName, ONTOLOGY_SHAPE_TABLE) || tableMatches(tableName, ONTOLOGY_PROPERTY_TABLE) || tableMatches(tableName, ONTOLOGY_RELEASE_TABLE))) { queryParams.put("ontologyIdParam", ontologyId); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyShapeRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyShapeRepository.java new file mode 100644 index 000000000000..c8b2fe37fca5 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyShapeRepository.java @@ -0,0 +1,45 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.jdbi3; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.List; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyShapeRules; +import org.openmetadata.service.resources.ontology.OntologyShapeResource; + +@Repository +public class OntologyShapeRepository extends OntologyEntityRepository { + public OntologyShapeRepository() { + super( + Entity.ONTOLOGY_SHAPE, + OntologyShape.class, + Entity.getCollectionDAO().ontologyShapeDAO(), + OntologyShapeResource.COLLECTION_PATH, + "ontology,targetConcept,severity,constraints"); + } + + @Override + protected void validateDefinition(final OntologyShape entity) { + requireAbsoluteIri(entity.getTargetConcept(), "targetConcept"); + if (entity.getSeverity() == null) { + entity.setSeverity(OntologyShapeSeverity.VIOLATION); + } + entity.setConstraints(List.copyOf(listOrEmpty(entity.getConstraints()))); + OntologyShapeRules.requireValid(entity); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java index 95575117329f..5284ffd523a7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java @@ -21,6 +21,7 @@ import org.openmetadata.schema.entity.data.Ontology; import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.utils.JsonUtils; @@ -75,6 +76,9 @@ void requireValid(final UUID ontologyId, final List changes) { final var context = new Context(ontologyId, true, false); final List changedRules = new ArrayList<>(); for (final var change : changes) { + if (isShape(change)) { + continue; + } if (!structure(change.before()).equals(structure(change.after()))) { if (change.after() != null) { context.add(change.after(), true); @@ -185,6 +189,11 @@ private void requireNotADuplicate(final OntologyAxiom proposed) { requireNoDuplicate(rules, Set.of(proposed.getId())); } + /** Shapes state what instances must look like; they add nothing the class model depends on. */ + private static boolean isShape(final Change change) { + return change.before() instanceof OntologyShape || change.after() instanceof OntologyShape; + } + private static ObjectNode structure(final OntologyDefinition value) { return value == null || value instanceof Ontology ? JsonUtils.getObjectMapper().createObjectNode() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java index cadcd1518de3..10aa7649a09c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java @@ -37,6 +37,7 @@ import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.entity.data.RelationshipType; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlQuery; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlUpdate; @@ -73,6 +74,9 @@ public interface RdfInfraDAOs { @CreateSqlObject OntologyAxiomDAO ontologyAxiomDAO(); + @CreateSqlObject + OntologyShapeDAO ontologyShapeDAO(); + @CreateSqlObject OntologyChangeSetDAO ontologyChangeSetDAO(); @@ -257,6 +261,23 @@ default String getNameHashColumn() { } } + interface OntologyShapeDAO extends OntologyMemberDAO { + @Override + default String getTableName() { + return "ontology_shape_entity"; + } + + @Override + default Class getEntityClass() { + return OntologyShape.class; + } + + @Override + default String getNameHashColumn() { + return "fqnHash"; + } + } + interface OntologyChangeSetDAO extends EntityDAO { @Override default String getTableName() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java index 55dea6365ddb..5992e2fd4fd0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java @@ -12,6 +12,7 @@ import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyExpression; import org.openmetadata.schema.type.OntologyLiteral; import org.openmetadata.schema.type.OntologyReference; @@ -28,7 +29,9 @@ public final class OntologyReferences { private OntologyReferences() {} public static List collect(final OntologyDefinition entity) { - if (Boolean.TRUE.equals(entity.getDeleted()) || entity instanceof Ontology) { + if (Boolean.TRUE.equals(entity.getDeleted()) + || entity instanceof Ontology + || entity instanceof OntologyShape) { return List.of(); } final OntologyReferences references = new OntologyReferences(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java index 5c397695c903..2000e5aab734 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java @@ -8,6 +8,7 @@ import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.utils.JsonUtils; /** The explicit ontology-release-v1 content contract, independent of live entity metadata. */ @@ -62,6 +63,7 @@ private static List semanticFields(final OntologyDefinition definition) "targetIri", "literal", "provenance"); + case OntologyShape ignored -> List.of("targetConcept", "severity", "constraints"); default -> throw new IllegalArgumentException( "Unsupported ontology content: " + definition.getClass()); }; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseReader.java index 8f612147c72c..60180129273d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseReader.java @@ -13,6 +13,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.schema.utils.JsonUtils; @@ -119,7 +120,8 @@ public static OntologyDefinition definition(final OntologyReleaseMember member) case CONCEPT -> OntologyConcept.class; case PROPERTY -> OntologyProperty.class; case AXIOM -> OntologyAxiom.class; - default -> throw new BadRequestException( + case SHAPE -> OntologyShape.class; + case ASSOCIATION -> throw new BadRequestException( "Unsupported ontology release member: " + member.getMemberKind()); }; final var value = JsonUtils.convertValueLenient(member.getPayload(), type); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java new file mode 100644 index 000000000000..abae12031e81 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java @@ -0,0 +1,202 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyProfileViolation; +import org.openmetadata.schema.type.OntologyProfileViolationCode; +import org.openmetadata.schema.type.OntologyProfileViolationSeverity; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.service.exception.BadRequestException; + +/** + * The checks a shape passes on its own, without the ontology it belongs to: identity of its + * constraints, the supported constraint set, and values that cannot be satisfied. Whether the + * classes and properties it names exist is a question for a release. + */ +public final class OntologyShapeRules { + private static final Pattern CONSTRAINT_ID = Pattern.compile("^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"); + + private OntologyShapeRules() {} + + public static List validate(final OntologyShape shape) { + final List findings = new ArrayList<>(); + requireAbsolute(findings, shape.getTargetConcept(), "/targetConcept"); + final Set ids = new HashSet<>(); + final List constraints = listOrEmpty(shape.getConstraints()); + for (int index = 0; index < constraints.size(); index++) { + final OntologyShapeConstraint constraint = constraints.get(index); + final String path = "/constraints/" + index; + if (constraint == null) { + add(findings, OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, path, "Empty entry"); + } else { + validate(findings, constraint, path, ids); + } + } + return findings; + } + + public static void requireValid(final OntologyShape shape) { + final List findings = validate(shape); + if (!findings.isEmpty()) { + final OntologyProfileViolation first = findings.getFirst(); + throw new BadRequestException(first.getPath() + ": " + first.getMessage()); + } + } + + private static void validate( + final List findings, + final OntologyShapeConstraint constraint, + final String path, + final Set ids) { + if (constraint.getId() == null || !CONSTRAINT_ID.matcher(constraint.getId()).matches()) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path + "/id", + "A constraint id is 1 to 64 letters, digits, '_', '.' or '-', starting with a letter or digit"); + } else if (!ids.add(constraint.getId())) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path + "/id", + "A constraint id is unique within its shape: " + constraint.getId()); + } + requireAbsolute(findings, constraint.getPath(), path + "/path"); + requireAbsolute(findings, constraint.getClassIri(), path + "/classIri"); + requireAbsolute(findings, constraint.getDatatypeIri(), path + "/datatypeIri"); + if (!carriesAConstraint(constraint)) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path, + "A constraint states at least one of minCount, maxCount, classIri, datatypeIri, minInclusive, maxInclusive, in or pattern"); + } + validateCardinality(findings, constraint, path); + validateValues(findings, constraint, path); + validatePattern(findings, constraint, path); + } + + private static boolean carriesAConstraint(final OntologyShapeConstraint constraint) { + return constraint.getMinCount() != null + || constraint.getMaxCount() != null + || constraint.getClassIri() != null + || constraint.getDatatypeIri() != null + || constraint.getMinInclusive() != null + || constraint.getMaxInclusive() != null + || constraint.getIn() != null + || constraint.getPattern() != null; + } + + private static void validateCardinality( + final List findings, + final OntologyShapeConstraint constraint, + final String path) { + if (constraint.getMinCount() != null + && constraint.getMaxCount() != null + && constraint.getMinCount() > constraint.getMaxCount()) { + add( + findings, + OntologyProfileViolationCode.SHAPE_CARDINALITY_CONFLICT, + path, + "minCount " + + constraint.getMinCount() + + " is above maxCount " + + constraint.getMaxCount() + + ", so no value count satisfies the constraint"); + } + } + + private static void validateValues( + final List findings, + final OntologyShapeConstraint constraint, + final String path) { + if (constraint.getIn() == null) { + return; + } + if (constraint.getIn().isEmpty()) { + add( + findings, + OntologyProfileViolationCode.SHAPE_EMPTY_VALUE_LIST, + path + "/in", + "An in list names at least one value, or no value satisfies the constraint"); + } + for (int index = 0; index < constraint.getIn().size(); index++) { + final OntologyShapeValue value = constraint.getIn().get(index); + final boolean exactlyOne = + value != null && (value.getIri() == null) != (value.getLiteral() == null); + if (!exactlyOne) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path + "/in/" + index, + "An in value is exactly one of an iri or a literal"); + } else { + requireAbsolute(findings, value.getIri(), path + "/in/" + index + "/iri"); + } + } + } + + private static void validatePattern( + final List findings, + final OntologyShapeConstraint constraint, + final String path) { + if (constraint.getPattern() == null) { + return; + } + try { + Pattern.compile(constraint.getPattern()); + } catch (PatternSyntaxException invalid) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path + "/pattern", + "The pattern is not a valid regular expression: " + invalid.getDescription()); + } + } + + private static void requireAbsolute( + final List findings, final URI iri, final String path) { + if (iri != null && !iri.isAbsolute()) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path, + "An IRI must be absolute: " + iri); + } + } + + private static void add( + final List findings, + final OntologyProfileViolationCode code, + final String path, + final String message) { + findings.add( + new OntologyProfileViolation() + .withCode(code) + .withPath(path) + .withMessage(message) + .withSeverity(OntologyProfileViolationSeverity.ERROR)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java index f02aea4ad94e..c8f75c49a41f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java @@ -23,6 +23,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.type.OntologyProfileViolation; @@ -35,6 +36,7 @@ import org.openmetadata.schema.type.OntologyReleaseStructureIssue; import org.openmetadata.service.exception.OntologyValidationException; import org.openmetadata.service.rdf.OwlEntityDeclarations; +import org.openmetadata.service.rdf.OwlEntityDeclarations.EntityKind; /** Structural and OWL 2 DL checks for the supported authoring model; no logical reasoning. */ public final class OntologyStructureValidator { @@ -199,6 +201,7 @@ private static OntologyStructureValidator validateWorkingDefinitions( case OntologyConcept concept -> MemberKind.CONCEPT; case OntologyProperty property -> MemberKind.PROPERTY; case OntologyAxiom axiom -> MemberKind.AXIOM; + case OntologyShape shape -> MemberKind.SHAPE; default -> throw new IllegalArgumentException( "Unsupported ontology definition"); }), @@ -307,6 +310,7 @@ private void validate(final Definition definition) { OntologyProfileViolationCode.UNDECLARED_PROPERTY); } case OntologyAxiom axiom -> validateAxiom(definition.member(), axiom); + case OntologyShape shape -> validateShape(definition.member(), shape); default -> {} } } @@ -341,6 +345,41 @@ private void validateAxiom(final OntologyReleaseMember member, final OntologyAxi } } + /** + * A shape holds up only if the class it targets and every class and property it names exist in + * the same release, and its constraints can be satisfied at all. + */ + private void validateShape(final OntologyReleaseMember member, final OntologyShape shape) { + OntologyShapeRules.validate(shape).forEach(violation -> add(member, violation)); + requireClass(member, shape.getTargetConcept(), "/targetConcept"); + final var constraints = listOrEmpty(shape.getConstraints()); + for (int index = 0; index < constraints.size(); index++) { + final var constraint = constraints.get(index); + if (constraint == null) { + continue; + } + final String path = "/constraints/" + index; + if (constraint.getPath() != null) { + requireProperty(member, constraint.getPath(), null, path + "/path"); + } + if (constraint.getClassIri() != null) { + requireClass(member, constraint.getClassIri(), path + "/classIri"); + } + } + } + + private void requireClass(final OntologyReleaseMember member, final URI iri, final String path) { + if (iri != null + && !concepts.contains(iri.toString()) + && OwlEntityDeclarations.vocabularyKind(iri.toString()) != EntityKind.CLASS) { + add( + member, + OntologyProfileViolationCode.UNDECLARED_CLASS, + path, + "Declare or import the referenced class: " + iri); + } + } + private static boolean isIdentityAssertion(final OntologyAxiom axiom) { return axiom.getAxiomType() == OntologyAxiomType.OBJECT_PROPERTY_ASSERTION && axiom.getPropertyIri() != null diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java index 88c8641f78d2..412b37c16b0c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java @@ -33,7 +33,8 @@ private record Member(MemberKind kind, UUID id) {} new Source(MemberKind.ONTOLOGY, "ontology_entity", "id"), new Source(MemberKind.CONCEPT, "ontology_concept_entity", "ontologyId"), new Source(MemberKind.PROPERTY, "ontology_property_entity", "ontologyId"), - new Source(MemberKind.AXIOM, "ontology_axiom_entity", "ontologyId")); + new Source(MemberKind.AXIOM, "ontology_axiom_entity", "ontologyId"), + new Source(MemberKind.SHAPE, "ontology_shape_entity", "ontologyId")); private final CollectionDAO dao; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyWorkingSnapshot.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyWorkingSnapshot.java index 03ddd274ad0b..70a107b96e78 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyWorkingSnapshot.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyWorkingSnapshot.java @@ -57,7 +57,9 @@ public static OntologyWorkingSnapshot production() { MemberKind.PROPERTY, (OntologyEntityRepository) Entity.getEntityRepository(Entity.ONTOLOGY_PROPERTY), MemberKind.AXIOM, - (OntologyEntityRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM))); + (OntologyEntityRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM), + MemberKind.SHAPE, + (OntologyEntityRepository) Entity.getEntityRepository(Entity.ONTOLOGY_SHAPE))); } /** Reads under the `ontology_state` row lock, so the callback runs with every writer excluded. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyExportFormat.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyExportFormat.java index e99be96bebdc..eeb7b9ad962a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyExportFormat.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyExportFormat.java @@ -9,7 +9,8 @@ /** * Every serialization a captured ontology release can be exported as. The RDF graph formats reuse * {@link RdfSerializationFormat}; SKOS and SKOS-XL are concept projections written as Turtle, and - * CSV is the native ontology spreadsheet, which has no RDF serialization. + * CSV is the native ontology spreadsheet, which has no RDF serialization, and SHACL is the + * ontology's shapes written as Turtle. */ public enum OntologyExportFormat { TURTLE(NativeOntologyExportFormat.TURTLE, RdfSerializationFormat.TURTLE), @@ -18,7 +19,8 @@ public enum OntologyExportFormat { JSON_LD(NativeOntologyExportFormat.JSONLD, RdfSerializationFormat.JSON_LD), SKOS(NativeOntologyExportFormat.SKOS, RdfSerializationFormat.TURTLE), SKOS_XL(NativeOntologyExportFormat.SKOS_XL, RdfSerializationFormat.TURTLE), - CSV(NativeOntologyExportFormat.CSV, null); + CSV(NativeOntologyExportFormat.CSV, null), + SHACL(NativeOntologyExportFormat.SHACL, RdfSerializationFormat.TURTLE); private final NativeOntologyExportFormat wire; private final RdfSerializationFormat serialization; @@ -66,6 +68,11 @@ public boolean isGraph() { return serialization != null; } + /** Whether the export is the ontology's concepts, properties and axioms as one RDF graph. */ + public boolean isOntologyGraph() { + return isGraph() && this != SHACL; + } + /** The RDF serialization of a graph format; a CSV export has none. */ public RdfSerializationFormat serialization() { if (serialization == null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseExporter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseExporter.java index 11607f8408e3..bb4dbd008ff1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseExporter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseExporter.java @@ -11,6 +11,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.service.exception.BadRequestException; @@ -57,6 +58,9 @@ static String render( final OntologyReleaseExportOptions options, final BoundAssetLinks assetLinks) { requireSupported(format, options); + if (format == OntologyExportFormat.SHACL) { + return shacl(release, members); + } return format.isGraph() ? graph(release, members, format, options, assetLinks) : csv(release, members, options); @@ -64,7 +68,7 @@ static String render( private static void requireSupported( final OntologyExportFormat format, final OntologyReleaseExportOptions options) { - if (!format.isGraph() && options.getIncludeBoundAssets()) { + if (!format.isOntologyGraph() && options.getIncludeBoundAssets()) { throw new BadRequestException( "Bound asset links cannot be written to " + format.wire().value()); } @@ -124,6 +128,22 @@ private static void linkAssets( OntologyRdfVocabulary.BOUND_ASSET, model.createResource(asset.toString()))); } + private static String shacl( + final OntologyRelease release, final List members) { + final List shapes = + members.stream() + .filter(member -> member.getMemberKind() == MemberKind.SHAPE) + .map(member -> (OntologyShape) OntologyReleaseReader.definition(release, member)) + .toList(); + final Model model = + OntologyShaclWriter.write(OntologyReleaseReader.root(release, members), shapes); + try { + return RdfGraphSerializer.asString(model, RdfSerializationFormat.TURTLE); + } finally { + model.close(); + } + } + private static String csv( final OntologyRelease release, final List members, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseProjection.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseProjection.java index 38d8767aa6b8..6db2a8b186ee 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseProjection.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseProjection.java @@ -25,6 +25,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyConceptType; import org.openmetadata.schema.type.OntologyPropertyKind; import org.openmetadata.schema.type.OntologyReleaseMember; @@ -69,6 +70,7 @@ public Model build( members.stream() .map( member -> new Definition(member, OntologyReleaseReader.definition(release, member))) + .filter(definition -> !(definition.value() instanceof OntologyShape)) .toList(); if (!includeInverses) { withoutInverses(definitions); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java new file mode 100644 index 000000000000..8be381f14997 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java @@ -0,0 +1,556 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.rdf; + +import java.io.StringReader; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import org.apache.jena.rdf.model.Literal; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.ModelFactory; +import org.apache.jena.rdf.model.Property; +import org.apache.jena.rdf.model.RDFList; +import org.apache.jena.rdf.model.RDFNode; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.rdf.model.Statement; +import org.apache.jena.riot.Lang; +import org.apache.jena.riot.RDFDataMgr; +import org.apache.jena.riot.RiotException; +import org.apache.jena.vocabulary.RDF; +import org.apache.jena.vocabulary.RDFS; +import org.apache.jena.vocabulary.XSD; +import org.openmetadata.schema.api.data.OntologyShapeUnsupportedConstruct; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.BadRequestException; + +/** + * Reads the SHACL node shapes of a Turtle document. A shape is an {@code sh:NodeShape} with one + * {@code sh:targetClass} and {@code sh:property} nodes whose {@code sh:path} is a single IRI. A + * property node holds the constraints the shape model has: {@code sh:minCount}, {@code + * sh:maxCount}, {@code sh:class}, {@code sh:datatype}, {@code sh:minInclusive}, {@code + * sh:maxInclusive}, {@code sh:in} and {@code sh:pattern}. Every other SHACL construct is + * reported by name and left out; the rest of the file is still read. + */ +public final class OntologyShaclReader { + private static final String BASE = "urn:openmetadata:import:"; + private static final Pattern CONSTRAINT_ID = Pattern.compile("^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"); + private static final Set NODE_CONSUMED = + Set.of( + OntologyShaclVocabulary.NAME, + OntologyShaclVocabulary.TARGET_CLASS, + OntologyShaclVocabulary.SEVERITY, + OntologyShaclVocabulary.PROPERTY); + private static final Set PROPERTY_CONSUMED = + Set.of( + OntologyShaclVocabulary.PATH, + OntologyShaclVocabulary.ORDER, + OntologyShaclVocabulary.MIN_COUNT, + OntologyShaclVocabulary.MAX_COUNT, + OntologyShaclVocabulary.CLASS, + OntologyShaclVocabulary.DATATYPE, + OntologyShaclVocabulary.MIN_INCLUSIVE, + OntologyShaclVocabulary.MAX_INCLUSIVE, + OntologyShaclVocabulary.IN, + OntologyShaclVocabulary.PATTERN); + + /** A node shape as the file states it; the caller turns it into a stored shape. */ + public record ParsedShape( + String name, + String displayName, + String description, + URI targetConcept, + OntologyShapeSeverity severity, + List constraints) {} + + public record Parsed( + List shapes, List unsupported) {} + + private final List unsupported = new ArrayList<>(); + + private OntologyShaclReader() {} + + public static Parsed read(final String turtle) { + final Model model = ModelFactory.createDefaultModel(); + try { + RDFDataMgr.read(model, new StringReader(turtle), BASE, Lang.TURTLE); + return new OntologyShaclReader().parse(model); + } catch (RiotException invalid) { + throw new BadRequestException("The file is not valid Turtle: " + invalid.getMessage()); + } finally { + model.close(); + } + } + + private Parsed parse(final Model model) { + final Set attached = + new HashSet<>( + model + .listObjectsOfProperty(OntologyShaclVocabulary.PROPERTY) + .filterKeep(RDFNode::isResource) + .mapWith(RDFNode::asResource) + .toList()); + final List nodes = nodeShapes(model, attached); + reportDetachedPropertyShapes(model, attached, nodes); + final Set taken = new HashSet<>(); + final List shapes = new ArrayList<>(); + for (final Resource node : nodes) { + final ParsedShape shape = shape(node, taken); + if (shape != null) { + shapes.add(shape); + } + } + shapes.sort(Comparator.comparing(ParsedShape::name)); + return new Parsed(List.copyOf(shapes), List.copyOf(unsupported)); + } + + private static List nodeShapes(final Model model, final Set attached) { + final Map nodes = new LinkedHashMap<>(); + final List candidates = new ArrayList<>(); + candidates.addAll( + model.listSubjectsWithProperty(RDF.type, OntologyShaclVocabulary.NODE_SHAPE).toList()); + candidates.addAll( + model.listSubjectsWithProperty(OntologyShaclVocabulary.TARGET_CLASS).toList()); + for (final Resource candidate : candidates) { + final boolean typed = candidate.hasProperty(RDF.type, OntologyShaclVocabulary.NODE_SHAPE); + if (typed || !attached.contains(candidate)) { + nodes.putIfAbsent(key(candidate), candidate); + } + } + return nodes.values().stream().sorted(Comparator.comparing(OntologyShaclReader::key)).toList(); + } + + private static String key(final RDFNode node) { + return node.isURIResource() ? node.asResource().getURI() : "_:" + node.asResource().getId(); + } + + private void reportDetachedPropertyShapes( + final Model model, final Set attached, final List nodes) { + model + .listSubjectsWithProperty(OntologyShaclVocabulary.PATH) + .filterDrop(attached::contains) + .filterDrop(nodes::contains) + .toList() + .stream() + .sorted(Comparator.comparing(OntologyShaclReader::key)) + .forEach( + node -> + report( + "sh:PropertyShape", + null, + pathOf(node), + "A property shape that no node shape holds through sh:property was left out")); + } + + private ParsedShape shape(final Resource node, final Set taken) { + final List targets = + node.listProperties(OntologyShaclVocabulary.TARGET_CLASS) + .mapWith(Statement::getObject) + .toList(); + final String label = label(node); + final List classes = targets.stream().filter(RDFNode::isURIResource).toList(); + if (classes.size() != 1 || classes.size() != targets.size()) { + report( + "sh:targetClass", + label, + null, + "A node shape needs exactly one sh:targetClass that is an IRI; the shape was left out"); + reportUnconsumed(node, NODE_CONSUMED, label, null); + return null; + } + final String name = uniqueName(node, classes.getFirst().asResource(), taken); + reportUnconsumed(node, NODE_CONSUMED, name, null); + final List constraints = constraints(node, name); + return new ParsedShape( + name, + text(node, RDFS.label, name), + text(node, RDFS.comment, ""), + URI.create(classes.getFirst().asResource().getURI()), + severity(node, name), + constraints); + } + + private static String label(final Resource node) { + return node.isURIResource() ? node.getURI() : "_:" + node.getId(); + } + + private String uniqueName(final Resource node, final Resource target, final Set taken) { + final Statement named = node.getProperty(OntologyShaclVocabulary.NAME); + final String base = + named != null && named.getObject().isLiteral() + ? named.getString() + : node.isURIResource() + ? localName(node.getURI()) + : localName(target.getURI()) + "Shape"; + final String clean = base.isBlank() ? "Shape" : base.strip().replace("::", ":_"); + String candidate = clean.length() > 256 ? clean.substring(0, 256) : clean; + for (int suffix = 2; !taken.add(candidate); suffix++) { + candidate = clean + suffix; + } + return candidate; + } + + private static String localName(final String iri) { + final int cut = + Math.max(Math.max(iri.lastIndexOf('#'), iri.lastIndexOf('/')), iri.lastIndexOf(':')); + final String local = cut < 0 ? iri : iri.substring(cut + 1); + try { + return URLDecoder.decode(local.replace("+", "%2B"), StandardCharsets.UTF_8); + } catch (IllegalArgumentException undecodable) { + return local; + } + } + + private static String text(final Resource node, final Property property, final String fallback) { + final Statement statement = node.getProperty(property); + return statement != null && statement.getObject().isLiteral() + ? statement.getString() + : fallback; + } + + private OntologyShapeSeverity severity(final Resource node, final String name) { + final Statement statement = node.getProperty(OntologyShaclVocabulary.SEVERITY); + if (statement == null) { + return OntologyShapeSeverity.VIOLATION; + } + final RDFNode value = statement.getObject(); + if (OntologyShaclVocabulary.VIOLATION.equals(value)) { + return OntologyShapeSeverity.VIOLATION; + } + if (OntologyShaclVocabulary.WARNING.equals(value)) { + return OntologyShapeSeverity.WARNING; + } + if (OntologyShaclVocabulary.INFO.equals(value)) { + return OntologyShapeSeverity.INFO; + } + report( + "sh:severity", + name, + null, + "Only sh:Violation, sh:Warning and sh:Info are held; Violation was used"); + return OntologyShapeSeverity.VIOLATION; + } + + private List constraints(final Resource node, final String shapeName) { + final List properties = new ArrayList<>(); + for (final Statement statement : + node.listProperties(OntologyShaclVocabulary.PROPERTY).toList()) { + final RDFNode object = statement.getObject(); + if (!object.isResource()) { + report( + "sh:property", shapeName, null, "A sh:property value that is not a node was left out"); + continue; + } + final PropertyNode property = propertyNode(object.asResource(), shapeName); + if (property != null) { + properties.add(property); + } + } + properties.sort( + Comparator.comparingLong(PropertyNode::order) + .thenComparing(property -> property.constraint().getPath().toString()) + .thenComparing(property -> JsonUtils.pojoToJson(property.constraint()))); + return assignIds(node, properties); + } + + private PropertyNode propertyNode(final Resource node, final String shapeName) { + final List paths = + node.listProperties(OntologyShaclVocabulary.PATH).mapWith(Statement::getObject).toList(); + if (paths.size() != 1 || !paths.getFirst().isURIResource()) { + report( + "sh:path", + shapeName, + null, + "A property path that is not a single IRI is not held; the property shape was left out"); + return null; + } + final URI path = URI.create(paths.getFirst().asResource().getURI()); + reportUnconsumed(node, PROPERTY_CONSUMED, shapeName, path); + final OntologyShapeConstraint constraint = new OntologyShapeConstraint().withPath(path); + final boolean any = + count(node, OntologyShaclVocabulary.MIN_COUNT, shapeName, path, constraint::setMinCount) + | count( + node, OntologyShaclVocabulary.MAX_COUNT, shapeName, path, constraint::setMaxCount) + | iri(node, OntologyShaclVocabulary.CLASS, shapeName, path, constraint::setClassIri) + | iri( + node, OntologyShaclVocabulary.DATATYPE, shapeName, path, constraint::setDatatypeIri) + | bound( + node, + OntologyShaclVocabulary.MIN_INCLUSIVE, + shapeName, + path, + constraint::setMinInclusive) + | bound( + node, + OntologyShaclVocabulary.MAX_INCLUSIVE, + shapeName, + path, + constraint::setMaxInclusive) + | values(node, shapeName, path, constraint) + | pattern(node, shapeName, path, constraint); + if (!any) { + report( + "sh:property", + shapeName, + path, + "A property shape with no supported constraint was left out"); + return null; + } + return new PropertyNode(node, order(node), constraint); + } + + private static long order(final Resource node) { + final Statement statement = node.getProperty(OntologyShaclVocabulary.ORDER); + if (statement != null && statement.getObject().isLiteral()) { + try { + return Long.parseLong(statement.getLiteral().getLexicalForm().strip()); + } catch (NumberFormatException ignored) { + return Long.MAX_VALUE; + } + } + return Long.MAX_VALUE; + } + + private boolean count( + final Resource node, + final Property predicate, + final String shapeName, + final URI path, + final java.util.function.Consumer setter) { + final Statement statement = node.getProperty(predicate); + if (statement == null) { + return false; + } + final Integer value = nonNegative(statement.getObject()); + if (value == null) { + report( + "sh:" + predicate.getLocalName(), + shapeName, + path, + "The value is not a non-negative integer; the constraint was left out"); + return false; + } + setter.accept(value); + return true; + } + + private static Integer nonNegative(final RDFNode object) { + if (!object.isLiteral()) { + return null; + } + try { + final int value = Integer.parseInt(object.asLiteral().getLexicalForm().strip()); + return value < 0 ? null : value; + } catch (NumberFormatException invalid) { + return null; + } + } + + private boolean iri( + final Resource node, + final Property predicate, + final String shapeName, + final URI path, + final java.util.function.Consumer setter) { + final Statement statement = node.getProperty(predicate); + if (statement == null) { + return false; + } + if (!statement.getObject().isURIResource()) { + report( + "sh:" + predicate.getLocalName(), + shapeName, + path, + "The value is not an IRI; the constraint was left out"); + return false; + } + setter.accept(URI.create(statement.getResource().getURI())); + return true; + } + + private boolean bound( + final Resource node, + final Property predicate, + final String shapeName, + final URI path, + final java.util.function.Consumer setter) { + final Statement statement = node.getProperty(predicate); + if (statement == null) { + return false; + } + if (!statement.getObject().isLiteral()) { + report( + "sh:" + predicate.getLocalName(), + shapeName, + path, + "The value is not a literal; the constraint was left out"); + return false; + } + setter.accept(literal(statement.getLiteral())); + return true; + } + + private boolean values( + final Resource node, + final String shapeName, + final URI path, + final OntologyShapeConstraint constraint) { + final Statement statement = node.getProperty(OntologyShaclVocabulary.IN); + if (statement == null) { + return false; + } + final List values = new ArrayList<>(); + final boolean list = + statement.getObject().isResource() && statement.getObject().canAs(RDFList.class); + if (list) { + for (final RDFNode element : statement.getObject().as(RDFList.class).asJavaList()) { + if (element.isURIResource()) { + values.add(new OntologyShapeValue().withIri(URI.create(element.asResource().getURI()))); + } else if (element.isLiteral()) { + values.add(new OntologyShapeValue().withLiteral(literal(element.asLiteral()))); + } else { + list(shapeName, path); + return false; + } + } + } else { + list(shapeName, path); + return false; + } + constraint.setIn(values); + return true; + } + + private void list(final String shapeName, final URI path) { + report( + "sh:in", + shapeName, + path, + "The value is not a list of IRIs and literals; the constraint was left out"); + } + + private boolean pattern( + final Resource node, + final String shapeName, + final URI path, + final OntologyShapeConstraint constraint) { + final Statement statement = node.getProperty(OntologyShaclVocabulary.PATTERN); + if (statement == null) { + return false; + } + if (!statement.getObject().isLiteral()) { + report( + "sh:pattern", shapeName, path, "The value is not a string; the constraint was left out"); + return false; + } + constraint.setPattern(statement.getString()); + return true; + } + + private static OntologyLiteral literal(final Literal literal) { + final String datatype = literal.getDatatypeURI(); + final boolean plain = + datatype == null + || XSD.xstring.getURI().equals(datatype) + || RDF.langString.getURI().equals(datatype); + return new OntologyLiteral() + .withValue(literal.getLexicalForm()) + .withDatatypeIri(plain ? null : URI.create(datatype)); + } + + /** + * A property node written by {@link OntologyShaclWriter} carries its id after the {@code #} of + * its IRI, under its shape's own IRI. Any other node, such as a blank node, gets {@code c1}, + * {@code c2}, in the order the constraints are held. + */ + private static List assignIds( + final Resource shape, final List properties) { + final Set used = new HashSet<>(); + final Map explicit = new LinkedHashMap<>(); + for (final PropertyNode property : properties) { + final String id = explicitId(shape, property.node()); + if (id != null && used.add(id)) { + explicit.put(property, id); + } + } + final List constraints = new ArrayList<>(); + int serial = 0; + for (final PropertyNode property : properties) { + String id = explicit.get(property); + while (id == null) { + final String candidate = "c" + ++serial; + id = used.add(candidate) ? candidate : null; + } + constraints.add(property.constraint().withId(id)); + } + return constraints; + } + + private static String explicitId(final Resource shape, final Resource property) { + if (!shape.isURIResource() || !property.isURIResource()) { + return null; + } + final String prefix = shape.getURI() + "#"; + final String uri = property.getURI(); + if (!uri.startsWith(prefix)) { + return null; + } + final String id = uri.substring(prefix.length()); + return CONSTRAINT_ID.matcher(id).matches() ? id : null; + } + + private void reportUnconsumed( + final Resource node, final Set consumed, final String shapeName, final URI path) { + final Set reported = new HashSet<>(); + for (final Statement statement : node.listProperties().toList()) { + final Property predicate = statement.getPredicate(); + if (OntologyShaclVocabulary.isShacl(predicate) + && !consumed.contains(predicate) + && reported.add(predicate.getLocalName())) { + report("sh:" + predicate.getLocalName(), shapeName, path, "Not held by the shape model"); + } + } + } + + private static URI pathOf(final Resource node) { + final Statement path = node.getProperty(OntologyShaclVocabulary.PATH); + return path != null && path.getObject().isURIResource() + ? URI.create(path.getResource().getURI()) + : null; + } + + private void report( + final String construct, final String shape, final URI path, final String message) { + unsupported.add( + new OntologyShapeUnsupportedConstruct() + .withConstruct(construct) + .withShape(shape) + .withPath(path) + .withMessage(message)); + } + + private record PropertyNode(Resource node, long order, OntologyShapeConstraint constraint) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclVocabulary.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclVocabulary.java new file mode 100644 index 000000000000..5a6b59c51026 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclVocabulary.java @@ -0,0 +1,85 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.rdf; + +import org.apache.jena.rdf.model.Property; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.rdf.model.ResourceFactory; +import org.apache.jena.shacl.vocabulary.SHACL; + +/** The SHACL terms a shape is written with and read from, and the IRIs that carry its identity. */ +final class OntologyShaclVocabulary { + static final String SHAPE_IRI_PREFIX = "urn:openmetadata:ontology-shape:"; + static final Resource NODE_SHAPE = resource("NodeShape"); + static final Resource VIOLATION = resource("Violation"); + static final Resource WARNING = resource("Warning"); + static final Resource INFO = resource("Info"); + static final Property NAME = property("name"); + static final Property TARGET_CLASS = property("targetClass"); + static final Property SEVERITY = property("severity"); + static final Property PROPERTY = property("property"); + static final Property PATH = property("path"); + static final Property ORDER = property("order"); + static final Property MIN_COUNT = property("minCount"); + static final Property MAX_COUNT = property("maxCount"); + static final Property CLASS = property("class"); + static final Property DATATYPE = property("datatype"); + static final Property MIN_INCLUSIVE = property("minInclusive"); + static final Property MAX_INCLUSIVE = property("maxInclusive"); + static final Property IN = property("in"); + static final Property PATTERN = property("pattern"); + + private OntologyShaclVocabulary() {} + + static boolean isShacl(final Property predicate) { + return SHACL.NS.equals(predicate.getNameSpace()); + } + + /** The IRI a shape is written under: its name, percent-encoded so distinct names stay distinct. */ + static String shapeIri(final String name) { + final StringBuilder encoded = new StringBuilder(SHAPE_IRI_PREFIX); + for (final byte value : name.getBytes(java.nio.charset.StandardCharsets.UTF_8)) { + final char character = (char) (value & 0xff); + if (isUnreserved(character)) { + encoded.append(character); + } else { + encoded.append('%').append(String.format("%02X", value & 0xff)); + } + } + return encoded.toString(); + } + + /** The IRI a constraint is written under, so the importer can read its id back. */ + static String constraintIri(final String shapeIri, final String constraintId) { + return shapeIri + "#" + constraintId; + } + + private static boolean isUnreserved(final char character) { + return (character >= 'a' && character <= 'z') + || (character >= 'A' && character <= 'Z') + || (character >= '0' && character <= '9') + || character == '-' + || character == '.' + || character == '_' + || character == '~'; + } + + private static Resource resource(final String name) { + return ResourceFactory.createResource(SHACL.NS + name); + } + + private static Property property(final String name) { + return ResourceFactory.createProperty(SHACL.NS + name); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclWriter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclWriter.java new file mode 100644 index 000000000000..477ba07da5d4 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclWriter.java @@ -0,0 +1,147 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.rdf; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import java.util.Comparator; +import java.util.List; +import org.apache.jena.rdf.model.Literal; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.ModelFactory; +import org.apache.jena.rdf.model.RDFNode; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.shacl.vocabulary.SHACL; +import org.apache.jena.vocabulary.RDF; +import org.apache.jena.vocabulary.RDFS; +import org.apache.jena.vocabulary.XSD; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; + +/** + * Writes shapes as SHACL. Each shape is an {@code sh:NodeShape} named by {@code sh:name} and + * written under an IRI made from its name; each constraint is an {@code sh:property} node whose IRI + * is its shape's IRI, {@code #} and its constraint id, and whose {@code sh:order} is its authored + * position. {@link OntologyShaclReader} reads the id and the order back from those. + */ +public final class OntologyShaclWriter { + private OntologyShaclWriter() {} + + public static Model write(final Ontology root, final List shapes) { + final Model model = ModelFactory.createDefaultModel(); + model.setNsPrefix("sh", SHACL.NS); + model.setNsPrefix("rdfs", RDFS.uri); + model.setNsPrefix("xsd", XSD.NS); + listOrEmpty(root.getPrefixes()) + .forEach(prefix -> model.setNsPrefix(prefix.getPrefix(), prefix.getNamespace().toString())); + shapes.stream() + .sorted(Comparator.comparing(OntologyShape::getName)) + .forEach(shape -> write(model, shape)); + return model; + } + + private static void write(final Model model, final OntologyShape shape) { + final String shapeIri = OntologyShaclVocabulary.shapeIri(shape.getName()); + final Resource node = model.createResource(shapeIri); + node.addProperty(RDF.type, OntologyShaclVocabulary.NODE_SHAPE); + node.addProperty(OntologyShaclVocabulary.NAME, shape.getName()); + if (!nullOrEmpty(shape.getDisplayName())) { + node.addProperty(RDFS.label, shape.getDisplayName()); + } + if (!nullOrEmpty(shape.getDescription())) { + node.addProperty(RDFS.comment, shape.getDescription()); + } + node.addProperty( + OntologyShaclVocabulary.TARGET_CLASS, + model.createResource(shape.getTargetConcept().toString())); + node.addProperty(OntologyShaclVocabulary.SEVERITY, severity(shape.getSeverity())); + final List constraints = listOrEmpty(shape.getConstraints()); + for (int index = 0; index < constraints.size(); index++) { + final OntologyShapeConstraint constraint = constraints.get(index); + final Resource property = + model.createResource(OntologyShaclVocabulary.constraintIri(shapeIri, constraint.getId())); + node.addProperty(OntologyShaclVocabulary.PROPERTY, property); + write(model, property, constraint, index); + } + } + + private static Resource severity(final OntologyShapeSeverity severity) { + return switch (severity == null ? OntologyShapeSeverity.VIOLATION : severity) { + case VIOLATION -> OntologyShaclVocabulary.VIOLATION; + case WARNING -> OntologyShaclVocabulary.WARNING; + case INFO -> OntologyShaclVocabulary.INFO; + }; + } + + private static void write( + final Model model, + final Resource property, + final OntologyShapeConstraint constraint, + final int position) { + property.addProperty( + OntologyShaclVocabulary.PATH, model.createResource(constraint.getPath().toString())); + property.addLiteral(OntologyShaclVocabulary.ORDER, model.createTypedLiteral(position)); + if (constraint.getMinCount() != null) { + property.addLiteral( + OntologyShaclVocabulary.MIN_COUNT, model.createTypedLiteral(constraint.getMinCount())); + } + if (constraint.getMaxCount() != null) { + property.addLiteral( + OntologyShaclVocabulary.MAX_COUNT, model.createTypedLiteral(constraint.getMaxCount())); + } + if (constraint.getClassIri() != null) { + property.addProperty( + OntologyShaclVocabulary.CLASS, model.createResource(constraint.getClassIri().toString())); + } + if (constraint.getDatatypeIri() != null) { + property.addProperty( + OntologyShaclVocabulary.DATATYPE, + model.createResource(constraint.getDatatypeIri().toString())); + } + if (constraint.getMinInclusive() != null) { + property.addLiteral( + OntologyShaclVocabulary.MIN_INCLUSIVE, literal(model, constraint.getMinInclusive())); + } + if (constraint.getMaxInclusive() != null) { + property.addLiteral( + OntologyShaclVocabulary.MAX_INCLUSIVE, literal(model, constraint.getMaxInclusive())); + } + if (constraint.getIn() != null) { + property.addProperty( + OntologyShaclVocabulary.IN, + model.createList( + constraint.getIn().stream().map(value -> node(model, value)).iterator())); + } + if (constraint.getPattern() != null) { + property.addProperty(OntologyShaclVocabulary.PATTERN, constraint.getPattern()); + } + } + + private static RDFNode node(final Model model, final OntologyShapeValue value) { + return value.getIri() == null + ? literal(model, value.getLiteral()) + : model.createResource(value.getIri().toString()); + } + + private static Literal literal(final Model model, final OntologyLiteral literal) { + return literal.getDatatypeIri() == null + ? model.createLiteral(literal.getValue()) + : model.createTypedLiteral(literal.getValue(), literal.getDatatypeIri().toString()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java index c5cb7294f346..808a20ad6a99 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java @@ -38,6 +38,7 @@ public final class RdfExcludedEntities { Entity.ONTOLOGY_CONCEPT, Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_AXIOM, + Entity.ONTOLOGY_SHAPE, Entity.ONTOLOGY_RELEASE); private RdfExcludedEntities() {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java index 4acc3dd52a85..7ecc6f6ddc77 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java @@ -89,6 +89,7 @@ import org.openmetadata.service.jdbi3.OntologyPropertyRepository; import org.openmetadata.service.jdbi3.OntologyReleaseRepository; import org.openmetadata.service.jdbi3.OntologyRepository; +import org.openmetadata.service.jdbi3.OntologyShapeRepository; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.ontology.NativeOntologyDataGraphPager; import org.openmetadata.service.ontology.NativeOntologyDataGraphService; @@ -182,7 +183,9 @@ public OntologyResource(final Authorizer authorizer, final Limits limits) { MemberKind.PROPERTY, (OntologyPropertyRepository) Entity.getEntityRepository(Entity.ONTOLOGY_PROPERTY), MemberKind.AXIOM, - (OntologyAxiomRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM)), + (OntologyAxiomRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM), + MemberKind.SHAPE, + (OntologyShapeRepository) Entity.getEntityRepository(Entity.ONTOLOGY_SHAPE)), Clock.systemUTC()); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeMapper.java new file mode 100644 index 000000000000..a0ed86edb66f --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeMapper.java @@ -0,0 +1,38 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.resources.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.service.Entity; +import org.openmetadata.service.mapper.EntityMapper; + +public final class OntologyShapeMapper implements EntityMapper { + @Override + public OntologyShape createToEntity(final CreateOntologyShape request, final String user) { + return copy(new OntologyShape(), request, user) + .withOntology( + Entity.getEntityReferenceByName( + Entity.ONTOLOGY, request.getOntology(), Include.NON_DELETED)) + .withTargetConcept(request.getTargetConcept()) + .withSeverity( + request.getSeverity() == null ? OntologyShapeSeverity.VIOLATION : request.getSeverity()) + .withConstraints(listOrEmpty(request.getConstraints())) + .withProvider(request.getProvider()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java new file mode 100644 index 000000000000..ffc7402f0b0e --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java @@ -0,0 +1,297 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.resources.ontology; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.json.JsonPatch; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.DefaultValue; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.ImportOntologyShapes; +import org.openmetadata.schema.api.data.OntologyShapeImportAction; +import org.openmetadata.schema.api.data.OntologyShapeImportResult; +import org.openmetadata.schema.api.data.OntologyShapeImported; +import org.openmetadata.schema.api.data.RestoreEntity; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.EntityHistory; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.utils.ResultList; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.ListFilter; +import org.openmetadata.service.jdbi3.OntologyShapeRepository; +import org.openmetadata.service.limits.Limits; +import org.openmetadata.service.ontology.OntologyShapeRules; +import org.openmetadata.service.rdf.OntologyShaclReader; +import org.openmetadata.service.resources.Collection; +import org.openmetadata.service.resources.EntityResource; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.CreateResourceContext; +import org.openmetadata.service.security.policyevaluator.OperationContext; + +@Path("/v1/ontologyShapes") +@Tag(name = "Ontology Shapes", description = "SHACL node shapes authored in an ontology.") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Collection(name = "ontologyShapes", order = 3) +public class OntologyShapeResource extends EntityResource { + public static final String COLLECTION_PATH = "/v1/ontologyShapes/"; + private final OntologyShapeMapper mapper = new OntologyShapeMapper(); + + public OntologyShapeResource(final Authorizer authorizer, final Limits limits) { + super(Entity.ONTOLOGY_SHAPE, authorizer, limits); + } + + public static class OntologyShapeList extends ResultList {} + + @GET + @Operation(operationId = "listOntologyShapes", summary = "List ontology shapes") + public ResultList list( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @QueryParam("fields") final String fields, + @QueryParam("ontologyId") final UUID ontologyId, + @QueryParam("limit") @DefaultValue("50") @Min(0) @Max(1000000) final int limit, + @QueryParam("before") final String before, + @QueryParam("after") final String after, + @QueryParam("include") @DefaultValue("non-deleted") final Include include) { + final ListFilter filter = ontologyFilter(include, ontologyId); + OntologyResourceAccess.requireDraftListRead(authorizer, securityContext, ontologyId); + final ResultList page = + listInternal(uriInfo, securityContext, fields, filter, limit, before, after); + OntologyResourceAccess.requireDraftRowsRead( + authorizer, + securityContext, + ontologyId, + OntologyResourceAccess.ontologyIdsOf(page.getData())); + return page; + } + + private static ListFilter ontologyFilter(final Include include, final UUID ontologyId) { + final ListFilter filter = new ListFilter(include); + if (ontologyId != null) { + filter.addQueryParam("ontologyId", ontologyId.toString()); + } + return filter; + } + + @GET + @Path("/{id}") + @Operation(operationId = "getOntologyShapeById", summary = "Get an ontology shape") + public OntologyShape get( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @QueryParam("fields") final String fields, + @QueryParam("include") @DefaultValue("non-deleted") final Include include) { + return getInternal(uriInfo, securityContext, id, fields, include, null); + } + + @GET + @Path("/name/{fqn}") + @Operation(operationId = "getOntologyShapeByName", summary = "Get an ontology shape by name") + public OntologyShape getByName( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("fqn") final String fqn, + @QueryParam("fields") final String fields, + @QueryParam("include") @DefaultValue("non-deleted") final Include include) { + return getByNameInternal(uriInfo, securityContext, fqn, fields, include, null); + } + + @POST + @Operation(operationId = "createOntologyShape", summary = "Create an ontology shape") + public Response create( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @Valid final CreateOntologyShape request) { + final OntologyShape entity = mapper.createToEntity(request, user(securityContext)); + return OntologyResourceAccess.createOrRecreate( + repository, + entity, + () -> create(uriInfo, securityContext, entity), + () -> createOrUpdate(uriInfo, securityContext, entity)); + } + + @POST + @Path("/import") + @Operation( + operationId = "importOntologyShapes", + summary = "Import SHACL node shapes into an ontology's working draft", + description = + "Reads a Turtle document and creates or updates one shape per sh:NodeShape that has a single sh:targetClass, keyed by name, with the supported constraints of its sh:property nodes. Every other SHACL construct is left out and named in the result; that is a report, not an error. A shape that violates the shape rules fails the whole request before anything is written. With dryRun nothing is written.") + public OntologyShapeImportResult importShapes( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @Valid final ImportOntologyShapes request) { + final EntityReference ontology = + Entity.getEntityReferenceByName( + Entity.ONTOLOGY, request.getOntology(), Include.NON_DELETED); + authorizer.authorize( + securityContext, + new OperationContext(entityType, MetadataOperation.CREATE), + new CreateResourceContext<>(entityType, new OntologyShape().withOntology(ontology))); + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(request.getContent()); + final List shapes = + parsed.shapes().stream() + .map(shape -> toEntity(request.getOntology(), shape, user(securityContext))) + .toList(); + shapes.forEach(OntologyShapeRules::requireValid); + final boolean dryRun = Boolean.TRUE.equals(request.getDryRun()); + final List written = new ArrayList<>(); + for (final OntologyShape shape : shapes) { + written.add(dryRun ? planned(shape) : write(uriInfo, securityContext, shape)); + } + return new OntologyShapeImportResult() + .withDryRun(dryRun) + .withShapes(written) + .withUnsupported(parsed.unsupported()); + } + + private OntologyShape toEntity( + final String ontology, final OntologyShaclReader.ParsedShape shape, final String user) { + return mapper.createToEntity( + new CreateOntologyShape() + .withName(shape.name()) + .withDisplayName(shape.displayName()) + .withDescription(shape.description()) + .withOntology(ontology) + .withTargetConcept(shape.targetConcept()) + .withSeverity(shape.severity()) + .withConstraints(shape.constraints()), + user); + } + + private OntologyShapeImported planned(final OntologyShape shape) { + repository.setFullyQualifiedName(shape); + final boolean exists = + repository.findByNameOrNull(shape.getFullyQualifiedName(), Include.NON_DELETED) != null; + return imported( + shape, exists ? OntologyShapeImportAction.UPDATED : OntologyShapeImportAction.CREATED); + } + + private OntologyShapeImported write( + final UriInfo uriInfo, final SecurityContext securityContext, final OntologyShape shape) { + final Response response = createOrUpdate(uriInfo, securityContext, shape); + return imported( + shape, + response.getStatus() == Response.Status.CREATED.getStatusCode() + ? OntologyShapeImportAction.CREATED + : OntologyShapeImportAction.UPDATED); + } + + private static OntologyShapeImported imported( + final OntologyShape shape, final OntologyShapeImportAction action) { + return new OntologyShapeImported() + .withName(shape.getName()) + .withAction(action) + .withConstraintIds( + shape.getConstraints().stream().map(OntologyShapeConstraint::getId).toList()); + } + + @PUT + @Operation(operationId = "createOrUpdateOntologyShape", summary = "Create or update a shape") + public Response createOrUpdate( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @Valid final CreateOntologyShape request) { + final OntologyShape entity = mapper.createToEntity(request, user(securityContext)); + return createOrUpdate(uriInfo, securityContext, entity); + } + + @PATCH + @Path("/{id}") + @Consumes(MediaType.APPLICATION_JSON_PATCH_JSON) + @Operation(operationId = "patchOntologyShape", summary = "Patch an ontology shape") + public Response patch( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + final JsonPatch patch) { + OntologyResourceAccess.requireEditForContentPatch( + authorizer, securityContext, Entity.ONTOLOGY_SHAPE, id, patch); + return patchInternal(uriInfo, securityContext, id, patch); + } + + @GET + @Path("/{id}/versions") + @Operation(operationId = "listOntologyShapeVersions", summary = "List shape versions") + public EntityHistory listVersions( + @Context final SecurityContext securityContext, @PathParam("id") final UUID id) { + return listVersionsInternal(securityContext, id); + } + + @GET + @Path("/{id}/versions/{version}") + @Operation(operationId = "getOntologyShapeVersion", summary = "Get a shape version") + public OntologyShape getVersion( + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @PathParam("version") final String version) { + return getVersionInternal(securityContext, id, version); + } + + @DELETE + @Path("/{id}") + @Operation(operationId = "deleteOntologyShape", summary = "Delete an ontology shape") + public Response delete( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @QueryParam("hardDelete") @DefaultValue("false") final boolean hardDelete) { + return delete(uriInfo, securityContext, id, false, hardDelete); + } + + @PUT + @Path("/restore") + @Operation(operationId = "restoreOntologyShape", summary = "Restore an ontology shape") + public Response restore( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @Valid final RestoreEntity restore) { + return OntologyResourceAccess.restoreOrKeepLive( + authorizer, + securityContext, + repository, + restore.getId(), + () -> restoreEntity(uriInfo, securityContext, restore.getId())); + } + + private static String user(final SecurityContext securityContext) { + return securityContext.getUserPrincipal().getName(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/DefaultAuthorizer.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/DefaultAuthorizer.java index 99edf39f5033..696b93c0f32c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/DefaultAuthorizer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/DefaultAuthorizer.java @@ -341,6 +341,7 @@ private SubjectContext changeSubjectContext(String user, SubjectContext loggedIn Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_RELEASE, Entity.ONTOLOGY_AXIOM, + Entity.ONTOLOGY_SHAPE, Entity.ONTOLOGY_CHANGE_SET); private boolean requiresEditRight(String resource) { diff --git a/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json b/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json index 6c330fa6f23e..d1a2072f7093 100644 --- a/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json +++ b/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json @@ -10,7 +10,7 @@ { "name": "OntologyAuthorPolicy-AuthorRule", "description": "Allow authors to create, edit, delete and view the content of an ontology.", - "resources": ["ontology", "ontologyConcept", "ontologyProperty", "ontologyAxiom", "ontologyChangeSet"], + "resources": ["ontology", "ontologyConcept", "ontologyProperty", "ontologyAxiom", "ontologyShape", "ontologyChangeSet"], "operations": ["Create", "Delete", "ViewAll", "EditAll"], "effect": "allow" }, diff --git a/openmetadata-service/src/main/resources/json/data/policy/OntologyReviewerPolicy.json b/openmetadata-service/src/main/resources/json/data/policy/OntologyReviewerPolicy.json index b60eb535ba86..617ff01df7b4 100644 --- a/openmetadata-service/src/main/resources/json/data/policy/OntologyReviewerPolicy.json +++ b/openmetadata-service/src/main/resources/json/data/policy/OntologyReviewerPolicy.json @@ -10,7 +10,7 @@ { "name": "OntologyReviewerPolicy-ViewRule", "description": "Allow reviewers to view ontologies, their content and their releases.", - "resources": ["ontology", "ontologyConcept", "ontologyProperty", "ontologyAxiom", "ontologyChangeSet", "ontologyRelease"], + "resources": ["ontology", "ontologyConcept", "ontologyProperty", "ontologyAxiom", "ontologyShape", "ontologyChangeSet", "ontologyRelease"], "operations": ["ViewAll"], "effect": "allow" } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java new file mode 100644 index 000000000000..9ff0f4fc2b30 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java @@ -0,0 +1,174 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyProfileViolation; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.service.exception.BadRequestException; + +class OntologyShapeRulesTest { + private static final URI NAME = URI.create("urn:property:name"); + + @Test + void aShapeWithSatisfiableConstraintsHasNoFindings() { + final OntologyShape shape = + shape( + constraint("name-required").withMinCount(1).withMaxCount(1), + constraint("name-pattern").withPattern("^[A-Z][a-z]+$"), + constraint("name-values") + .withIn( + List.of( + new OntologyShapeValue().withLiteral(new OntologyLiteral().withValue("A")), + new OntologyShapeValue().withIri(URI.create("urn:value:b"))))); + + assertEquals(List.of(), validate(shape)); + } + + @Test + void aMinimumAboveTheMaximumCanNeverBeSatisfied() { + final var findings = validate(shape(constraint("c1").withMinCount(3).withMaxCount(2))); + + assertEquals( + List.of( + "SHAPE_CARDINALITY_CONFLICT /constraints/0: minCount 3 is above maxCount 2, so no value count satisfies the constraint"), + findings); + } + + @Test + void anEmptyInListCanNeverBeSatisfied() { + final var findings = validate(shape(constraint("c1").withIn(List.of()))); + + assertEquals( + List.of( + "SHAPE_EMPTY_VALUE_LIST /constraints/0/in: An in list names at least one value, or no value satisfies the constraint"), + findings); + } + + @Test + void aRepeatedConstraintIdIsRefused() { + final var findings = + validate(shape(constraint("c1").withMinCount(1), constraint("c1").withMaxCount(2))); + + assertEquals( + List.of( + "SHAPE_INVALID_CONSTRAINT /constraints/1/id: A constraint id is unique within its shape: c1"), + findings); + } + + @Test + void aConstraintThatStatesNothingIsRefused() { + final var findings = validate(shape(constraint("c1"))); + + assertEquals(1, findings.size()); + assertTrue(findings.getFirst().startsWith("SHAPE_INVALID_CONSTRAINT /constraints/0: ")); + } + + @Test + void anIdOutsideTheAllowedAlphabetIsRefused() { + assertEquals( + 1, validate(shape(constraint("has space").withMinCount(1))).size(), "space in the id"); + assertEquals(1, validate(shape(constraint("-leading").withMinCount(1))).size(), "leading dash"); + assertEquals( + 1, validate(shape(constraint("x".repeat(65)).withMinCount(1))).size(), "65 characters"); + } + + @Test + void aRelativeIriIsRefused() { + final OntologyShape shape = + shape(constraint("c1").withMinCount(1).withPath(URI.create("relative"))); + shape.setTargetConcept(URI.create("AlsoRelative")); + + assertEquals( + List.of( + "SHAPE_INVALID_CONSTRAINT /targetConcept: An IRI must be absolute: AlsoRelative", + "SHAPE_INVALID_CONSTRAINT /constraints/0/path: An IRI must be absolute: relative"), + validate(shape)); + } + + @Test + void aPatternThatDoesNotCompileIsRefused() { + final var findings = validate(shape(constraint("c1").withPattern("[unclosed"))); + + assertEquals(1, findings.size()); + assertTrue( + findings.getFirst().startsWith("SHAPE_INVALID_CONSTRAINT /constraints/0/pattern: "), + findings.getFirst()); + } + + @Test + void anInValueNeedsExactlyOneOfAnIriOrALiteral() { + final var both = + new OntologyShapeValue() + .withIri(URI.create("urn:v")) + .withLiteral(new OntologyLiteral().withValue("v")); + final var findings = + validate(shape(constraint("c1").withIn(List.of(both, new OntologyShapeValue())))); + + assertEquals( + List.of( + "SHAPE_INVALID_CONSTRAINT /constraints/0/in/0: An in value is exactly one of an iri or a literal", + "SHAPE_INVALID_CONSTRAINT /constraints/0/in/1: An in value is exactly one of an iri or a literal"), + findings); + } + + @Test + void savingASatisfiableShapeThrowsNothingAndAnInvalidOneNamesTheFirstProblem() { + OntologyShapeRules.requireValid(shape(constraint("c1").withMinCount(1))); + + final var refused = + assertThrows( + BadRequestException.class, + () -> + OntologyShapeRules.requireValid( + shape(constraint("c1").withMinCount(2).withMaxCount(1)))); + assertEquals( + "/constraints/0: minCount 2 is above maxCount 1, so no value count satisfies the constraint", + refused.getMessage()); + } + + private static List validate(final OntologyShape shape) { + return OntologyShapeRules.validate(shape).stream() + .map(OntologyShapeRulesTest::describe) + .toList(); + } + + private static String describe(final OntologyProfileViolation violation) { + return violation.getCode() + " " + violation.getPath() + ": " + violation.getMessage(); + } + + private static OntologyShape shape(final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withName("PersonShape") + .withTargetConcept(URI.create("urn:class:Person")) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints(List.of(constraints)); + } + + private static OntologyShapeConstraint constraint(final String id) { + return new OntologyShapeConstraint().withId(id).withPath(NAME); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java new file mode 100644 index 000000000000..ef86c4f6a1c2 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java @@ -0,0 +1,201 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyConceptType; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; + +/** What release validation says about the shapes a release holds. */ +class OntologyShapeValidationTest { + private static final OntologyRelease RELEASE = + new OntologyRelease().withId(UUID.randomUUID()).withContentDigest("a".repeat(64)); + private static final URI PERSON = URI.create("urn:class:Person"); + private static final URI ADDRESS = URI.create("urn:class:Address"); + private static final URI NAME = URI.create("urn:property:name"); + private static final URI LIVES_AT = URI.create("urn:property:livesAt"); + + @Test + void aShapeOverDeclaredClassesAndPropertiesIsValid() { + final var report = + validate( + shape( + PERSON, + new OntologyShapeConstraint().withId("name").withPath(NAME).withMinCount(1), + new OntologyShapeConstraint() + .withId("address") + .withPath(LIVES_AT) + .withClassIri(ADDRESS))); + + assertTrue(report.getValid(), report.getViolations().toString()); + } + + @Test + void aTargetClassThatTheReleaseDoesNotDeclareFails() { + assertEquals( + List.of("UNDECLARED_CLASS /targetConcept"), + violations( + shape( + URI.create("urn:class:Missing"), + new OntologyShapeConstraint().withId("name").withPath(NAME).withMinCount(1)))); + } + + @Test + void aPathThatTheReleaseDoesNotDeclareFails() { + assertEquals( + List.of("UNDECLARED_PROPERTY /constraints/0/path"), + violations( + shape( + PERSON, + new OntologyShapeConstraint() + .withId("age") + .withPath(URI.create("urn:property:age")) + .withMinCount(1)))); + } + + @Test + void aClassConstraintThatNamesAMissingClassFails() { + assertEquals( + List.of("UNDECLARED_CLASS /constraints/0/classIri"), + violations( + shape( + PERSON, + new OntologyShapeConstraint() + .withId("address") + .withPath(LIVES_AT) + .withClassIri(URI.create("urn:class:Missing"))))); + } + + @Test + void aMinimumCountAboveTheMaximumFails() { + assertEquals( + List.of("SHAPE_CARDINALITY_CONFLICT /constraints/0"), + violations( + shape( + PERSON, + new OntologyShapeConstraint() + .withId("name") + .withPath(NAME) + .withMinCount(2) + .withMaxCount(1)))); + } + + @Test + void anEmptyInListFails() { + assertEquals( + List.of("SHAPE_EMPTY_VALUE_LIST /constraints/0/in"), + violations( + shape( + PERSON, + new OntologyShapeConstraint() + .withId("name") + .withPath(NAME) + .withIn(List.of())))); + } + + @Test + void aRepeatedConstraintIdFails() { + assertEquals( + List.of("SHAPE_INVALID_CONSTRAINT /constraints/1/id"), + violations( + shape( + PERSON, + new OntologyShapeConstraint().withId("c").withPath(NAME).withMinCount(1), + new OntologyShapeConstraint().withId("c").withPath(NAME).withMaxCount(2)))); + } + + @Test + void aShapeDoesNotChangeTheVerdictOnTheDefinitionsAroundIt() { + final var without = validate(null); + + assertTrue(without.getValid()); + assertEquals(0, without.getViolationCount()); + } + + private static List violations(final OntologyShape shape) { + final var report = validate(shape); + assertEquals(false, report.getValid()); + return report.getViolations().stream() + .map(issue -> issue.getViolation().getCode() + " " + issue.getViolation().getPath()) + .toList(); + } + + private static org.openmetadata.schema.api.data.OntologyReleaseStructureReport validate( + final OntologyShape shape) { + final List members = new ArrayList<>(); + members.add(member(MemberKind.CONCEPT, concept(PERSON))); + members.add(member(MemberKind.CONCEPT, concept(ADDRESS))); + members.add(member(MemberKind.PROPERTY, property(NAME, OntologyPropertyKind.DATA))); + members.add(member(MemberKind.PROPERTY, property(LIVES_AT, OntologyPropertyKind.OBJECT))); + if (shape != null) { + members.add(member(MemberKind.SHAPE, shape)); + } + return OntologyStructureValidator.validate(RELEASE, members); + } + + private static OntologyShape shape( + final URI target, final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withName("PersonShape") + .withTargetConcept(target) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints(List.of(constraints)) + .withOntology(ontology()); + } + + private static OntologyConcept concept(final URI iri) { + return new OntologyConcept() + .withId(UUID.randomUUID()) + .withIri(iri) + .withConceptType(OntologyConceptType.OWL_CLASS) + .withOntology(ontology()); + } + + private static OntologyProperty property(final URI iri, final OntologyPropertyKind kind) { + return new OntologyProperty() + .withId(UUID.randomUUID()) + .withIri(iri) + .withKind(kind) + .withOntology(ontology()); + } + + private static EntityReference ontology() { + return new EntityReference().withId(RELEASE.getId()).withType("ontology"); + } + + private static OntologyReleaseMember member( + final MemberKind kind, final OntologyDefinition definition) { + return OntologyReleaseManifest.member( + RELEASE.getId(), kind, definition.getId(), OntologyReleaseContent.project(definition)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseExportFixture.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseExportFixture.java index 5eedc17bea77..5f1a1c1fccd0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseExportFixture.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseExportFixture.java @@ -17,6 +17,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.type.OntologyConceptType; import org.openmetadata.schema.type.OntologyExpression; @@ -152,6 +153,7 @@ private static MemberKind kind(final EntityInterface definition) { case OntologyConcept ignored -> MemberKind.CONCEPT; case OntologyProperty ignored -> MemberKind.PROPERTY; case OntologyAxiom ignored -> MemberKind.AXIOM; + case OntologyShape ignored -> MemberKind.SHAPE; default -> throw new IllegalArgumentException(); }; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java index a5c88b7a82d7..803fb05ecf78 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java @@ -900,7 +900,7 @@ void rejectsAValidDigestWhenPayloadIdentityOrOwnershipIsWrong() { @Test void unsupportedMembersAndMissingRootsCannotDisappearFromExport() { Bundle bundle = bundle(List.of(concept("Customer"))); - bundle.members().getLast().setMemberKind(MemberKind.SHAPE); + bundle.members().getLast().setMemberKind(MemberKind.ASSOCIATION); reseal(bundle); assertThrows( BadRequestException.class, diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseShapeExportTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseShapeExportTest.java new file mode 100644 index 000000000000..4b258da38f04 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseShapeExportTest.java @@ -0,0 +1,152 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.rdf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.service.rdf.OntologyReleaseExportFixture.CUSTOMER; +import static org.openmetadata.service.rdf.OntologyReleaseExportFixture.EX; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.api.data.OntologyReleaseExportOptions; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.OntologyReleaseManifest; +import org.openmetadata.service.rdf.OntologyReleaseExportFixture.Sealed; + +/** Shapes in a sealed release: exported as SHACL, and invisible to the OWL graph formats. */ +class OntologyReleaseShapeExportTest { + private static final OntologyShape SHAPE = + new OntologyShape() + .withId(OntologyReleaseExportFixture.id("customer-shape")) + .withName("CustomerShape") + .withDisplayName("Customer shape") + .withDescription("") + .withOntology(OntologyReleaseExportFixture.ROOT.getEntityReference()) + .withTargetConcept(CUSTOMER.getIri()) + .withSeverity(OntologyShapeSeverity.INFO) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("buys") + .withPath(URI.create(EX + "buysFrom")) + .withMinCount(1), + new OntologyShapeConstraint() + .withId("buys-max") + .withPath(URI.create(EX + "buysFrom")) + .withMaxCount(5))); + + private static final Sealed WITH_SHAPE = sealed(true); + private static final Sealed WITHOUT_SHAPE = sealed(false); + + @Test + void shaclExportReadsBackWithTheConstraintIdsOfTheSealedShape() { + final String shacl = + OntologyReleaseExporter.render( + WITH_SHAPE.release(), + WITH_SHAPE.members(), + OntologyExportFormat.SHACL, + new OntologyReleaseExportOptions(), + BoundAssetLinks.NONE); + + final var parsed = OntologyShaclReader.read(shacl); + + assertEquals(List.of(), parsed.unsupported()); + assertEquals(1, parsed.shapes().size()); + final var shape = parsed.shapes().getFirst(); + assertEquals("CustomerShape", shape.name()); + assertEquals(CUSTOMER.getIri(), shape.targetConcept()); + assertEquals(OntologyShapeSeverity.INFO, shape.severity()); + assertEquals( + List.of("buys", "buys-max"), + shape.constraints().stream().map(OntologyShapeConstraint::getId).toList()); + } + + @Test + void aReleaseWithoutShapesExportsEmptyShacl() { + final String shacl = + OntologyReleaseExporter.render( + WITHOUT_SHAPE.release(), + WITHOUT_SHAPE.members(), + OntologyExportFormat.SHACL, + new OntologyReleaseExportOptions(), + BoundAssetLinks.NONE); + + assertEquals(List.of(), OntologyShaclReader.read(shacl).shapes()); + } + + @Test + void theOwlGraphOfAReleaseIsTheSameWithOrWithoutItsShapes() { + final var options = new OntologyReleaseExportOptions(); + final String with = + OntologyReleaseExporter.render( + WITH_SHAPE.release(), + WITH_SHAPE.members(), + OntologyExportFormat.TURTLE, + options, + BoundAssetLinks.NONE); + final String without = + OntologyReleaseExporter.render( + WITHOUT_SHAPE.release(), + WITHOUT_SHAPE.members(), + OntologyExportFormat.TURTLE, + options, + BoundAssetLinks.NONE); + + assertTrue( + OntologyReleaseExportFixture.turtle(with) + .isIsomorphicWith(OntologyReleaseExportFixture.turtle(without)), + "a shape adds no statement to the OWL graph"); + } + + @Test + void aSealedShapeChangesTheDigestAndStillVerifies() { + assertNotEquals( + WITHOUT_SHAPE.release().getContentDigest(), WITH_SHAPE.release().getContentDigest()); + OntologyReleaseManifest.verify(WITH_SHAPE.release(), WITH_SHAPE.members()); + } + + @Test + void boundAssetLinksAreRefusedForShacl() { + final var refused = + assertThrows( + BadRequestException.class, + () -> + OntologyReleaseExporter.render( + WITH_SHAPE.release(), + WITH_SHAPE.members(), + OntologyExportFormat.SHACL, + new OntologyReleaseExportOptions().withIncludeBoundAssets(true), + BoundAssetLinks.NONE)); + assertEquals("Bound asset links cannot be written to shacl", refused.getMessage()); + } + + private static Sealed sealed(final boolean withShape) { + final List definitions = new ArrayList<>(); + definitions.add(CUSTOMER); + definitions.add(OntologyReleaseExportFixture.property("buysFrom", "soldTo")); + if (withShape) { + definitions.add(SHAPE); + } + return OntologyReleaseExportFixture.seal(definitions); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclRoundTripTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclRoundTripTest.java new file mode 100644 index 000000000000..940d8d538d48 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclRoundTripTest.java @@ -0,0 +1,203 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.rdf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.apache.jena.rdf.model.Model; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyShapeUnsupportedConstruct; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.BadRequestException; + +class OntologyShaclRoundTripTest { + private static final URI PERSON = URI.create("https://example.org/onto/Person"); + private static final URI NAME = URI.create("https://example.org/onto/name"); + private static final URI AGE = URI.create("https://example.org/onto/age"); + private static final URI STATUS = URI.create("https://example.org/onto/status"); + private static final URI XSD_INTEGER = URI.create("http://www.w3.org/2001/XMLSchema#integer"); + + @Test + void exportedShapesImportBackWithEveryConstraintIdAndTheirOrder() { + final OntologyShape person = + shape( + "Person shape", + PERSON, + OntologyShapeSeverity.WARNING, + new OntologyShapeConstraint() + .withId("z-first") + .withPath(NAME) + .withMinCount(1) + .withMaxCount(1) + .withPattern("^[A-Z]"), + new OntologyShapeConstraint() + .withId("age.range") + .withPath(AGE) + .withDatatypeIri(XSD_INTEGER) + .withMinInclusive(new OntologyLiteral().withValue("0").withDatatypeIri(XSD_INTEGER)) + .withMaxInclusive( + new OntologyLiteral().withValue("150").withDatatypeIri(XSD_INTEGER)), + new OntologyShapeConstraint() + .withId("status_in") + .withPath(STATUS) + .withClassIri(URI.create("https://example.org/onto/Status")) + .withIn( + List.of( + new OntologyShapeValue() + .withIri(URI.create("https://example.org/onto/Active")), + new OntologyShapeValue() + .withLiteral(new OntologyLiteral().withValue("retired"))))); + final OntologyShape empty = shape("Plain", PERSON, OntologyShapeSeverity.VIOLATION); + + final String turtle = turtle(person, empty); + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(turtle); + + assertEquals(List.of(), parsed.unsupported()); + assertEquals( + List.of("Person shape", "Plain"), + parsed.shapes().stream().map(OntologyShaclReader.ParsedShape::name).toList()); + final OntologyShaclReader.ParsedShape read = parsed.shapes().get(0); + assertEquals(PERSON, read.targetConcept()); + assertEquals(OntologyShapeSeverity.WARNING, read.severity()); + assertEquals("Person shape display", read.displayName()); + assertEquals("Person shape description", read.description()); + assertEquals( + JsonUtils.pojoToJson(person.getConstraints()), JsonUtils.pojoToJson(read.constraints())); + assertEquals( + List.of("z-first", "age.range", "status_in"), + read.constraints().stream().map(OntologyShapeConstraint::getId).toList()); + assertEquals(List.of(), parsed.shapes().get(1).constraints()); + } + + @Test + void aFileFromElsewhereImportsItsSupportedPartsAndNamesTheRest() { + final String file = + """ + @prefix sh: . + @prefix ex: . + @prefix xsd: . + + ex:PersonShape a sh:NodeShape ; + sh:targetClass ex:Person ; + sh:closed true ; + sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:minLength 2 ] ; + sh:property [ sh:path ex:age ; sh:datatype xsd:integer ; sh:or ( [ sh:minInclusive 0 ] [ sh:maxInclusive 5 ] ) ] ; + sh:property [ sh:path [ sh:inversePath ex:knows ] ; sh:minCount 1 ] ; + sh:property [ sh:path ex:nick ; sh:uniqueLang true ] ; + sh:sparql [ sh:select "SELECT $this WHERE { }" ] . + + ex:Orphan a sh:NodeShape ; sh:targetNode ex:Alice . + """; + + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(file); + + assertEquals(1, parsed.shapes().size()); + final OntologyShaclReader.ParsedShape person = parsed.shapes().get(0); + assertEquals("PersonShape", person.name()); + assertEquals( + List.of("age=null/null", "name=1/null"), + person.constraints().stream() + .map( + c -> + c.getPath().toString().replaceAll(".*/", "") + + "=" + + c.getMinCount() + + "/" + + c.getMaxCount()) + .sorted() + .toList()); + assertEquals( + List.of("c1", "c2"), + person.constraints().stream().map(OntologyShapeConstraint::getId).toList()); + assertEquals( + List.of( + "sh:closed", + "sh:minLength", + "sh:or", + "sh:path", + "sh:property", + "sh:sparql", + "sh:targetClass", + "sh:targetNode", + "sh:uniqueLang"), + parsed.unsupported().stream() + .map(OntologyShapeUnsupportedConstruct::getConstruct) + .distinct() + .sorted() + .toList()); + assertTrue( + parsed.unsupported().stream() + .anyMatch( + item -> + item.getConstruct().equals("sh:path") && "PersonShape".equals(item.getShape())), + "a property path that is not a single IRI is named with its shape"); + } + + @Test + void aShapeWithoutOneTargetClassIsLeftOutAndNamed() { + final OntologyShaclReader.Parsed parsed = + OntologyShaclReader.read( + """ + @prefix sh: . + @prefix ex: . + ex:NoTarget a sh:NodeShape ; sh:property [ sh:path ex:name ; sh:minCount 1 ] . + """); + + assertEquals(List.of(), parsed.shapes()); + assertEquals("sh:targetClass", parsed.unsupported().get(0).getConstruct()); + assertEquals("https://example.org/onto/NoTarget", parsed.unsupported().get(0).getShape()); + } + + @Test + void textThatIsNotTurtleIsRefused() { + assertThrows(BadRequestException.class, () -> OntologyShaclReader.read("this is { not turtle")); + } + + private static String turtle(final OntologyShape... shapes) { + final Model model = + OntologyShaclWriter.write( + new Ontology().withIri(URI.create("https://example.org/onto")), List.of(shapes)); + try { + return RdfGraphSerializer.asString(model, RdfSerializationFormat.TURTLE); + } finally { + model.close(); + } + } + + private static OntologyShape shape( + final String name, + final URI target, + final OntologyShapeSeverity severity, + final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withName(name) + .withDisplayName(name + " display") + .withDescription(name + " description") + .withTargetConcept(target) + .withSeverity(severity) + .withConstraints(List.of(constraints)); + } +} diff --git a/openmetadata-spec/src/main/antlr4/org/openmetadata/schema/EntityLink.g4 b/openmetadata-spec/src/main/antlr4/org/openmetadata/schema/EntityLink.g4 index 699d9233e5a5..b567aebe5a72 100644 --- a/openmetadata-spec/src/main/antlr4/org/openmetadata/schema/EntityLink.g4 +++ b/openmetadata-spec/src/main/antlr4/org/openmetadata/schema/EntityLink.g4 @@ -45,6 +45,7 @@ ENTITY_TYPE | 'ontologyProperty' | 'ontologyRelease' | 'ontologyAxiom' + | 'ontologyShape' | 'ontologyChangeSet' | 'databaseService' | 'messagingService' diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyShape.json b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyShape.json new file mode 100644 index 000000000000..ccca851150dd --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyShape.json @@ -0,0 +1,51 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/createOntologyShape.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "CreateOntologyShapeRequest", + "description": "Create or update an ontology shape.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.CreateOntologyShape", + "javaInterfaces": [ + "org.openmetadata.schema.CreateEntity" + ], + "properties": { + "name": { + "$ref": "../../type/basic.json#/definitions/entityName" + }, + "displayName": { + "type": "string" + }, + "description": { + "$ref": "../../type/basic.json#/definitions/markdown" + }, + "ontology": { + "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "targetConcept": { + "$ref": "../../type/ontologyIri.json" + }, + "severity": { + "$ref": "../../entity/data/ontologyShape.json#/definitions/severity" + }, + "constraints": { + "type": "array", + "items": { + "$ref": "../../type/ontologyShapeConstraint.json" + } + }, + "owners": { + "$ref": "../../type/entityReferenceList.json" + }, + "provider": { + "$ref": "../../type/basic.json#/definitions/providerType" + } + }, + "required": [ + "name", + "displayName", + "description", + "ontology", + "targetConcept" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/importOntologyShapes.json b/openmetadata-spec/src/main/resources/json/schema/api/data/importOntologyShapes.json new file mode 100644 index 000000000000..8d857908b481 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/importOntologyShapes.json @@ -0,0 +1,29 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/importOntologyShapes.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "ImportOntologyShapesRequest", + "description": "Import the SHACL node shapes of a Turtle document into an ontology's working draft.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.ImportOntologyShapes", + "properties": { + "ontology": { + "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "content": { + "description": "The Turtle document.", + "type": "string", + "minLength": 1, + "maxLength": 8388608 + }, + "dryRun": { + "description": "Report what the import would write without writing it.", + "type": "boolean", + "default": false + } + }, + "required": [ + "ontology", + "content" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeImportResult.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeImportResult.json new file mode 100644 index 000000000000..f83aea2e574f --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeImportResult.json @@ -0,0 +1,96 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyShapeImportResult.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyShapeImportResult", + "description": "What a SHACL import wrote, and every construct of the file it did not take over.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeImportResult", + "definitions": { + "action": { + "javaType": "org.openmetadata.schema.api.data.OntologyShapeImportAction", + "type": "string", + "enum": [ + "CREATED", + "UPDATED" + ] + }, + "shape": { + "javaType": "org.openmetadata.schema.api.data.OntologyShapeImported", + "description": "A shape the import wrote, or would write on a dry run.", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "action": { + "$ref": "#/definitions/action" + }, + "constraintIds": { + "type": "array", + "items": { + "type": "string" + }, + "default": [] + } + }, + "required": [ + "name", + "action", + "constraintIds" + ], + "additionalProperties": false + }, + "unsupported": { + "javaType": "org.openmetadata.schema.api.data.OntologyShapeUnsupportedConstruct", + "description": "A SHACL construct of the file the shape model does not hold. Reporting it is not an error: the supported parts of the file are imported.", + "type": "object", + "properties": { + "construct": { + "description": "The construct by name, such as sh:or.", + "type": "string" + }, + "shape": { + "description": "Name of the node shape that carries it, when it has one.", + "type": "string" + }, + "path": { + "description": "Full IRI of the property the construct constrains, when it constrains one.", + "$ref": "../../type/ontologyIri.json" + }, + "message": { + "type": "string" + } + }, + "required": [ + "construct", + "message" + ], + "additionalProperties": false + } + }, + "properties": { + "dryRun": { + "type": "boolean" + }, + "shapes": { + "type": "array", + "items": { + "$ref": "#/definitions/shape" + }, + "default": [] + }, + "unsupported": { + "type": "array", + "items": { + "$ref": "#/definitions/unsupported" + }, + "default": [] + } + }, + "required": [ + "dryRun", + "shapes", + "unsupported" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyShape.json b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyShape.json new file mode 100644 index 000000000000..e5e987e9f253 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyShape.json @@ -0,0 +1,104 @@ +{ + "$id": "https://open-metadata.org/schema/entity/data/ontologyShape.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyShape", + "description": "A SHACL node shape that targets one class of an ontology and lists constraints on the properties of its instances.", + "$comment": "@om-entity-type", + "type": "object", + "javaType": "org.openmetadata.schema.entity.data.OntologyShape", + "javaInterfaces": [ + "org.openmetadata.schema.EntityInterface", + "org.openmetadata.schema.OntologyDefinition" + ], + "definitions": { + "severity": { + "javaType": "org.openmetadata.schema.type.OntologyShapeSeverity", + "description": "How serious a failed constraint is, as SHACL defines the severities.", + "type": "string", + "enum": [ + "Violation", + "Warning", + "Info" + ] + } + }, + "properties": { + "id": { + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "name": { + "$ref": "../../type/basic.json#/definitions/entityName" + }, + "displayName": { + "type": "string" + }, + "fullyQualifiedName": { + "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "description": { + "$ref": "../../type/basic.json#/definitions/markdown" + }, + "ontology": { + "$ref": "../../type/entityReference.json" + }, + "targetConcept": { + "description": "Full IRI of the class the shape applies to.", + "$ref": "../../type/ontologyIri.json" + }, + "severity": { + "$ref": "#/definitions/severity" + }, + "constraints": { + "description": "Constraints on the properties of the target class, in authored order.", + "type": "array", + "items": { + "$ref": "../../type/ontologyShapeConstraint.json" + }, + "default": [] + }, + "owners": { + "$ref": "../../type/entityReferenceList.json" + }, + "version": { + "$ref": "../../type/entityHistory.json#/definitions/entityVersion" + }, + "updatedAt": { + "$ref": "../../type/basic.json#/definitions/timestamp" + }, + "updatedBy": { + "type": "string" + }, + "impersonatedBy": { + "description": "Bot user that performed the action on behalf of the actual user.", + "$ref": "../../type/basic.json#/definitions/impersonatedBy" + }, + "href": { + "$ref": "../../type/basic.json#/definitions/href" + }, + "changeDescription": { + "$ref": "../../type/entityHistory.json#/definitions/changeDescription" + }, + "incrementalChangeDescription": { + "$ref": "../../type/entityHistory.json#/definitions/changeDescription" + }, + "deleted": { + "type": "boolean", + "default": false + }, + "provider": { + "$ref": "../../type/basic.json#/definitions/providerType" + } + }, + "required": [ + "id", + "name", + "displayName", + "fullyQualifiedName", + "description", + "ontology", + "targetConcept", + "severity", + "constraints" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/nativeOntologyExportFormat.json b/openmetadata-spec/src/main/resources/json/schema/type/nativeOntologyExportFormat.json index f5f3a71fa9e7..34617665008e 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/nativeOntologyExportFormat.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/nativeOntologyExportFormat.json @@ -2,8 +2,8 @@ "$id": "https://open-metadata.org/schema/type/nativeOntologyExportFormat.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "NativeOntologyExportFormat", - "description": "Serializations and concept projections available for sealed native ontology releases. SKOS and SKOS-XL are written as Turtle, and CSV is the native ontology spreadsheet.", + "description": "Serializations and concept projections available for sealed native ontology releases. SKOS and SKOS-XL are written as Turtle, CSV is the native ontology spreadsheet, and SHACL is the ontology's shapes written as Turtle.", "javaType": "org.openmetadata.schema.type.NativeOntologyExportFormat", "type": "string", - "enum": ["turtle", "rdfxml", "ntriples", "jsonld", "skos", "skos-xl", "csv"] + "enum": ["turtle", "rdfxml", "ntriples", "jsonld", "skos", "skos-xl", "csv", "shacl"] } diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json index 46f2a1074aea..96a6e0ffb764 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json @@ -31,7 +31,10 @@ "INVALID_CLASS_KIND", "SUBCLASS_CYCLE", "SUBPROPERTY_CYCLE", - "DISJOINT_CLASH" + "DISJOINT_CLASH", + "SHAPE_CARDINALITY_CONFLICT", + "SHAPE_EMPTY_VALUE_LIST", + "SHAPE_INVALID_CONSTRAINT" ] } }, diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyShapeConstraint.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyShapeConstraint.json new file mode 100644 index 000000000000..8b4d80235586 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyShapeConstraint.json @@ -0,0 +1,74 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyShapeConstraint.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyShapeConstraint", + "description": "One constraint of an ontology shape: the values a property may take on instances of the shape's target class.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyShapeConstraint", + "definitions": { + "value": { + "description": "A node a constraint accepts: an IRI or a literal, never both.", + "javaType": "org.openmetadata.schema.type.OntologyShapeValue", + "type": "object", + "properties": { + "iri": { + "$ref": "ontologyIri.json" + }, + "literal": { + "$ref": "ontologyExpression.json#/definitions/literal" + } + }, + "additionalProperties": false + } + }, + "properties": { + "id": { + "description": "Identity of the constraint inside its shape. It stays the same when the constraint is edited.", + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$" + }, + "path": { + "description": "Full IRI of the ontology property the constraint applies to.", + "$ref": "ontologyIri.json" + }, + "minCount": { + "type": "integer", + "minimum": 0 + }, + "maxCount": { + "type": "integer", + "minimum": 0 + }, + "classIri": { + "description": "Every value must be an instance of this class.", + "$ref": "ontologyIri.json" + }, + "datatypeIri": { + "description": "Every value must be a literal of this datatype.", + "$ref": "ontologyIri.json" + }, + "minInclusive": { + "$ref": "ontologyExpression.json#/definitions/literal" + }, + "maxInclusive": { + "$ref": "ontologyExpression.json#/definitions/literal" + }, + "in": { + "description": "Every value must be one of these nodes.", + "type": "array", + "items": { + "$ref": "#/definitions/value" + }, + "default": null + }, + "pattern": { + "description": "Every value's lexical form must match this regular expression.", + "type": "string" + } + }, + "required": [ + "id", + "path" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl index ec7c7d3df04c..891a2d117371 100644 --- a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl +++ b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl @@ -2283,6 +2283,18 @@ om:axiomType a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "axiomType" . +om:constraints a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "constraints" . + +om:severity a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "severity" . + +om:targetConcept a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "targetConcept" . + om:baseModel a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "baseModel" . From 69aaeeb0a89113a38c7ef95c598cfd6754cca66d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 21:08:08 -0800 Subject: [PATCH 007/203] migrations: shape table in 2.2.0 and a step that adds the shape resource to seeded ontology policies --- .../native/2.1.0/mysql/schemaChanges.sql | 19 -- .../native/2.1.0/postgres/schemaChanges.sql | 19 -- .../native/2.2.0/mysql/schemaChanges.sql | 18 ++ .../native/2.2.0/postgres/schemaChanges.sql | 18 ++ .../tests/OntologyShapePolicyMigrationIT.java | 223 ++++++++++++++++++ .../migration/mysql/v220/Migration.java | 38 +++ .../migration/postgres/v220/Migration.java | 38 +++ .../utils/v220/OntologyShapePolicyRules.java | 135 +++++++++++ .../data/policy/OntologyAuthorPolicy.json | 2 +- .../json/data/role/OntologyAuthor.json | 2 +- 10 files changed, 472 insertions(+), 40 deletions(-) create mode 100644 bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql create mode 100644 bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapePolicyMigrationIT.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v220/Migration.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v220/Migration.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v220/OntologyShapePolicyRules.java diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql index 71856cfa3971..5d603c4caa68 100644 --- a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql @@ -1240,22 +1240,3 @@ DEALLOCATE PREPARE context_file_visibility_stmt; -- Flowable schema upgrades run after this migration and inherit the database default. Existing -- ACT_* tables are aligned to the same collation by FlowableCharsetMigration. ALTER DATABASE CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci; - --- Shapes: SHACL node shapes of an ontology, each targeting one class and listing constraints on --- its properties. They are working content, sealed into releases as SHAPE members. --- ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints -CREATE TABLE IF NOT EXISTS ontology_shape_entity ( - id varchar(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.id'))) STORED NOT NULL, - name varchar(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.name'))) STORED NOT NULL, - fqnHash varchar(768) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - json json NOT NULL, - ontologyId varchar(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.ontology.id'))) STORED NOT NULL, - updatedAt bigint unsigned GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.updatedAt'))) STORED NOT NULL, - updatedBy varchar(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.updatedBy'))) STORED NOT NULL, - deleted tinyint(1) GENERATED ALWAYS AS (json_extract(json, '$.deleted')) STORED, - PRIMARY KEY (id), - UNIQUE KEY ontology_shape_fqn_hash_unique (fqnHash), - KEY ontology_shape_name_index (name), - KEY ontology_shape_listing_index (ontologyId, deleted, name, id), - KEY ontology_shape_deleted_index (deleted) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql index 697a7b4f013f..ae5a9d4cd6a9 100644 --- a/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql @@ -938,22 +938,3 @@ ALTER TABLE mcp_pending_auth_requests ALTER TABLE context_file ADD COLUMN IF NOT EXISTS visibility VARCHAR(16) GENERATED ALWAYS AS (json -> 'shareConfig' ->> 'visibility') STORED; CREATE INDEX IF NOT EXISTS idx_context_file_visibility ON context_file (visibility); - --- Shapes: SHACL node shapes of an ontology, each targeting one class and listing constraints on --- its properties. They are working content, sealed into releases as SHAPE members. --- ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints -CREATE TABLE IF NOT EXISTS ontology_shape_entity ( - id VARCHAR(36) GENERATED ALWAYS AS (json ->> 'id') STORED NOT NULL, - name VARCHAR(256) GENERATED ALWAYS AS (json ->> 'name') STORED NOT NULL, - fqnHash VARCHAR(768) NOT NULL, - json JSONB NOT NULL, - ontologyId VARCHAR(36) GENERATED ALWAYS AS (json -> 'ontology' ->> 'id') STORED NOT NULL, - updatedAt BIGINT GENERATED ALWAYS AS ((json ->> 'updatedAt')::bigint) STORED NOT NULL, - updatedBy VARCHAR(256) GENERATED ALWAYS AS (json ->> 'updatedBy') STORED NOT NULL, - deleted BOOLEAN GENERATED ALWAYS AS ((json ->> 'deleted')::boolean) STORED, - PRIMARY KEY (id), - CONSTRAINT ontology_shape_fqn_hash_unique UNIQUE (fqnHash) -); -CREATE INDEX IF NOT EXISTS ontology_shape_name_index ON ontology_shape_entity (name); -CREATE INDEX IF NOT EXISTS ontology_shape_listing_index ON ontology_shape_entity (ontologyId, deleted, name, id); -CREATE INDEX IF NOT EXISTS ontology_shape_deleted_index ON ontology_shape_entity (deleted); diff --git a/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql new file mode 100644 index 000000000000..4fabcace7057 --- /dev/null +++ b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql @@ -0,0 +1,18 @@ +-- Shapes: SHACL node shapes of an ontology, each targeting one class and listing constraints on +-- its properties. They are working content, sealed into releases as SHAPE members. +-- ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints +CREATE TABLE IF NOT EXISTS ontology_shape_entity ( + id varchar(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.id'))) STORED NOT NULL, + name varchar(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.name'))) STORED NOT NULL, + fqnHash varchar(768) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + json json NOT NULL, + ontologyId varchar(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.ontology.id'))) STORED NOT NULL, + updatedAt bigint unsigned GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.updatedAt'))) STORED NOT NULL, + updatedBy varchar(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.updatedBy'))) STORED NOT NULL, + deleted tinyint(1) GENERATED ALWAYS AS (json_extract(json, '$.deleted')) STORED, + PRIMARY KEY (id), + UNIQUE KEY ontology_shape_fqn_hash_unique (fqnHash), + KEY ontology_shape_name_index (name), + KEY ontology_shape_listing_index (ontologyId, deleted, name, id), + KEY ontology_shape_deleted_index (deleted) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql new file mode 100644 index 000000000000..af3f6b48b536 --- /dev/null +++ b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql @@ -0,0 +1,18 @@ +-- Shapes: SHACL node shapes of an ontology, each targeting one class and listing constraints on +-- its properties. They are working content, sealed into releases as SHAPE members. +-- ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints +CREATE TABLE IF NOT EXISTS ontology_shape_entity ( + id VARCHAR(36) GENERATED ALWAYS AS (json ->> 'id') STORED NOT NULL, + name VARCHAR(256) GENERATED ALWAYS AS (json ->> 'name') STORED NOT NULL, + fqnHash VARCHAR(768) NOT NULL, + json JSONB NOT NULL, + ontologyId VARCHAR(36) GENERATED ALWAYS AS (json -> 'ontology' ->> 'id') STORED NOT NULL, + updatedAt BIGINT GENERATED ALWAYS AS ((json ->> 'updatedAt')::bigint) STORED NOT NULL, + updatedBy VARCHAR(256) GENERATED ALWAYS AS (json ->> 'updatedBy') STORED NOT NULL, + deleted BOOLEAN GENERATED ALWAYS AS ((json ->> 'deleted')::boolean) STORED, + PRIMARY KEY (id), + CONSTRAINT ontology_shape_fqn_hash_unique UNIQUE (fqnHash) +); +CREATE INDEX IF NOT EXISTS ontology_shape_name_index ON ontology_shape_entity (name); +CREATE INDEX IF NOT EXISTS ontology_shape_listing_index ON ontology_shape_entity (ontologyId, deleted, name, id); +CREATE INDEX IF NOT EXISTS ontology_shape_deleted_index ON ontology_shape_entity (deleted); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapePolicyMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapePolicyMigrationIT.java new file mode 100644 index 000000000000..c3d83aa716a3 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapePolicyMigrationIT.java @@ -0,0 +1,223 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.migration.utils.v220.OntologyShapePolicyRules; +import org.openmetadata.service.security.policyevaluator.SubjectCache; + +/** + * Exercises the 2.2.0 step that adds the shape resource to the seeded author and reviewer + * policies, against the real database. A policy created by an earlier release keeps its old rule, + * because seeding creates a policy only when it is missing. + */ +@Isolated("rewrites seeded policies that every user of the shared server is evaluated against") +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapePolicyMigrationIT extends BaseOntologyApprovalIT { + private static final HttpClient HTTP = HttpClient.newHttpClient(); + private static final String RESOURCE = "ontologyShape"; + private static final String AUTHOR_POLICY = "OntologyAuthorPolicy"; + private static final String AUTHOR_RULE = "OntologyAuthorPolicy-AuthorRule"; + private static final String REVIEWER_POLICY = "OntologyReviewerPolicy"; + private static final String REVIEWER_RULE = "OntologyReviewerPolicy-ViewRule"; + + @Test + void upgradeGivesAuthorsTheShapeRightOnceAndLeavesTheOtherRulesAlone(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final User author = createAuthor(ns); + final String body = JsonUtils.pojoToJson(shape(ontology, "UpgradedAuthorShape")); + removeResource(AUTHOR_POLICY, AUTHOR_RULE); + removeResource(REVIEWER_POLICY, REVIEWER_RULE); + final List releaseRuleBefore = + resources(AUTHOR_POLICY, "OntologyAuthorPolicy-ReleaseRule"); + assertEquals(403, createShape(author, body), "an upgraded install starts without the right"); + + try { + step(); + step(); + + assertEquals( + 1, resources(AUTHOR_POLICY, AUTHOR_RULE).stream().filter(RESOURCE::equals).count()); + assertEquals( + 1, resources(REVIEWER_POLICY, REVIEWER_RULE).stream().filter(RESOURCE::equals).count()); + assertEquals( + List.of( + "ontology", + "ontologyAxiom", + "ontologyChangeSet", + "ontologyConcept", + "ontologyProperty", + RESOURCE), + resources(AUTHOR_POLICY, AUTHOR_RULE).stream().sorted().toList()); + assertEquals(releaseRuleBefore, resources(AUTHOR_POLICY, "OntologyAuthorPolicy-ReleaseRule")); + assertEquals(201, createShape(author, body)); + } finally { + step(); + } + } + + private static void step() { + final ConnectionType engine = + "mysql".equalsIgnoreCase(System.getProperty("databaseType", "postgres")) + ? ConnectionType.MYSQL + : ConnectionType.POSTGRES; + TestSuiteBootstrap.getJdbi() + .useHandle(handle -> OntologyShapePolicyRules.addShapeResource(handle, engine)); + evictPolicies(); + } + + /** Writes the rule as a release before this resource existed listed it. */ + private static void removeResource(final String policy, final String rule) { + final JsonNode stored = readPolicy(policy); + final ArrayNode resources = (ArrayNode) ruleOf(stored, rule).get("resources"); + for (int index = resources.size() - 1; index >= 0; index--) { + if (RESOURCE.equals(resources.get(index).asText())) { + resources.remove(index); + } + } + final String json = stored.toString(); + final String cast = + "mysql".equalsIgnoreCase(System.getProperty("databaseType", "postgres")) + ? ":json" + : "CAST(:json AS jsonb)"; + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> + handle + .createUpdate("UPDATE policy_entity SET json = " + cast + " WHERE name = :name") + .bind("json", json) + .bind("name", policy) + .execute()); + evictPolicies(); + } + + private static List resources(final String policy, final String rule) { + final List names = new ArrayList<>(); + ruleOf(readPolicy(policy), rule).get("resources").forEach(node -> names.add(node.asText())); + return names; + } + + private static JsonNode ruleOf(final JsonNode policy, final String rule) { + for (final JsonNode candidate : policy.get("rules")) { + if (rule.equals(candidate.get("name").asText())) { + return candidate; + } + } + throw new IllegalStateException("No rule " + rule); + } + + private static JsonNode readPolicy(final String policy) { + return JsonUtils.readTree( + TestSuiteBootstrap.getJdbi() + .withHandle( + handle -> + handle + .createQuery("SELECT json FROM policy_entity WHERE name = :name") + .bind("name", policy) + .mapTo(String.class) + .one())); + } + + /** A restart reads the rows again; this server keeps the policies it already loaded. */ + private static void evictPolicies() { + for (final String name : List.of(AUTHOR_POLICY, REVIEWER_POLICY)) { + final var policy = SdkClients.adminClient().policies().getByName(name); + EntityRepository.invalidateCacheForEntity( + Entity.POLICY, policy.getId(), policy.getFullyQualifiedName()); + } + SubjectCache.invalidateAll(); + } + + private static CreateOntologyShape shape(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("A shape created by an author of an upgraded install") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(URI.create("https://example.org/model/Person")) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("name-count") + .withPath(URI.create("https://example.org/model/name")) + .withMinCount(1))); + } + + private static User createAuthor(final TestNamespace ns) { + final String name = ns.shortPrefix("upgradedAuthor"); + return ns.trackRoot( + Entity.USER, + SdkClients.adminClient() + .users() + .create( + new CreateUser() + .withName(name) + .withEmail(name + "@test.om.org") + .withDescription("author of an upgraded install") + .withRoles( + List.of( + SdkClients.adminClient() + .roles() + .getByName("OntologyAuthor") + .getId())))); + } + + private static int createShape(final User user, final String body) { + final String token = + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 600); + try { + return HTTP.send( + HttpRequest.newBuilder() + .uri(URI.create(SdkClients.getServerUrl() + "/v1/ontologyShapes")) + .header("Authorization", "Bearer " + token) + .header("Content-Type", "application/json") + .timeout(Duration.ofSeconds(60)) + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(), + HttpResponse.BodyHandlers.ofString()) + .statusCode(); + } catch (java.io.IOException | InterruptedException e) { + throw new IllegalStateException("POST /v1/ontologyShapes", e); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v220/Migration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v220/Migration.java new file mode 100644 index 000000000000..18fbac8363c5 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v220/Migration.java @@ -0,0 +1,38 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.migration.mysql.v220; + +import static org.openmetadata.service.jdbi3.locator.ConnectionType.MYSQL; +import static org.openmetadata.service.migration.utils.DataMigrationStep.runOnce; + +import org.openmetadata.service.migration.api.MigrationProcessImpl; +import org.openmetadata.service.migration.utils.MigrationFile; +import org.openmetadata.service.migration.utils.v220.OntologyShapePolicyRules; + +public class Migration extends MigrationProcessImpl { + public Migration(final MigrationFile migrationFile) { + super(migrationFile); + } + + @Override + public void runDataMigration() { + // Seeded policies are created only when missing, so the ontology author and reviewer policies + // of an installed catalog gain the shape resource here. Idempotent. + runOnce( + migrationDAO, + getVersion(), + OntologyShapePolicyRules.STEP_NAME, + () -> OntologyShapePolicyRules.addShapeResource(handle, MYSQL)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v220/Migration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v220/Migration.java new file mode 100644 index 000000000000..148bd2b200a2 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v220/Migration.java @@ -0,0 +1,38 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.migration.postgres.v220; + +import static org.openmetadata.service.jdbi3.locator.ConnectionType.POSTGRES; +import static org.openmetadata.service.migration.utils.DataMigrationStep.runOnce; + +import org.openmetadata.service.migration.api.MigrationProcessImpl; +import org.openmetadata.service.migration.utils.MigrationFile; +import org.openmetadata.service.migration.utils.v220.OntologyShapePolicyRules; + +public class Migration extends MigrationProcessImpl { + public Migration(final MigrationFile migrationFile) { + super(migrationFile); + } + + @Override + public void runDataMigration() { + // Seeded policies are created only when missing, so the ontology author and reviewer policies + // of an installed catalog gain the shape resource here. Idempotent. + runOnce( + migrationDAO, + getVersion(), + OntologyShapePolicyRules.STEP_NAME, + () -> OntologyShapePolicyRules.addShapeResource(handle, POSTGRES)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v220/OntologyShapePolicyRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v220/OntologyShapePolicyRules.java new file mode 100644 index 000000000000..1911c7094dc9 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v220/OntologyShapePolicyRules.java @@ -0,0 +1,135 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.migration.utils.v220; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.List; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.jdbi.v3.core.Handle; +import org.openmetadata.service.jdbi3.locator.ConnectionType; + +/** + * Adds the {@code ontologyShape} resource to the rules of the seeded ontology author and reviewer + * policies on an installed catalog. + * + *

A seeded policy is created only when it is missing, so a policy created by an earlier release + * never picks up a resource added to its seed. The step changes one rule of each policy, and only + * when that rule exists and does not list the resource yet, so a second run changes nothing and an + * administrator's other edits are left as they are. A policy that does not exist yet is not + * created: seeding creates it with the new list. + */ +@Slf4j +public final class OntologyShapePolicyRules { + + /** Run once per version through {@code DataMigrationStep}. */ + public static final String STEP_NAME = "ontology-shape-policy-rules"; + + static final String RESOURCE = "ontologyShape"; + + /** Seeded policy name to the name of the rule that lists the ontology resources. */ + static final Map RULES = + Map.of( + "OntologyAuthorPolicy", "OntologyAuthorPolicy-AuthorRule", + "OntologyReviewerPolicy", "OntologyReviewerPolicy-ViewRule"); + + private static final String POLICY_TABLE = "policy_entity"; + private static final String RULES_FIELD = "rules"; + private static final String NAME_FIELD = "name"; + private static final String RESOURCES_FIELD = "resources"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private OntologyShapePolicyRules() {} + + public static void addShapeResource(final Handle handle, final ConnectionType connectionType) { + RULES.forEach((policy, rule) -> addToRule(handle, connectionType, policy, rule)); + } + + private static void addToRule( + final Handle handle, + final ConnectionType connectionType, + final String policyName, + final String ruleName) { + final List> rows = + handle + .createQuery("SELECT id, json FROM " + POLICY_TABLE + " WHERE name = :name") + .bind("name", policyName) + .mapToMap() + .list(); + for (final Map row : rows) { + final JsonNode policy = parse(row.get("json")); + if (policy instanceof ObjectNode && listResource((ObjectNode) policy, ruleName)) { + store(handle, connectionType, String.valueOf(row.get("id")), policy); + LOG.info("Added {} to rule {} of {}", RESOURCE, ruleName, policyName); + } + } + } + + /** Returns true when the rule exists, lists its resources and the resource was added to them. */ + private static boolean listResource(final ObjectNode policy, final String ruleName) { + final JsonNode rules = policy.get(RULES_FIELD); + if (rules == null || !rules.isArray()) { + return false; + } + for (final JsonNode rule : rules) { + if (ruleName.equals(rule.path(NAME_FIELD).asText()) && rule.get(RESOURCES_FIELD) != null) { + return append(rule.get(RESOURCES_FIELD)); + } + } + return false; + } + + private static boolean append(final JsonNode resources) { + if (!resources.isArray() || contains(resources)) { + return false; + } + ((ArrayNode) resources).add(RESOURCE); + return true; + } + + private static boolean contains(final JsonNode resources) { + for (final JsonNode resource : resources) { + if (RESOURCE.equals(resource.asText())) { + return true; + } + } + return false; + } + + private static JsonNode parse(final Object json) { + try { + return MAPPER.readTree(String.valueOf(json)); + } catch (com.fasterxml.jackson.core.JsonProcessingException exception) { + throw new IllegalStateException("A stored policy is not valid JSON", exception); + } + } + + private static void store( + final Handle handle, + final ConnectionType connectionType, + final String id, + final JsonNode policy) { + final String sql = + switch (connectionType) { + case MYSQL -> "UPDATE " + POLICY_TABLE + " SET json = :json WHERE id = :id"; + case POSTGRES -> "UPDATE " + + POLICY_TABLE + + " SET json = CAST(:json AS jsonb) WHERE id = :id"; + }; + handle.createUpdate(sql).bind("json", policy.toString()).bind("id", id).execute(); + } +} diff --git a/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json b/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json index d1a2072f7093..625e3c343c21 100644 --- a/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json +++ b/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json @@ -2,7 +2,7 @@ "name": "OntologyAuthorPolicy", "displayName": "Ontology Author Policy", "fullyQualifiedName": "OntologyAuthorPolicy", - "description": "Policy for authoring ontologies: create, edit and delete ontologies, concepts, properties, axioms and change sets, read releases, and request a release review.", + "description": "Policy for authoring ontologies: create, edit and delete ontologies, concepts, properties, axioms, shapes and change sets, read releases, and request a release review.", "enabled": true, "allowDelete": false, "provider": "system", diff --git a/openmetadata-service/src/main/resources/json/data/role/OntologyAuthor.json b/openmetadata-service/src/main/resources/json/data/role/OntologyAuthor.json index 1262d96b9174..4d2dcdbc72aa 100644 --- a/openmetadata-service/src/main/resources/json/data/role/OntologyAuthor.json +++ b/openmetadata-service/src/main/resources/json/data/role/OntologyAuthor.json @@ -1,7 +1,7 @@ { "name": "OntologyAuthor", "displayName": "Ontology Author", - "description": "Users with the Ontology Author role create and edit ontologies, concepts, properties and axioms, capture releases, and request their review.", + "description": "Users with the Ontology Author role create and edit ontologies, concepts, properties, axioms and shapes, capture releases, and request their review.", "allowDelete": false, "provider": "system", "policies": [ From b661a95b5adfd8a5d2ab6027d781521b8ecd69a3 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 21:17:43 -0800 Subject: [PATCH 008/203] Ontology: pin the sibling read to the target index on MySQL, and apply a forged domain change in the display-name test On MySQL the locking sibling read switched to a scan of every ontology's property references for a heavily referenced class and locked all of them, blocking writers to other ontologies. FORCE INDEX keeps the read, and its locks, inside the ontology. The Postgres statement is unchanged. The CSV domain test now applies a forged update that adds the domain class and asserts the refusal. --- ...NativeOntologyPartialImportPropertyIT.java | 45 +++++++++++++++++-- .../service/jdbi3/OntologyReferenceDAO.java | 19 +++++--- 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java index a76885f494b9..459c9b4a74de 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java @@ -190,8 +190,9 @@ void aCsvRowThatMakesTheFlaggedPropertyAnObjectPropertyIsPreviewedAndAppliedWith } @Test - void aCsvRowThatAddsADomainClassWithADisplayNamePropertyIsRefusedByPreviewAndApply( - TestNamespace ns) { + void + aCsvRowThatAddsADomainClassWithADisplayNamePropertyIsRefusedByPreviewAndAForgedUpdateIsRefusedByApply( + TestNamespace ns) { final var client = SdkClients.adminClient(); final Ontology ontology = createOntology(ns, "domainSibling"); final String both = @@ -226,9 +227,45 @@ void aCsvRowThatAddsADomainClassWithADisplayNamePropertyIsRefusedByPreviewAndApp assertEquals(NativeOntologyImportItemStatus.SKIPPED, item.getStatus()); assertTrue(item.getReason().contains("at most one display-name property"), item.getReason()); assertEquals(0, preview.getChangeSet().getOperations().size()); + final URI account = + URI.create("https://example.org/displayNames/" + ns.shortPrefix() + "/Account"); + final URI ledger = + URI.create("https://example.org/displayNames/" + ns.shortPrefix() + "/Ledger"); + assertEquals(List.of(account), storedProperty(ontology, "accountName").getDomain()); + + final NativeOntologyImportPreview described = + client + .ontologies() + .previewImport( + ontology.getId(), + csvOf( + ns, + both.replace( + "rdfs:label \"accountName\" ;", + "rdfs:label \"accountName\" ; rdfs:comment \"The account name\" ;"))); + final OntologyChangeOperation forged = + JsonUtils.deepCopy( + described.getChangeSet().getOperations().stream() + .filter(operation -> operation.getProperty() != null) + .findFirst() + .orElseThrow(), + OntologyChangeOperation.class); + assertEquals(1, described.getChangeSet().getOperations().size()); + forged.getProperty().setDomain(List.of(account, ledger)); + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> apply(ns, ontology, described, List.of(forged), "forgedDomain")); + + assertEquals(400, refusal.getStatusCode()); assertEquals( - List.of(URI.create("https://example.org/displayNames/" + ns.shortPrefix() + "/Account")), - storedProperty(ontology, "accountName").getDomain()); + "Ontology validation failed: A class has at most one display-name property, but " + + account.toString().replace("/Account", "/accountName") + + " and " + + account.toString().replace("/Account", "/ledgerName") + + " both name the same class", + refusal.getMessage()); + assertEquals(List.of(account), storedProperty(ontology, "accountName").getDomain()); } private static OntologyProperty storedProperty(Ontology ontology, String name) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java index 9a5f09976f1b..f442795b986b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java @@ -105,9 +105,10 @@ List referencingForUpdate( @BindList("iriHashes") List iriHashes, @Bind("limit") int limit); - String SIBLINGS_FROM = - "SELECT p.json FROM ontology_property_entity p JOIN ontology_reference r " - + "ON r.sourceId = p.id AND r.ontologyId = p.ontologyId " + String SIBLINGS_SELECT = + "SELECT p.json FROM ontology_property_entity p JOIN ontology_reference r "; + String SIBLINGS_JOIN_ON = + "ON r.sourceId = p.id AND r.ontologyId = p.ontologyId " + "WHERE p.ontologyId = :ontologyId AND p.deleted = FALSE AND "; String SIBLINGS_WHERE = " AND r.sourceType = 'ontologyProperty' AND r.role = 'DOMAIN' AND r.iriHash IN () " @@ -120,14 +121,22 @@ List referencingForUpdate( * A property with several matching domain classes comes back once per match, and the caller drops * the repeats, because Postgres rejects {@code FOR UPDATE} with {@code DISTINCT}. */ + // The index keeps the locking read inside the ontology's key range. Without it MySQL scans every + // ontology's references for a heavily referenced class and locks them all. @ConnectionAwareSqlQuery( value = - SIBLINGS_FROM + SIBLINGS_SELECT + + "FORCE INDEX (ontology_reference_target_index) " + + SIBLINGS_JOIN_ON + "JSON_UNQUOTE(JSON_EXTRACT(p.json, '$.isDisplayName')) = 'true'" + SIBLINGS_WHERE, connectionType = MYSQL) @ConnectionAwareSqlQuery( - value = SIBLINGS_FROM + "p.json ->> 'isDisplayName' = 'true'" + SIBLINGS_WHERE, + value = + SIBLINGS_SELECT + + SIBLINGS_JOIN_ON + + "p.json ->> 'isDisplayName' = 'true'" + + SIBLINGS_WHERE, connectionType = POSTGRES) List displayNameSiblings( @BindUUID("ontologyId") UUID ontologyId, From 0a6f9311c03517712d557a8bdadc50adaaa2fe25 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 21:26:24 -0800 Subject: [PATCH 009/203] ontology shapes: guard referenced definitions, bounded atomic import, readable reports, status and policy upgrade --- ...nitions-have-independent-entity-storage.md | 11 +- ...working-draft-reads-require-edit-rights.md | 19 +- ...es-hold-the-supported-shacl-constraints.md | 44 +++- ...ndependentOntologyShapeDeleteImpactIT.java | 192 ++++++++++++++++ .../IndependentOntologyShapeStatusIT.java | 150 +++++++++++++ .../it/tests/OntologyShapeResourceIT.java | 118 ++++++++++ .../jdbi3/OntologyConceptRepository.java | 1 + .../service/jdbi3/OntologyReferenceDAO.java | 12 + .../service/jdbi3/OntologyReferenceIndex.java | 6 +- .../service/jdbi3/OntologyRepository.java | 18 +- .../service/jdbi3/OntologyWorkingModel.java | 45 ++++ .../service/ontology/OntologyReferences.java | 23 +- .../service/ontology/OntologyShapeRules.java | 26 +++ .../ontology/OntologyStructureValidator.java | 6 + .../ontology/OntologyUnpublishedChanges.java | 1 + .../service/rdf/OntologyShaclReader.java | 190 ++++++++++------ .../ontology/OntologyShapeResource.java | 47 +++- .../migration/MigrationArchitectureTest.java | 2 +- .../ontology/OntologyReferencesTest.java | 34 +++ .../ontology/OntologyShapeRulesTest.java | 34 +++ .../ontology/OntologyShapeValidationTest.java | 14 +- .../OntologyStructureValidatorTest.java | 33 +++ .../service/rdf/OntologyShaclReaderTest.java | 211 ++++++++++++++++++ 23 files changed, 1148 insertions(+), 89 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeDeleteImpactIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeStatusIT.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclReaderTest.java diff --git a/docs/decisions/2026-10-14-ontology-definitions-have-independent-entity-storage.md b/docs/decisions/2026-10-14-ontology-definitions-have-independent-entity-storage.md index 59cc73f98382..f8a7d5af34ce 100644 --- a/docs/decisions/2026-10-14-ontology-definitions-have-independent-entity-storage.md +++ b/docs/decisions/2026-10-14-ontology-definitions-have-independent-entity-storage.md @@ -1,7 +1,7 @@ # Ontology definitions use independent entity storage - **Status:** Accepted -- **Revisions:** v1 2026-10-14 (initial) · v2 2026-10-14 (semantic identity) · v3 2026-10-14 (native IRI creation) · v4 2026-10-14 (client IRI fidelity) · v5 2026-10-15 (native axiom ownership) · v6 2026-10-15 (derived reference index) · v7 2026-10-15 (unreleased 2.1.0 migrations and scoped axiom reset) · v8 2026-10-15 (metadata usage search by concept UUID) · v9 2026-10-15 (shared search and CSV definitions) · v10 2026-10-15 (release-only review and affected-definition validation) · v11 2026-10-15 (metadata annotations moved to a follow-up) +- **Revisions:** v1 2026-10-14 (initial) · v2 2026-10-14 (semantic identity) · v3 2026-10-14 (native IRI creation) · v4 2026-10-14 (client IRI fidelity) · v5 2026-10-15 (native axiom ownership) · v6 2026-10-15 (derived reference index) · v7 2026-10-15 (unreleased 2.1.0 migrations and scoped axiom reset) · v8 2026-10-15 (metadata usage search by concept UUID) · v9 2026-10-15 (shared search and CSV definitions) · v10 2026-10-15 (release-only review and affected-definition validation) · v11 2026-10-15 (metadata annotations moved to a follow-up) · v12 2026-11-21 (2.1.0 has shipped) - **Deciders:** Harsha - **Guard:** `OntologyEntityDAOTest`, `OntologyDefinitionTest`, `CollectionDAOCompositionTest`, `IndependentOntologyAxiomIT`, `OntologyReferencesTest`, `OntologyReferenceDAOTest`, `OntologyReleaseCaptureTest`, `IndependentOntologyReferenceIT` - **Related:** [Organizational ontology design](../plans/2026-10-14-organizational-ontology-design.md) @@ -136,3 +136,12 @@ through the reference index. These reads share the ontology state lock; MySQL re recently committed changes use locking reads, including both sides of the reference/axiom join. Cycle detection identifies every member of a strongly connected component without recursion. An invalid unrelated draft does not prevent repairs. Capture still validates the complete model. + +## Amendment: 2.1.0 has shipped + +The "unreleased 2.1.0 migrations" of v7 no longer hold. 2.1.0 shipped as the final release +`2.1.0-release` on 2026-11-20, so its migration folder is closed: a database that has run it never +reads an earlier folder again, and a statement added to it would run only on a database that +upgrades from before 2.1.0. Ontology tables and indexes added after that date go in the next +folder that has not shipped, starting with `2.2.0`, and a data change to a seeded row needs its +own `runOnce` step in that release. The shape table is the first to follow this. diff --git a/docs/decisions/2026-11-03-ontology-working-draft-reads-require-edit-rights.md b/docs/decisions/2026-11-03-ontology-working-draft-reads-require-edit-rights.md index 9d4825318621..9da586cf61f6 100644 --- a/docs/decisions/2026-11-03-ontology-working-draft-reads-require-edit-rights.md +++ b/docs/decisions/2026-11-03-ontology-working-draft-reads-require-edit-rights.md @@ -1,9 +1,9 @@ # Reading an ontology's working draft requires EditAll on the ontology - **Status:** Accepted -- **Revisions:** v1 2026-11-03 (initial); v2 2026-11-03 (change sets); v3 2026-11-05 (rows of an unscoped list); v3 amended 2026-11-05 (glossary scopes taken from the page) +- **Revisions:** v1 2026-11-03 (initial); v2 2026-11-03 (change sets); v3 2026-11-05 (rows of an unscoped list); v3 amended 2026-11-05 (glossary scopes taken from the page); v4 2026-11-21 (shapes) - **Deciders:** Ontology Studio program -- **Guard:** `OntologyResourceAccessTest`, `ListFilterTest`, `IndependentOntologyDraftReadIT`, `IndependentOntologyAuthorizationIT` +- **Guard:** `OntologyResourceAccessTest`, `ListFilterTest`, `IndependentOntologyDraftReadIT`, `IndependentOntologyAuthorizationIT`, `OntologyShapeResourceIT` - **Related:** ADR:2026-11-02-ontology-reviewers-vote-without-edit-rights, `OntologyResourceAccess.requireDraftRead`, `useOntologyStudioModel.ts`, `OntologyMemoryReviewPanel.tsx` ## Context @@ -20,7 +20,8 @@ endpoints and not others. release, its members, release export, release-scoped SPARQL) keep view access. - The rule covers `POST /v1/ontologies/{id}/sparql?scope=draft`, `GET .../working/diff`, `GET .../working/validation`, `GET .../export`, `GET .../references`, and the lists - `GET /v1/ontologyConcepts`, `/v1/ontologyProperties` and `/v1/ontologyAxioms`. + `GET /v1/ontologyConcepts`, `/v1/ontologyProperties`, `/v1/ontologyAxioms` and + `/v1/ontologyShapes`. - A change set holds operations that no release has published, so reading one needs the edit right on its scope, the right `authorizeScope` checks for submit. That covers `GET /v1/ontologyChangeSets/{id}`, `GET .../{id}/versions`, `GET .../{id}/versions/{version}` @@ -44,7 +45,7 @@ endpoints and not others. not filtered, for the reason above. - The existing per-definition view check on the snapshot stays in place after the new check. - Reading one definition by id or name is unchanged: any viewer reads the working version of a - concept, property or axiom, including one no release contains. This is an exception to the rule, + concept, property, axiom or shape, including one no release contains. This is an exception to the rule, kept because deep links and the Studio's concept panel read a single definition this way, and because gating it would need a release-membership lookup on every read. It exposes one definition at a time to a caller who already knows its id or name; it exposes no listing, diff, @@ -66,3 +67,13 @@ endpoints and not others. - Closing the by-id exception needs a membership lookup against the active release and a published-version fallback for the single-definition read. - To revert to view access for a read, change `requireDraftRead` and the Viewer IT together. + +## Amendment: shapes + +A shape (ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints) is working-draft +content, so the rules above cover it. Listing `GET /v1/ontologyShapes`, the draft SHACL export +(`GET /v1/ontologies/{id}/export?format=shacl`) and `POST /v1/ontologyShapes/import` need `EditAll` +on the ontology, as the concept, property and axiom lists do. Reading one shape by id, by name, by +version list or by one version stays open to any viewer, which is the single-definition exception +above applied to shapes. A sealed release exports its shapes as SHACL with the release read rule. +`OntologyShapeResourceIT` and `IndependentOntologyShapeReleaseIT` guard it. diff --git a/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md b/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md index 9347a6f85451..99d15fde0724 100644 --- a/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md +++ b/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md @@ -1,9 +1,9 @@ # Ontology shapes hold eight SHACL constraints, and report every other construct instead of refusing the file - **Status:** Accepted -- **Revisions:** v1 2026-11-21 (initial) +- **Revisions:** v1 2026-11-21 (initial) · v2 2026-11-21 (deletes, import bounds and atomicity, reported constructs, size, upgrade) - **Deciders:** Ontology Studio team -- **Guard:** `OntologyShapeRulesTest`, `OntologyShaclRoundTripTest`, `OntologyShapeValidationTest`, `OntologyShapeResourceIT`, `IndependentOntologyShapeReleaseIT` +- **Guard:** `OntologyShapeRulesTest`, `OntologyShaclRoundTripTest`, `OntologyShapeValidationTest`, `OntologyShapeResourceIT`, `IndependentOntologyShapeReleaseIT`, `IndependentOntologyShapeDeleteImpactIT`, `IndependentOntologyShapeStatusIT`, `OntologyShapePolicyMigrationIT`, `OntologyShaclReaderTest`, `OntologyReferencesTest` - **Related:** ADR:2026-10-14-ontology-definitions-have-independent-entity-storage, ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights ## Context @@ -43,8 +43,8 @@ paths and recursion, and a stored model that held all of that would need a valid `sh:sparql`, `sh:qualifiedValueShape`, `sh:closed`, a path that is not a single IRI, or a second kind of target, is named in the response and left out. It is a report, not an error. A shape the rules above would refuse fails the whole request before anything is written. -- Shapes are left out of the OWL graph projection and of the reference index. They do not change - what the ontology means, so the graph and its disjointness and hierarchy checks stay as they were. +- Shapes are left out of the OWL graph projection. They do not change what the ontology means, so + the graph and its disjointness and hierarchy checks stay as they were. ## Consequences A file with constructs the model does not hold still gives its owner the supported part at once, @@ -53,3 +53,39 @@ imported shape can be weaker than the file's: the report is the only record of t exporting does not bring the lost constructs back. Widening the model later adds fields and reports fewer constructs; it does not change a stored id. A literal written with no datatype and one written as `xsd:string` are the same RDF term, so an export and an import give the first form. + +## Amendment + +A shape names classes and properties, so the reference index holds them: the `targetConcept` and +each `classIri` as `CLASS_EXPRESSION` references and each constraint `path` as a `PROPERTY` +reference. A class or property that a live shape names cannot be deleted. The request returns 400 +and names up to three of the shapes, and `GET /v1/ontologyConcepts/{id}/deleteImpact` lists each +such shape under `blockers`. Deleting or editing the shape first lifts the refusal. Saving stays +lenient: a shape may name a class or property that is declared a moment later, and declaring or +editing a definition never validates the shapes that name it, because one shape with a second +missing reference would then block an unrelated declaration. Capture still fails a dangling shape. + +Shapes import through their own endpoint until change sets carry shape operations. The native +import (ADR:2026-10-19-native-ontology-imports-use-working-drafts) returns a change set for review +before anything is written. This endpoint writes the working draft directly, as saving one shape +does, and takes the same bounds as that import: at most 1,000 shapes, 100,000 statements and +10 MiB, and 30 seconds of parsing, with no relative identifiers or named graphs. It checks every +shape against the entity name rules and the shape rules before it writes anything, and refuses the +whole file with 400 if one fails; a name is never cut to fit, except that the suffix which tells +two equal names apart is fitted to the 256-character limit. The writes then run in one transaction +under the ontology's lock, so a failing request leaves the draft as it was. A `dryRun` request +writes nothing. + +Reading a file reports, rather than guesses at, more than it did. A predicate that holds more than +one value (`sh:class`, `sh:datatype`, `sh:pattern`, `sh:minCount`, `sh:in`, `sh:name` and the +others) is reported under its own name, and the value first in lexical order is kept so the same +file always reads the same. A language-tagged literal in `sh:in`, `sh:minInclusive` or +`sh:maxInclusive` is reported and its constraint left out, because the model holds no language +tag. An `sh:in` list is read cell by cell, at most 1,000 of them, and a list that loops, ends +without `rdf:nil`, lacks a link or is longer is reported and its constraint left out. + +A shape holds at most 200 constraints and at most 1 MiB of JSON, the member limit every other +definition meets, and both are checked when it is saved. A shape beyond either was already unable +to be captured. The table is created by the 2.2.0 migration, because 2.1.0 has shipped. A step in +that release adds `ontologyShape` to the seeded author and reviewer rules of an installed +catalog, since a seeded policy is created only when it is missing. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeDeleteImpactIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeDeleteImpactIT.java new file mode 100644 index 000000000000..f91e3417e724 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeDeleteImpactIT.java @@ -0,0 +1,192 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; + +/** A class or property that a live shape names cannot be deleted; a shape save stays lenient. */ +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyShapeDeleteImpactIT extends BaseOntologyApprovalIT { + + @Test + void deletingAClassAShapeNamesIsRefusedAndListsTheShapeAsABlocker(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept person = declareClass(ontology, "Person", model("Person")); + final OntologyConcept address = declareClass(ontology, "Address", model("Address")); + final OntologyConcept unrelated = declareClass(ontology, "Unrelated", model("Unrelated")); + declareProperty(ontology, "livesAt", OntologyPropertyKind.OBJECT); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(request(ontology, "PersonShape")); + + assertEquals(List.of("PersonShape"), blockers(person.getId())); + assertEquals(List.of("PersonShape"), blockers(address.getId())); + assertEquals(List.of(), blockers(unrelated.getId())); + for (final OntologyConcept named : List.of(person, address)) { + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> SdkClients.adminClient().ontologyConcepts().delete(named.getId())); + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains("'PersonShape'"), refused.getMessage()); + assertFalse( + Boolean.TRUE.equals( + SdkClients.adminClient().ontologyConcepts().get(named.getId()).getDeleted())); + } + SdkClients.adminClient().ontologyConcepts().delete(unrelated.getId()); + + SdkClients.adminClient().ontologyShapes().delete(shape.getId()); + assertEquals(List.of(), blockers(person.getId())); + SdkClients.adminClient().ontologyConcepts().delete(person.getId()); + SdkClients.adminClient().ontologyConcepts().delete(address.getId()); + } + + @Test + void deletingAPropertyAShapeConstrainsIsRefusedUntilTheShapeIsDeleted(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Person", model("Person")); + declareClass(ontology, "Address", model("Address")); + final OntologyProperty livesAt = + declareProperty(ontology, "livesAt", OntologyPropertyKind.OBJECT); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(request(ontology, "PersonShape")); + + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> SdkClients.adminClient().ontologyProperties().delete(livesAt.getId())); + + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains("'PersonShape'"), refused.getMessage()); + SdkClients.adminClient().ontologyShapes().delete(shape.getId()); + SdkClients.adminClient().ontologyProperties().delete(livesAt.getId()); + } + + @Test + void aShapeNamingTwoMissingClassesDoesNotBlockDeclaringOneOfThem(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyShape shape = + SdkClients.adminClient() + .ontologyShapes() + .create( + request(ontology, "AheadOfItsModel") + .withTargetConcept(model("Ghost")) + .withConstraints( + new ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("lives-at") + .withPath(model("livesAt")) + .withClassIri(model("Phantom")))))); + + final OntologyConcept ghost = declareClass(ontology, "Ghost", model("Ghost")); + + assertEquals(model("Ghost"), ghost.getIri()); + assertEquals( + shape.getId(), + SdkClients.adminClient().ontologyShapes().get(shape.getId().toString()).getId()); + } + + @Test + void deletingTheOntologyThatHoldsTheShapeAndItsClassesStillWorks(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Person", model("Person")); + declareClass(ontology, "Address", model("Address")); + declareProperty(ontology, "livesAt", OntologyPropertyKind.OBJECT); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(request(ontology, "PersonShape")); + + SdkClients.adminClient() + .ontologies() + .delete(ontology.getId().toString(), Map.of("recursive", "true")); + + final OpenMetadataException gone = + assertThrows( + OpenMetadataException.class, + () -> SdkClients.adminClient().ontologyShapes().get(shape.getId().toString())); + assertEquals(404, gone.getStatusCode()); + } + + private static List blockers(final UUID conceptId) { + final JsonNode impact = + SdkClients.adminClient() + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyConcepts/" + conceptId + "/deleteImpact", + null, + JsonNode.class); + final List names = new ArrayList<>(); + impact.path("blockers").forEach(blocker -> names.add(blocker.path("name").asText())); + return names; + } + + private static OntologyProperty declareProperty( + final Ontology ontology, final String name, final OntologyPropertyKind kind) { + return SdkClients.adminClient() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName(name) + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model(name)) + .withKind(kind)); + } + + private static CreateOntologyShape request(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("Shape of a person") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(model("Person")) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + new ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("lives-at") + .withPath(model("livesAt")) + .withClassIri(model("Address"))))); + } + + private static URI model(final String name) { + return URI.create("https://example.org/model/" + name); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeStatusIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeStatusIT.java new file mode 100644 index 000000000000..85ae1be5e748 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeStatusIT.java @@ -0,0 +1,150 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseChangeType; +import org.openmetadata.schema.type.OntologyReleaseMemberChange; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.sdk.models.ListParams; + +/** What a shape edit does to the working state, the working diff and the publication status. */ +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyShapeStatusIT extends BaseOntologyApprovalIT { + + @Test + void editingASealedShapeIsOneUnpublishedChangeOnTheSingleReadAndOnTheList( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(request(ontology, "PersonShape")); + activate(ns, ontology); + assertEquals(0, unpublishedOnSingleRead(ontology)); + assertEquals(0, unpublishedOnList(ontology)); + + SdkClients.adminClient() + .ontologyShapes() + .update(shape.getId(), shape.withSeverity(OntologyShapeSeverity.WARNING)); + + assertEquals(1, unpublishedOnSingleRead(ontology)); + assertEquals(1, unpublishedOnList(ontology)); + } + + @Test + void everyShapeWriteMovesTheWorkingRevisionAndTheWorkingDiffListsTheEditedShape( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final var service = SdkClients.adminClient().ontologyShapes(); + long revision = workingRevision(ontology); + + final OntologyShape shape = service.create(request(ontology, "PersonShape")); + final long afterCreate = workingRevision(ontology); + assertTrue(afterCreate > revision, "create"); + + activate(ns, ontology); + final long afterActivation = workingRevision(ontology); + service.update(shape.getId(), shape.withSeverity(OntologyShapeSeverity.WARNING)); + final long afterUpdate = workingRevision(ontology); + assertTrue(afterUpdate > afterActivation, "update"); + final List diff = + SdkClients.adminClient().ontologies().workingDiff(ontology.getId(), 100, null).getData(); + assertEquals( + List.of("SHAPE:CHANGED:" + shape.getId()), + diff.stream() + .map( + row -> + row.getMemberKind() + ":" + row.getChangeType() + ":" + row.getEntity().getId()) + .toList()); + assertEquals(OntologyReleaseChangeType.CHANGED, diff.getFirst().getChangeType()); + + service.delete(shape.getId().toString()); + assertTrue(workingRevision(ontology) > afterUpdate, "delete"); + } + + private static int unpublishedOnSingleRead(final Ontology ontology) { + return SdkClients.adminClient() + .ontologies() + .get(ontology.getId().toString(), "publicationStatus") + .getPublicationStatus() + .getUnpublishedChanges(); + } + + private static int unpublishedOnList(final Ontology ontology) { + return SdkClients.adminClient() + .ontologies() + .list(new ListParams().setLimit(1000).setFields("publicationStatus")) + .getData() + .stream() + .filter(listed -> listed.getId().equals(ontology.getId())) + .findFirst() + .orElseThrow() + .getPublicationStatus() + .getUnpublishedChanges(); + } + + private static long workingRevision(final Ontology ontology) { + return SdkClients.adminClient().ontologies().state(ontology.getId()).getWorkingRevision(); + } + + private static void declareModel(final Ontology ontology) { + declareClass(ontology, "Person", model("Person")); + SdkClients.adminClient() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("name") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("name")) + .withKind(OntologyPropertyKind.DATA)); + } + + private static CreateOntologyShape request(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("Shape of a person") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(model("Person")) + .withSeverity(OntologyShapeSeverity.INFO) + .withConstraints( + new ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("has-name") + .withPath(model("name")) + .withMinCount(1)))); + } + + private static URI model(final String name) { + return URI.create("https://example.org/model/" + name); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java index 2527d0ebd142..bebdcd5907f2 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java @@ -51,6 +51,9 @@ import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.sdk.network.RequestOptions; import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyRepository; +import org.openmetadata.service.jdbi3.OntologyShapeRepository; +import org.openmetadata.service.resources.ontology.OntologyShapeMapper; /** Persistence, SHACL exchange and authorization of ontology shapes in a working draft. */ @Execution(ExecutionMode.CONCURRENT) @@ -274,6 +277,112 @@ void aDryRunImportWritesNothingAndAnUnsatisfiableFileWritesNothing(final TestNam .size()); } + @Test + void aFileWithAShapeNameTheNameRulesRefuseWritesNothing(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + final String fine = + "ex:Fine a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] .\n"; + final String prefixes = + "@prefix sh: .\n@prefix ex: .\n"; + final String tooLong = + prefixes + + fine + + "ex:Long a sh:NodeShape ; sh:name \"" + + "n".repeat(300) + + "\" ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] .\n"; + final String invalid = + prefixes + + fine + + "ex:Bad a sh:NodeShape ; sh:name \"bad\\\"quote>\" ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] .\n"; + + for (final String file : List.of(tooLong, invalid)) { + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(file))); + assertEquals(400, refused.getStatusCode(), refused.getMessage()); + assertTrue(refused.getMessage().contains("cannot be imported"), refused.getMessage()); + } + assertEquals(0, shapeCount(ontology)); + } + + @Test + void aFileOverTheShapeCapWritesNothing(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final StringBuilder file = + new StringBuilder( + "@prefix sh: .\n@prefix ex: .\n"); + for (int shape = 0; shape <= 1000; shape++) { + file.append("ex:S").append(shape).append(" a sh:NodeShape ; sh:targetClass ex:Person .\n"); + } + + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(file.toString()))); + + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains("at most 1000 shapes"), refused.getMessage()); + assertEquals(0, shapeCount(ontology)); + } + + @Test + void writesMadeUnderTheDraftLockAreKeptOrDroppedTogether(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyRepository ontologies = + (OntologyRepository) Entity.getEntityRepository(Entity.ONTOLOGY); + final OntologyShapeRepository shapes = + (OntologyShapeRepository) Entity.getEntityRepository(Entity.ONTOLOGY_SHAPE); + final OntologyShape first = + new OntologyShapeMapper().createToEntity(shapeRequest(ontology, "First"), "admin"); + final OntologyShape second = + new OntologyShapeMapper().createToEntity(shapeRequest(ontology, "Second"), "admin"); + + shapes.prepareInternal(first, false); + shapes.prepareInternal(second, false); + + assertThrows( + IllegalStateException.class, + () -> + ontologies.writeWorkingDraft( + ontology.getId(), + () -> { + shapes.createOrUpdate(null, first, "admin"); + shapes.createOrUpdate(null, second, "admin"); + throw new IllegalStateException("the import fails after both writes"); + })); + assertEquals(0, shapeCount(ontology)); + + ontologies.writeWorkingDraft( + ontology.getId(), + () -> { + shapes.createOrUpdate(null, first, "admin"); + return shapes.createOrUpdate(null, second, "admin"); + }); + assertEquals(2, shapeCount(ontology)); + } + + private static int shapeCount(final Ontology ontology) { + return SdkClients.adminClient() + .ontologyShapes() + .list(new ListParams().addFilter("ontologyId", ontology.getId().toString())) + .getData() + .size(); + } + @Test void textThatIsNotTurtleIsRefused(final TestNamespace ns) { final Ontology ontology = createOntology(ns); @@ -333,6 +442,15 @@ void aConsumerCannotWriteOrReadTheWorkingDraftShapesAndAnAuthorCan(final TestNam assertEquals( 200, status(SdkClients.getAdminToken(), "GET", "/v1/ontologyShapes?ontologyId=" + id, null)); + + SdkClients.adminClient().ontologyShapes().delete(shape.getId().toString()); + final String restore = "{\"id\":\"" + shape.getId() + "\"}"; + assertEquals(403, status(consumer, "PUT", "/v1/ontologyShapes/restore", restore)); + assertEquals(200, status(author, "PUT", "/v1/ontologyShapes/restore", restore)); + assertEquals(403, status(consumer, "PUT", "/v1/ontologyShapes/restore", restore)); + SdkClients.adminClient().ontologyShapes().delete(shape.getId().toString()); + assertEquals( + 200, status(SdkClients.getAdminToken(), "PUT", "/v1/ontologyShapes/restore", restore)); } private static void assertRefused( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptRepository.java index 973a963fc1e0..c4be9c898e7b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptRepository.java @@ -185,6 +185,7 @@ private OntologyDefinition loadSource(final String type, final UUID id) { case Entity.ONTOLOGY_AXIOM -> daoCollection.ontologyAxiomDAO().findEntityById(id); case Entity.ONTOLOGY_PROPERTY -> daoCollection.ontologyPropertyDAO().findEntityById(id); case Entity.ONTOLOGY_CONCEPT -> daoCollection.ontologyConceptDAO().findEntityById(id); + case Entity.ONTOLOGY_SHAPE -> daoCollection.ontologyShapeDAO().findEntityById(id); default -> throw new BadRequestException("Unsupported ontology reference source"); }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java index 95386b63eaa6..038261b0148b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java @@ -105,6 +105,18 @@ List referencingForUpdate( @BindList("iriHashes") List iriHashes, @Bind("limit") int limit); + @SqlQuery( + "SELECT s.name FROM ontology_shape_entity s JOIN ontology_reference r " + + "ON r.sourceId = s.id AND r.ontologyId = s.ontologyId " + + "WHERE s.ontologyId = :ontologyId AND s.deleted = FALSE " + + "AND r.sourceType = 'ontologyShape' AND r.iriHash = :iriHash " + + "ORDER BY s.name, s.id LIMIT :limit ") + List shapesNaming( + @BindUUID("ontologyId") UUID ontologyId, + @Bind("iriHash") String iriHash, + @Bind("limit") int limit, + @Define("locking") String locking); + @SqlQuery( "SELECT a.json FROM ontology_axiom_entity a JOIN ontology_reference r " + "ON r.sourceId = a.id AND r.ontologyId = a.ontologyId " diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceIndex.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceIndex.java index 9cf20d91a9f3..277550179f5d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceIndex.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceIndex.java @@ -17,7 +17,11 @@ /** Maintains derived working references inside the definition writer's SQL transaction. */ final class OntologyReferenceIndex { private static final Set SOURCE_TYPES = - Set.of(Entity.ONTOLOGY_CONCEPT, Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_AXIOM); + Set.of( + Entity.ONTOLOGY_CONCEPT, + Entity.ONTOLOGY_PROPERTY, + Entity.ONTOLOGY_AXIOM, + Entity.ONTOLOGY_SHAPE); private final OntologyReferenceDAO dao; OntologyReferenceIndex(final CollectionDAO dao) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java index a1dcaaf1502b..3ec174fa109f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java @@ -283,12 +283,28 @@ private void requireNoRetainedReleases(final UUID id) { public R applyWorkingChanges( final UUID id, final long expectedRevision, final Supplier work) { + return underWorkingLock(id, expectedRevision, work); + } + + /** + * Runs {@code work} in one transaction under the ontology's lock, so every write it makes is + * kept or none is, and no other writer interleaves. Unlike {@link #applyWorkingChanges}, it takes + * the draft as it finds it. + */ + public R writeWorkingDraft(final UUID id, final Supplier work) { + return underWorkingLock(id, null, work); + } + + private R underWorkingLock( + final UUID id, final Long expectedRevision, final Supplier work) { return executeInTransaction( () -> { try (var ignored = FreshReadScope.enter()) { final OntologyStateDAO states = daoCollection.ontologyStateDAO(); states.initialize(id); - if (states.lock(id).getWorkingRevision() != expectedRevision) { + final OntologyState state = states.lock(id); + if (expectedRevision != null + && state.getWorkingRevision() != expectedRevision.longValue()) { throw new PreconditionFailedException( "Ontology changed since this draft was created"); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java index 5284ffd523a7..bec2853de5a7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java @@ -61,6 +61,7 @@ final class OntologyWorkingModel { "literal"); private static final int LIMIT = OntologyWriteClosureLimits.WORKING_MODEL_CLOSURE; private static final int SUBJECTS_PER_RULE_QUERY = 20; + private static final int SHAPE_NAMES_SHOWN = 3; // A current read: on MySQL REPEATABLE READ a plain SELECT could miss a rule a concurrent writer // just committed. ADR:2026-10-14-ontology-definitions-have-independent-entity-storage private static final String FOR_UPDATE = "FOR UPDATE"; @@ -92,6 +93,7 @@ void requireValid(final UUID ontologyId, final List changes) { } else if (change.after() instanceof OntologyEntityInterface declaration) { context.dependents(Set.of(declaration.getIri().toString())); } + requireNoShapeNamesWhatIsRemoved(ontologyId, change); } } requireDistinctRules(ontologyId, changedRules); @@ -189,6 +191,45 @@ private void requireNotADuplicate(final OntologyAxiom proposed) { requireNoDuplicate(rules, Set.of(proposed.getId())); } + /** + * A shape is saved without checking that what it names exists, so a shape is not validated with + * the definitions around it. Removing a class or property is where a shape would dangle, so that + * is refused here, naming the shapes. Declaring or editing a definition never looks at shapes. + * ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints + */ + private void requireNoShapeNamesWhatIsRemoved(final UUID ontologyId, final Change change) { + if (!(change.before() instanceof OntologyEntityInterface removed) + || change.before() instanceof Ontology + || Boolean.TRUE.equals(change.before().getDeleted()) + || !isRemoved(removed, change.after())) { + return; + } + final String iri = removed.getIri().toString(); + final List names = + dao.ontologyReferenceDAO() + .shapesNaming( + ontologyId, DigestUtils.sha256Hex(iri), SHAPE_NAMES_SHOWN + 1, FOR_UPDATE); + if (!names.isEmpty()) { + final String shown = + String.join("', '", names.subList(0, Math.min(names.size(), SHAPE_NAMES_SHOWN))); + throw new BadRequestException( + String.format( + "%s cannot be deleted while %s '%s'%s name it; delete or edit the shape first", + iri, + names.size() == 1 ? "the shape" : "the shapes", + shown, + names.size() > SHAPE_NAMES_SHOWN ? " and others" : "")); + } + } + + private static boolean isRemoved( + final OntologyEntityInterface before, final OntologyDefinition after) { + return after == null + || Boolean.TRUE.equals(after.getDeleted()) + || !(after instanceof OntologyEntityInterface kept) + || !kept.getIri().equals(before.getIri()); + } + /** Shapes state what instances must look like; they add nothing the class model depends on. */ private static boolean isShape(final Change change) { return change.before() instanceof OntologyShape || change.after() instanceof OntologyShape; @@ -262,6 +303,10 @@ void dependents(final Set iris) { if (affected.contains(source.getId())) { continue; } + if (Entity.ONTOLOGY_SHAPE.equals(source.getType())) { + // Shapes are checked when a definition is removed, not when it is declared or edited. + continue; + } final EntityDAO entities = switch (source.getType()) { case Entity.ONTOLOGY_CONCEPT -> dao.ontologyConceptDAO(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java index 5992e2fd4fd0..b5a79ae3c24e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java @@ -17,6 +17,7 @@ import org.openmetadata.schema.type.OntologyLiteral; import org.openmetadata.schema.type.OntologyReference; import org.openmetadata.schema.type.OntologyReferenceRole; +import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; @@ -29,9 +30,7 @@ public final class OntologyReferences { private OntologyReferences() {} public static List collect(final OntologyDefinition entity) { - if (Boolean.TRUE.equals(entity.getDeleted()) - || entity instanceof Ontology - || entity instanceof OntologyShape) { + if (Boolean.TRUE.equals(entity.getDeleted()) || entity instanceof Ontology) { return List.of(); } final OntologyReferences references = new OntologyReferences(); @@ -49,6 +48,10 @@ public static List collect(final OntologyDefinition entity) { references.axiom(axiom); yield Entity.ONTOLOGY_AXIOM; } + case OntologyShape shape -> { + references.shape(shape); + yield Entity.ONTOLOGY_SHAPE; + } default -> throw new BadRequestException("Unsupported ontology reference source"); }; return references.targets.stream() @@ -83,6 +86,20 @@ private void property(final OntologyProperty property) { listOrEmpty(property.getEnumValues()).forEach(this::literal); } + /** + * A shape names the class it targets, the classes its constraints require and the properties + * they constrain, so deleting one of them is refused while the shape is live. + */ + private void shape(final OntologyShape shape) { + add(OntologyReferenceRole.CLASS_EXPRESSION, shape.getTargetConcept()); + for (final OntologyShapeConstraint constraint : listOrEmpty(shape.getConstraints())) { + if (constraint != null) { + add(OntologyReferenceRole.CLASS_EXPRESSION, constraint.getClassIri()); + add(OntologyReferenceRole.PROPERTY, constraint.getPath()); + } + } + } + private void axiom(final OntologyAxiom axiom) { add(OntologyReferenceRole.AXIOM_SUBJECT, axiom.getSubjectIri()); add(OntologyReferenceRole.SUPER_CLASS, OntologyClassHierarchy.namedParents(axiom)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java index abae12031e81..dc1e62d95af3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java @@ -16,6 +16,7 @@ import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -28,6 +29,7 @@ import org.openmetadata.schema.type.OntologyProfileViolationSeverity; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.exception.BadRequestException; /** @@ -36,6 +38,9 @@ * classes and properties it names exist is a question for a release. */ public final class OntologyShapeRules { + /** Constraints one shape holds; a class with more is described by several shapes. */ + public static final int MAX_CONSTRAINTS = 200; + private static final Pattern CONSTRAINT_ID = Pattern.compile("^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"); private OntologyShapeRules() {} @@ -45,6 +50,14 @@ public static List validate(final OntologyShape shape) requireAbsolute(findings, shape.getTargetConcept(), "/targetConcept"); final Set ids = new HashSet<>(); final List constraints = listOrEmpty(shape.getConstraints()); + if (constraints.size() > MAX_CONSTRAINTS) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + "/constraints", + "A shape holds at most " + MAX_CONSTRAINTS + " constraints: " + constraints.size()); + return findings; + } for (int index = 0; index < constraints.size(); index++) { final OntologyShapeConstraint constraint = constraints.get(index); final String path = "/constraints/" + index; @@ -57,12 +70,25 @@ public static List validate(final OntologyShape shape) return findings; } + /** + * The checks a save runs. The constraint count is checked first, so the size of a shape that is + * rejected for its count is never measured. + */ public static void requireValid(final OntologyShape shape) { final List findings = validate(shape); if (!findings.isEmpty()) { final OntologyProfileViolation first = findings.getFirst(); throw new BadRequestException(first.getPath() + ": " + first.getMessage()); } + requireWithinMemberSize(shape); + } + + /** The member limit every other definition meets when it is saved, so capture never meets more. */ + private static void requireWithinMemberSize(final OntologyShape shape) { + final int bytes = JsonUtils.pojoToJson(shape).getBytes(StandardCharsets.UTF_8).length; + if (bytes > OntologyReleaseManifest.MAX_MEMBER_BYTES) { + throw new BadRequestException("An ontology definition exceeds the 1 MiB member limit"); + } } private static void validate( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java index c8f75c49a41f..d92c014f7a93 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java @@ -271,6 +271,12 @@ public static OntologyConceptDeleteImpact deletionImpact( blockers.add(other.getEntityReference()); } } + case OntologyShape shape -> { + if (OntologyReferences.collect(shape).stream() + .anyMatch(reference -> reference.getIri().toString().equals(iri))) { + blockers.add(shape.getEntityReference()); + } + } default -> {} } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java index 412b37c16b0c..f9e6db342b46 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java @@ -164,6 +164,7 @@ private List workingDefinitions( case CONCEPT -> dao.ontologyConceptDAO().findEntitiesByIds(ids, Include.NON_DELETED); case PROPERTY -> dao.ontologyPropertyDAO().findEntitiesByIds(ids, Include.NON_DELETED); case AXIOM -> dao.ontologyAxiomDAO().findEntitiesByIds(ids, Include.NON_DELETED); + case SHAPE -> dao.ontologyShapeDAO().findEntitiesByIds(ids, Include.NON_DELETED); default -> throw new IllegalArgumentException("Unsupported working member kind " + kind); }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java index 8be381f14997..540b891e2dcb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java @@ -13,7 +13,6 @@ package org.openmetadata.service.rdf; -import java.io.StringReader; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; @@ -27,15 +26,10 @@ import java.util.regex.Pattern; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; -import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; -import org.apache.jena.rdf.model.RDFList; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.Statement; -import org.apache.jena.riot.Lang; -import org.apache.jena.riot.RDFDataMgr; -import org.apache.jena.riot.RiotException; import org.apache.jena.vocabulary.RDF; import org.apache.jena.vocabulary.RDFS; import org.apache.jena.vocabulary.XSD; @@ -56,7 +50,13 @@ * reported by name and left out; the rest of the file is still read. */ public final class OntologyShaclReader { - private static final String BASE = "urn:openmetadata:import:"; + /** Shapes one file may hold, as many as the native import allows changed definitions. */ + public static final int MAX_SHAPES = 1_000; + + /** Cells of one {@code sh:in} list that are read before the list counts as malformed. */ + static final int MAX_LIST_CELLS = 1_000; + + private static final int MAX_NAME_LENGTH = 256; private static final Pattern CONSTRAINT_ID = Pattern.compile("^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"); private static final Set NODE_CONSUMED = Set.of( @@ -93,13 +93,14 @@ public record Parsed( private OntologyShaclReader() {} + /** + * Parses with the bounds of the native import: at most 10 MiB, 100,000 statements and 30 seconds, + * and no relative identifiers or named graphs. + */ public static Parsed read(final String turtle) { - final Model model = ModelFactory.createDefaultModel(); + final Model model = new SafeRdfModelParser().parse(turtle, RdfSerializationFormat.TURTLE); try { - RDFDataMgr.read(model, new StringReader(turtle), BASE, Lang.TURTLE); return new OntologyShaclReader().parse(model); - } catch (RiotException invalid) { - throw new BadRequestException("The file is not valid Turtle: " + invalid.getMessage()); } finally { model.close(); } @@ -114,6 +115,9 @@ private Parsed parse(final Model model) { .mapWith(RDFNode::asResource) .toList()); final List nodes = nodeShapes(model, attached); + if (nodes.size() > MAX_SHAPES) { + throw new BadRequestException("A file holds at most " + MAX_SHAPES + " shapes"); + } reportDetachedPropertyShapes(model, attached, nodes); final Set taken = new HashSet<>(); final List shapes = new ArrayList<>(); @@ -197,22 +201,31 @@ private static String label(final Resource node) { return node.isURIResource() ? node.getURI() : "_:" + node.getId(); } + /** + * A name is kept as the file states it, so the caller can refuse one the name rules do not allow. + * Only the suffix that tells two equal names apart is fitted to the length limit. + */ private String uniqueName(final Resource node, final Resource target, final Set taken) { - final Statement named = node.getProperty(OntologyShaclVocabulary.NAME); + final RDFNode named = single(node, OntologyShaclVocabulary.NAME, label(node), null); final String base = - named != null && named.getObject().isLiteral() - ? named.getString() + named != null && named.isLiteral() + ? named.asLiteral().getString() : node.isURIResource() ? localName(node.getURI()) : localName(target.getURI()) + "Shape"; final String clean = base.isBlank() ? "Shape" : base.strip().replace("::", ":_"); - String candidate = clean.length() > 256 ? clean.substring(0, 256) : clean; + String candidate = clean; for (int suffix = 2; !taken.add(candidate); suffix++) { - candidate = clean + suffix; + final String tail = Integer.toString(suffix); + candidate = truncate(clean, MAX_NAME_LENGTH - tail.length()) + tail; } return candidate; } + private static String truncate(final String value, final int length) { + return value.length() > length ? value.substring(0, length) : value; + } + private static String localName(final String iri) { final int cut = Math.max(Math.max(iri.lastIndexOf('#'), iri.lastIndexOf('/')), iri.lastIndexOf(':')); @@ -232,11 +245,10 @@ private static String text(final Resource node, final Property property, final S } private OntologyShapeSeverity severity(final Resource node, final String name) { - final Statement statement = node.getProperty(OntologyShaclVocabulary.SEVERITY); - if (statement == null) { + final RDFNode value = single(node, OntologyShaclVocabulary.SEVERITY, name, null); + if (value == null) { return OntologyShapeSeverity.VIOLATION; } - final RDFNode value = statement.getObject(); if (OntologyShaclVocabulary.VIOLATION.equals(value)) { return OntologyShapeSeverity.VIOLATION; } @@ -340,11 +352,11 @@ private boolean count( final String shapeName, final URI path, final java.util.function.Consumer setter) { - final Statement statement = node.getProperty(predicate); - if (statement == null) { + final RDFNode object = single(node, predicate, shapeName, path); + if (object == null) { return false; } - final Integer value = nonNegative(statement.getObject()); + final Integer value = nonNegative(object); if (value == null) { report( "sh:" + predicate.getLocalName(), @@ -375,11 +387,11 @@ private boolean iri( final String shapeName, final URI path, final java.util.function.Consumer setter) { - final Statement statement = node.getProperty(predicate); - if (statement == null) { + final RDFNode object = single(node, predicate, shapeName, path); + if (object == null) { return false; } - if (!statement.getObject().isURIResource()) { + if (!object.isURIResource()) { report( "sh:" + predicate.getLocalName(), shapeName, @@ -387,7 +399,7 @@ private boolean iri( "The value is not an IRI; the constraint was left out"); return false; } - setter.accept(URI.create(statement.getResource().getURI())); + setter.accept(URI.create(object.asResource().getURI())); return true; } @@ -397,19 +409,21 @@ private boolean bound( final String shapeName, final URI path, final java.util.function.Consumer setter) { - final Statement statement = node.getProperty(predicate); - if (statement == null) { + final RDFNode object = single(node, predicate, shapeName, path); + if (object == null) { return false; } - if (!statement.getObject().isLiteral()) { + if (!object.isLiteral() || !object.asLiteral().getLanguage().isEmpty()) { report( "sh:" + predicate.getLocalName(), shapeName, path, - "The value is not a literal; the constraint was left out"); + object.isLiteral() + ? "A language-tagged literal is not held; the constraint was left out" + : "The value is not a literal; the constraint was left out"); return false; } - setter.accept(literal(statement.getLiteral())); + setter.accept(literal(object.asLiteral())); return true; } @@ -418,38 +432,91 @@ private boolean values( final String shapeName, final URI path, final OntologyShapeConstraint constraint) { - final Statement statement = node.getProperty(OntologyShaclVocabulary.IN); - if (statement == null) { + final RDFNode head = single(node, OntologyShaclVocabulary.IN, shapeName, path); + if (head == null) { return false; } - final List values = new ArrayList<>(); - final boolean list = - statement.getObject().isResource() && statement.getObject().canAs(RDFList.class); - if (list) { - for (final RDFNode element : statement.getObject().as(RDFList.class).asJavaList()) { - if (element.isURIResource()) { - values.add(new OntologyShapeValue().withIri(URI.create(element.asResource().getURI()))); - } else if (element.isLiteral()) { - values.add(new OntologyShapeValue().withLiteral(literal(element.asLiteral()))); - } else { - list(shapeName, path); - return false; - } - } - } else { - list(shapeName, path); + final List elements = items(head); + final List values = elements == null ? null : values(elements); + if (values == null) { + report( + "sh:in", + shapeName, + path, + elements == null + ? "The value is not a well-formed list of at most " + + MAX_LIST_CELLS + + " IRIs and literals; the constraint was left out" + : "A list value that is not an IRI or a plain or typed literal is not held; " + + "the constraint was left out"); return false; } constraint.setIn(values); return true; } - private void list(final String shapeName, final URI path) { - report( - "sh:in", - shapeName, - path, - "The value is not a list of IRIs and literals; the constraint was left out"); + /** Null when a value is a blank node or a language-tagged literal. */ + private static List values(final List elements) { + final List values = new ArrayList<>(); + for (final RDFNode element : elements) { + if (element.isURIResource()) { + values.add(new OntologyShapeValue().withIri(URI.create(element.asResource().getURI()))); + } else if (element.isLiteral() && element.asLiteral().getLanguage().isEmpty()) { + values.add(new OntologyShapeValue().withLiteral(literal(element.asLiteral()))); + } else { + return null; + } + } + return values; + } + + /** + * Walks {@code rdf:first} and {@code rdf:rest} itself, because a list that loops back on itself + * never ends. Null when the list repeats a cell, lacks or doubles a link, ends in anything but + * {@code rdf:nil}, or has more than {@link #MAX_LIST_CELLS} cells. + */ + private static List items(final RDFNode head) { + final List items = new ArrayList<>(); + final Set visited = new HashSet<>(); + RDFNode cell = head; + while (!RDF.nil.equals(cell)) { + if (!cell.isResource() || !visited.add(cell.asResource()) || items.size() >= MAX_LIST_CELLS) { + return null; + } + final List first = objects(cell.asResource(), RDF.first); + final List rest = objects(cell.asResource(), RDF.rest); + if (first.size() != 1 || rest.size() != 1) { + return null; + } + items.add(first.getFirst()); + cell = rest.getFirst(); + } + return items; + } + + private static List objects(final Resource node, final Property predicate) { + return node.listProperties(predicate).mapWith(Statement::getObject).toList(); + } + + /** + * The value of a predicate. A second value is reported and the first in lexical order is kept, so + * the same file always reads the same. + */ + private RDFNode single( + final Resource node, final Property predicate, final String shapeName, final URI path) { + final List values = new ArrayList<>(objects(node, predicate)); + if (values.isEmpty()) { + return null; + } + if (values.size() > 1) { + values.sort(Comparator.comparing(RDFNode::toString)); + report( + "sh:" + predicate.getLocalName(), + shapeName, + path, + "Only one value is held; the first in lexical order was used"); + } + return values.getFirst(); } private boolean pattern( @@ -457,25 +524,22 @@ private boolean pattern( final String shapeName, final URI path, final OntologyShapeConstraint constraint) { - final Statement statement = node.getProperty(OntologyShaclVocabulary.PATTERN); - if (statement == null) { + final RDFNode value = single(node, OntologyShaclVocabulary.PATTERN, shapeName, path); + if (value == null) { return false; } - if (!statement.getObject().isLiteral()) { + if (!value.isLiteral()) { report( "sh:pattern", shapeName, path, "The value is not a string; the constraint was left out"); return false; } - constraint.setPattern(statement.getString()); + constraint.setPattern(value.asLiteral().getString()); return true; } private static OntologyLiteral literal(final Literal literal) { final String datatype = literal.getDatatypeURI(); - final boolean plain = - datatype == null - || XSD.xstring.getURI().equals(datatype) - || RDF.langString.getURI().equals(datatype); + final boolean plain = datatype == null || XSD.xstring.getURI().equals(datatype); return new OntologyLiteral() .withValue(literal.getLexicalForm()) .withDatatypeIri(plain ? null : URI.create(datatype)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java index ffc7402f0b0e..f237981a505a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java @@ -35,7 +35,6 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.ws.rs.core.UriInfo; -import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.openmetadata.schema.api.data.CreateOntologyShape; @@ -52,7 +51,9 @@ import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.jdbi3.ListFilter; +import org.openmetadata.service.jdbi3.OntologyRepository; import org.openmetadata.service.jdbi3.OntologyShapeRepository; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.ontology.OntologyShapeRules; @@ -62,6 +63,7 @@ import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.policyevaluator.CreateResourceContext; import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.util.ValidatorUtil; @Path("/v1/ontologyShapes") @Tag(name = "Ontology Shapes", description = "SHACL node shapes authored in an ontology.") @@ -153,7 +155,7 @@ public Response create( operationId = "importOntologyShapes", summary = "Import SHACL node shapes into an ontology's working draft", description = - "Reads a Turtle document and creates or updates one shape per sh:NodeShape that has a single sh:targetClass, keyed by name, with the supported constraints of its sh:property nodes. Every other SHACL construct is left out and named in the result; that is a report, not an error. A shape that violates the shape rules fails the whole request before anything is written. With dryRun nothing is written.") + "Reads a Turtle document and creates or updates one shape per sh:NodeShape that has a single sh:targetClass, keyed by name, with the supported constraints of its sh:property nodes. Every other SHACL construct is left out and named in the result; that is a report, not an error. A file holds at most 1,000 shapes, 100,000 statements and 10 MiB, and parses within 30 seconds. A shape whose name or content violates the entity name or shape rules fails the whole request before anything is written, and the writes run in one transaction, so a failing request leaves the draft as it was. With dryRun nothing is written.") public OntologyShapeImportResult importShapes( @Context final UriInfo uriInfo, @Context final SecurityContext securityContext, @@ -172,19 +174,35 @@ public OntologyShapeImportResult importShapes( .toList(); shapes.forEach(OntologyShapeRules::requireValid); final boolean dryRun = Boolean.TRUE.equals(request.getDryRun()); - final List written = new ArrayList<>(); - for (final OntologyShape shape : shapes) { - written.add(dryRun ? planned(shape) : write(uriInfo, securityContext, shape)); - } return new OntologyShapeImportResult() .withDryRun(dryRun) - .withShapes(written) + .withShapes(dryRun ? planned(shapes) : write(uriInfo, securityContext, ontology, shapes)) .withUnsupported(parsed.unsupported()); } + /** + * Every write runs in one transaction under the ontology's lock: a shape that fails leaves the + * draft as it was. ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints + */ + private List write( + final UriInfo uriInfo, + final SecurityContext securityContext, + final EntityReference ontology, + final List shapes) { + final OntologyRepository ontologies = + (OntologyRepository) Entity.getEntityRepository(Entity.ONTOLOGY); + return ontologies.writeWorkingDraft( + ontology.getId(), + () -> shapes.stream().map(shape -> write(uriInfo, securityContext, shape)).toList()); + } + + private List planned(final List shapes) { + return shapes.stream().map(this::planned).toList(); + } + private OntologyShape toEntity( final String ontology, final OntologyShaclReader.ParsedShape shape, final String user) { - return mapper.createToEntity( + final CreateOntologyShape request = new CreateOntologyShape() .withName(shape.name()) .withDisplayName(shape.displayName()) @@ -192,8 +210,17 @@ private OntologyShape toEntity( .withOntology(ontology) .withTargetConcept(shape.targetConcept()) .withSeverity(shape.severity()) - .withConstraints(shape.constraints()), - user); + .withConstraints(shape.constraints()); + final String invalid = ValidatorUtil.validate(request); + if (invalid != null) { + throw new BadRequestException( + "The shape '" + abbreviated(shape.name()) + "' cannot be imported: " + invalid); + } + return mapper.createToEntity(request, user); + } + + private static String abbreviated(final String name) { + return name.length() > 64 ? name.substring(0, 64) + "..." : name; } private OntologyShapeImported planned(final OntologyShape shape) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/migration/MigrationArchitectureTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/migration/MigrationArchitectureTest.java index ae2312b89b5d..9c3ec4986a49 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/migration/MigrationArchitectureTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/migration/MigrationArchitectureTest.java @@ -97,7 +97,7 @@ class MigrationArchitectureTest { JsonUtils.class, Relationship.class); - // No folder after 2.1.0 exists yet, so the rules may match no class. + // The rules may match no class, as on a branch whose newest folder is a shipped one. @ArchTest static final ArchRule versionedMigrationsUseOnlyAllowedClasses = classes() diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReferencesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReferencesTest.java index 6e22a85ef379..1a29c4935778 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReferencesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReferencesTest.java @@ -15,11 +15,13 @@ import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyExpression; import org.openmetadata.schema.type.OntologyExpressionKind; import org.openmetadata.schema.type.OntologyLiteral; import org.openmetadata.schema.type.OntologyReference; +import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.exception.BadRequestException; class OntologyReferencesTest { @@ -130,6 +132,38 @@ void nestedExpressionsAndAssertionsIncludeIndividualsPropertiesAndDatatypes() { keys(OntologyReferences.collect(axiom))); } + @Test + void aShapeIndexesTheClassesAndPropertiesItNamesAndNothingElse() { + OntologyShape shape = + new OntologyShape() + .withId(UUID.randomUUID()) + .withOntology(OWNER) + .withTargetConcept(iri("Person")) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("home") + .withPath(iri("livesAt")) + .withClassIri(iri("Address")) + .withDatatypeIri(iri("text")), + new OntologyShapeConstraint() + .withId("name") + .withPath(iri("name")) + .withMinCount(1))); + + List references = OntologyReferences.collect(shape); + + assertEquals( + Set.of( + "CLASS_EXPRESSION:Person", + "CLASS_EXPRESSION:Address", + "PROPERTY:livesAt", + "PROPERTY:name"), + keys(references)); + assertEquals("ontologyShape", references.getFirst().getSource().getType()); + assertEquals(List.of(), OntologyReferences.collect(shape.withDeleted(true))); + } + @Test void removedDefinitionsAndNamespacesHaveNoOutgoingReferences() { assertTrue(OntologyReferences.collect(new Ontology().withId(OWNER.getId())).isEmpty()); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java index 9ff0f4fc2b30..8b331bfc7349 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java @@ -67,6 +67,40 @@ void anEmptyInListCanNeverBeSatisfied() { findings); } + @Test + void aShapeWithMoreConstraintsThanTheCapIsRefusedAtSave() { + final OntologyShapeConstraint[] constraints = + java.util.stream.IntStream.rangeClosed(0, OntologyShapeRules.MAX_CONSTRAINTS) + .mapToObj(index -> constraint("c" + index).withMinCount(1)) + .toArray(OntologyShapeConstraint[]::new); + + final BadRequestException refused = + assertThrows( + BadRequestException.class, () -> OntologyShapeRules.requireValid(shape(constraints))); + + assertEquals("/constraints: A shape holds at most 200 constraints: 201", refused.getMessage()); + assertEquals( + List.of(), + validate( + shape( + java.util.stream.IntStream.range(0, OntologyShapeRules.MAX_CONSTRAINTS) + .mapToObj(index -> constraint("c" + index).withMinCount(1)) + .toArray(OntologyShapeConstraint[]::new)))); + } + + @Test + void aShapeOverTheMemberSizeLimitIsRefusedAtSave() { + final OntologyShape shape = shape(constraint("c1").withMinCount(1)); + shape.setDescription("x".repeat(OntologyReleaseManifest.MAX_MEMBER_BYTES)); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> OntologyShapeRules.requireValid(shape)); + + assertEquals("An ontology definition exceeds the 1 MiB member limit", refused.getMessage()); + shape.setDescription("x".repeat(1000)); + OntologyShapeRules.requireValid(shape); + } + @Test void aRepeatedConstraintIdIsRefused() { final var findings = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java index ef86c4f6a1c2..ae541b244376 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java @@ -134,11 +134,23 @@ void aRepeatedConstraintIdFails() { } @Test - void aShapeDoesNotChangeTheVerdictOnTheDefinitionsAroundIt() { + void aValidShapeOverValidDefinitionsLeavesTheReportValid() { final var without = validate(null); + final var with = + validate( + shape( + PERSON, + new OntologyShapeConstraint().withId("has-name").withPath(NAME).withMinCount(1), + new OntologyShapeConstraint() + .withId("lives-at") + .withPath(LIVES_AT) + .withClassIri(ADDRESS))); assertTrue(without.getValid()); + assertTrue(with.getValid()); assertEquals(0, without.getViolationCount()); + assertEquals(0, with.getViolationCount()); + assertEquals(List.of(), with.getViolations()); } private static List violations(final OntologyShape shape) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java index 10f151b7129f..97095d2fbc53 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java @@ -26,6 +26,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.type.OntologyConceptType; @@ -37,6 +38,7 @@ import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.schema.type.OntologyRestrictionKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.type.RelationshipCharacteristic; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.exception.OntologyValidationException; @@ -587,6 +589,37 @@ void deletionImpactListsChildrenRelationshipsRulesAndBlockers() { assertEquals(List.of("eats"), names(impact.getBlockers())); } + @Test + void aLiveShapeThatNamesTheConceptBlocksItsDeletion() { + final var person = named(concept("Person"), "Person"); + final var address = named(concept("Address"), "Address"); + final var names = named(shape(person.getIri(), address.getIri()), "names-person"); + final var elsewhere = + named(shape(address.getIri(), URI.create("urn:other")), "names-address-only"); + final var gone = named(shape(person.getIri(), address.getIri()), "deleted").withDeleted(true); + + final var impact = + OntologyStructureValidator.deletionImpact( + person, List.of(person, address, names, elsewhere, gone)); + + assertEquals(List.of("names-person"), names(impact.getBlockers())); + assertEquals(List.of(), impact.getRules()); + assertEquals(List.of(), impact.getRelationships()); + } + + private static OntologyShape shape(URI target, URI required) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withOntology(new EntityReference().withId(UUID.randomUUID()).withType("ontology")) + .withTargetConcept(target) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("c1") + .withPath(URI.create("urn:p")) + .withClassIri(required))); + } + @Test void deletionImpactIgnoresDefinitionsThatDoNotNameTheConcept() { final var animal = named(concept("Animal"), "Animal"); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclReaderTest.java new file mode 100644 index 000000000000..d569c0d4d835 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclReaderTest.java @@ -0,0 +1,211 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.rdf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.net.URI; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.openmetadata.schema.api.data.OntologyShapeUnsupportedConstruct; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.exception.BadRequestException; + +/** What the SHACL reader keeps, reports and refuses; every report is named in the result. */ +class OntologyShaclReaderTest { + private static final String HEAD = + """ + @prefix sh: . + @prefix ex: . + @prefix xsd: . + @prefix rdf: . + """; + + @Test + @Timeout(value = 20, unit = TimeUnit.SECONDS) + void aListThatLoopsBackOnItselfIsReportedAndItsConstraintLeftOut() { + final String file = + HEAD + + """ + ex:S a sh:NodeShape ; sh:targetClass ex:P ; sh:property ex:Sp . + ex:Sp sh:path ex:name ; sh:in _:l1 . + _:l1 rdf:first "a" ; rdf:rest _:l1 . + """; + + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(file); + + assertEquals( + List.of( + "sh:in: The value is not a well-formed list of at most 1000 IRIs and literals; the" + + " constraint was left out", + "sh:property: A property shape with no supported constraint was left out"), + reports(parsed)); + assertEquals(List.of(), parsed.shapes().getFirst().constraints()); + } + + @Test + @Timeout(value = 20, unit = TimeUnit.SECONDS) + void aListThatEndsEarlyOrRunsPastTheCellCapIsReported() { + final StringBuilder longList = new StringBuilder("( "); + for (int cell = 0; cell <= OntologyShaclReader.MAX_LIST_CELLS; cell++) { + longList.append("\"v").append(cell).append("\" "); + } + final String unterminated = + HEAD + + """ + ex:S a sh:NodeShape ; sh:targetClass ex:P ; + sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:in _:l1 ] . + _:l1 rdf:first "a" . + """; + final String tooLong = + HEAD + + "ex:S a sh:NodeShape ; sh:targetClass ex:P ; sh:property [ sh:path ex:name ;" + + " sh:minCount 1 ; sh:in " + + longList + + ") ] .\n"; + + final OntologyShaclReader.Parsed ended = OntologyShaclReader.read(unterminated); + final OntologyShaclReader.Parsed overCap = OntologyShaclReader.read(tooLong); + + for (final OntologyShaclReader.Parsed parsed : List.of(ended, overCap)) { + assertEquals( + List.of( + "sh:in: The value is not a well-formed list of at most 1000 IRIs and literals; the" + + " constraint was left out"), + reports(parsed)); + assertEquals( + Integer.valueOf(1), parsed.shapes().getFirst().constraints().getFirst().getMinCount()); + assertNull(parsed.shapes().getFirst().constraints().getFirst().getIn()); + } + } + + @Test + void aPredicateWithTwoValuesIsReportedAndTheFirstInLexicalOrderIsKept() { + final String file = + HEAD + + """ + ex:S a sh:NodeShape ; sh:name "Zed" , "Alpha" ; sh:targetClass ex:P ; + sh:property [ sh:path ex:knows ; sh:class ex:B , ex:A ; sh:pattern "b$" , "^a" ; + sh:datatype xsd:string , xsd:integer ; sh:minCount 2 , 1 ] . + """; + + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(file); + + final String once = "Only one value is held; the first in lexical order was used"; + assertEquals( + List.of( + "sh:name: " + once, + "sh:minCount: " + once, + "sh:class: " + once, + "sh:datatype: " + once, + "sh:pattern: " + once), + reports(parsed)); + assertEquals("Alpha", parsed.shapes().getFirst().name()); + final OntologyShapeConstraint kept = parsed.shapes().getFirst().constraints().getFirst(); + assertEquals(Integer.valueOf(1), kept.getMinCount()); + assertEquals(URI.create("https://example.org/onto/A"), kept.getClassIri()); + assertEquals(URI.create("http://www.w3.org/2001/XMLSchema#integer"), kept.getDatatypeIri()); + assertEquals("^a", kept.getPattern()); + } + + @Test + void aLanguageTaggedLiteralIsReportedAndItsConstraintLeftOut() { + final String file = + HEAD + + """ + ex:S a sh:NodeShape ; sh:targetClass ex:P ; + sh:property [ sh:path ex:label ; sh:minCount 1 ; sh:in ( "chat"@fr "cat"@en ) ] , + [ sh:path ex:title ; sh:minCount 1 ; sh:minInclusive "a"@en ; sh:maxInclusive "z" ] . + """; + + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(file); + + assertEquals( + List.of( + "sh:in: A list value that is not an IRI or a plain or typed literal is not held; the" + + " constraint was left out", + "sh:minInclusive: A language-tagged literal is not held; the constraint was left out"), + reports(parsed).stream().sorted().toList()); + final List constraints = parsed.shapes().getFirst().constraints(); + assertEquals(2, constraints.size()); + assertNull(constraints.get(0).getIn()); + assertNull(constraints.get(1).getMinInclusive()); + assertEquals("z", constraints.get(1).getMaxInclusive().getValue()); + } + + @Test + void aSuffixThatTellsTwoEqualNamesApartStaysWithinTheNameLength() { + final String name = "n".repeat(256); + final String file = + HEAD + + "ex:S1 a sh:NodeShape ; sh:name \"" + + name + + "\" ; sh:targetClass ex:P ; sh:property [ sh:path ex:a ; sh:minCount 1 ] .\n" + + "ex:S2 a sh:NodeShape ; sh:name \"" + + name + + "\" ; sh:targetClass ex:P ; sh:property [ sh:path ex:a ; sh:minCount 1 ] .\n"; + + final List names = + OntologyShaclReader.read(file).shapes().stream() + .map(OntologyShaclReader.ParsedShape::name) + .toList(); + + assertEquals(List.of("n".repeat(255) + "2", "n".repeat(256)), names); + } + + @Test + void aNameLongerThanTheLimitIsKeptSoTheCallerCanRefuseIt() { + final String file = + HEAD + + "ex:S1 a sh:NodeShape ; sh:name \"" + + "n".repeat(300) + + "\" ; sh:targetClass ex:P ; sh:property [ sh:path ex:a ; sh:minCount 1 ] .\n"; + + assertEquals(300, OntologyShaclReader.read(file).shapes().getFirst().name().length()); + } + + @Test + void aFileOverTheShapeCapIsRefused() { + final StringBuilder file = new StringBuilder(HEAD); + for (int shape = 0; shape <= OntologyShaclReader.MAX_SHAPES; shape++) { + file.append("ex:S").append(shape).append(" a sh:NodeShape ; sh:targetClass ex:P .\n"); + } + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> OntologyShaclReader.read(file.toString())); + + assertEquals("A file holds at most 1000 shapes", refused.getMessage()); + } + + @Test + void aRelativeIdentifierIsRefused() { + assertThrows( + BadRequestException.class, + () -> + OntologyShaclReader.read( + "@prefix sh: .\n a sh:NodeShape .\n")); + } + + private static List reports(final OntologyShaclReader.Parsed parsed) { + return parsed.unsupported().stream() + .map( + (OntologyShapeUnsupportedConstruct item) -> + item.getConstruct() + ": " + item.getMessage()) + .toList(); + } +} From 000f601be80b807cc3e0c3830d7bcf9738c68465 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 21:49:21 -0800 Subject: [PATCH 010/203] ontology tests: create the shape table in the storage test database --- .../openmetadata/service/jdbi3/OntologyTestDatabase.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyTestDatabase.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyTestDatabase.java index c208ffc9fa00..bc6b43656240 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyTestDatabase.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyTestDatabase.java @@ -172,6 +172,15 @@ static void migrate(Handle handle, ConnectionType dialect) { .dropWhile(statement -> !statement.contains("CREATE TABLE IF NOT EXISTS ontology_entity (")) .filter(statement -> statement.toLowerCase(Locale.ROOT).contains("ontology")) .forEach(handle::execute); + // The shape table is created by the next release's migration, which holds only ontology DDL. + MigrationFile.parseSQLFile( + repositoryRoot() + .resolve("bootstrap/sql/migrations/native/2.2.0") + .resolve(dialect == ConnectionType.MYSQL ? "mysql" : "postgres") + .resolve("schemaChanges.sql") + .toFile(), + dialect) + .forEach(handle::execute); } static Path repositoryRoot() { From 0cd4270d9228afab4688e943064eaa4b29616af2 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 21:49:32 -0800 Subject: [PATCH 011/203] Ontology: read the reference table first in the MySQL sibling read FORCE INDEX alone left the join order free. Once the target index was cached, MySQL started from the property table and locked every property row of every ontology. STRAIGHT_JOIN with the reference table first keeps the locking range inside one ontology's index entries. The Postgres statement is unchanged. --- .../service/jdbi3/OntologyReferenceDAO.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java index f442795b986b..8907779fa645 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java @@ -105,8 +105,11 @@ List referencingForUpdate( @BindList("iriHashes") List iriHashes, @Bind("limit") int limit); - String SIBLINGS_SELECT = - "SELECT p.json FROM ontology_property_entity p JOIN ontology_reference r "; + String SIBLINGS_SELECT = "SELECT p.json "; + String SIBLINGS_FROM_PG = "FROM ontology_property_entity p JOIN ontology_reference r "; + String SIBLINGS_FROM_MYSQL = + "FROM ontology_reference r FORCE INDEX (ontology_reference_target_index) " + + "STRAIGHT_JOIN ontology_property_entity p "; String SIBLINGS_JOIN_ON = "ON r.sourceId = p.id AND r.ontologyId = p.ontologyId " + "WHERE p.ontologyId = :ontologyId AND p.deleted = FALSE AND "; @@ -121,12 +124,16 @@ List referencingForUpdate( * A property with several matching domain classes comes back once per match, and the caller drops * the repeats, because Postgres rejects {@code FOR UPDATE} with {@code DISTINCT}. */ - // The index keeps the locking read inside the ontology's key range. Without it MySQL scans every - // ontology's references for a heavily referenced class and locks them all. + // Two pins keep the locking read inside the ontology's rows. The index keeps the range on the + // reference target index, whose first column is the ontology. STRAIGHT_JOIN reads the reference + // table first, so that range decides which property rows are read. Without the order MySQL may + // start from the property table once the index is cached, and it then locks every property row + // of every ontology. Without the index it scans every ontology's references for a heavily + // referenced class and locks them all. @ConnectionAwareSqlQuery( value = SIBLINGS_SELECT - + "FORCE INDEX (ontology_reference_target_index) " + + SIBLINGS_FROM_MYSQL + SIBLINGS_JOIN_ON + "JSON_UNQUOTE(JSON_EXTRACT(p.json, '$.isDisplayName')) = 'true'" + SIBLINGS_WHERE, @@ -134,6 +141,7 @@ List referencingForUpdate( @ConnectionAwareSqlQuery( value = SIBLINGS_SELECT + + SIBLINGS_FROM_PG + SIBLINGS_JOIN_ON + "p.json ->> 'isDisplayName' = 'true'" + SIBLINGS_WHERE, From 3eaa53aea21f487f7ccefd69a74d61fb7981255a Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 22:19:20 -0800 Subject: [PATCH 012/203] Add role, subject key, row filter and join to the binding schemas A table binding says which table holds data about a class. It did not say how one row becomes one record of the class. The schemas now let a table binding carry a role, a subject key and a row filter, let a column bound to an OBJECT property carry a join, and let an ontology name one database as its mapping source. The mapping health schema describes the read that lists what an editor still has to fix. The native 2.2.0 migration adds three nullable columns to ontology_concept_binding and backfills nothing, so rows written before it read back with no role, no key and no filter. The statements open the 2.2.0 folder, because 2.1.0 has shipped. Each one adds the columns only where they are missing, so the runner can apply it again. The RDF vocabulary declares the mappingSource predicate. The catalog projection maps every entity field to a predicate, and its contract test requires a declaration for each one. Ontology entities stay out of the catalog graph, so no triple is written for it. The decision record gives the rules and amends ADR:2026-10-19-native-concept-bindings-remain-operational-metadata. --- .../mysql/postDataMigrationSQLScript.sql | 0 .../native/2.2.0/mysql/schemaChanges.sql | 20 ++++ .../postgres/postDataMigrationSQLScript.sql | 0 .../native/2.2.0/postgres/schemaChanges.sql | 8 ++ ...pt-bindings-remain-operational-metadata.md | 13 +++ ...inding-says-how-its-rows-become-records.md | 107 ++++++++++++++++++ .../json/schema/api/data/createOntology.json | 3 + .../api/data/ontologyMappingHealth.json | 105 +++++++++++++++++ .../json/schema/entity/data/ontology.json | 4 + .../schema/type/ontologyConceptBindings.json | 89 ++++++++++++++- .../type/ontologyConceptBindingsResponse.json | 13 ++- .../resources/rdf/ontology/openmetadata.ttl | 4 + 12 files changed, 364 insertions(+), 2 deletions(-) create mode 100644 bootstrap/sql/migrations/native/2.2.0/mysql/postDataMigrationSQLScript.sql create mode 100644 bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql create mode 100644 bootstrap/sql/migrations/native/2.2.0/postgres/postDataMigrationSQLScript.sql create mode 100644 bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql create mode 100644 docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md create mode 100644 openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json diff --git a/bootstrap/sql/migrations/native/2.2.0/mysql/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.2.0/mysql/postDataMigrationSQLScript.sql new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql new file mode 100644 index 000000000000..c08181c42a5f --- /dev/null +++ b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql @@ -0,0 +1,20 @@ +-- A table binding of an ontology class can say how its table takes part in the class's records: +-- its role, the ordered columns that identify one record, and one row filter. A row written +-- before these columns existed keeps NULL in all three and reads back as an unassigned binding +-- (ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records). +SET @ontology_concept_binding_role_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'ontology_concept_binding' + AND column_name = 'bindingRole' + ), + 'SELECT 1', + 'ALTER TABLE ontology_concept_binding ADD COLUMN bindingRole VARCHAR(16) NULL, ADD COLUMN subjectKey JSON NULL, ADD COLUMN rowFilter JSON NULL' + ) +); +PREPARE ontology_concept_binding_role_stmt FROM @ontology_concept_binding_role_ddl; +EXECUTE ontology_concept_binding_role_stmt; +DEALLOCATE PREPARE ontology_concept_binding_role_stmt; diff --git a/bootstrap/sql/migrations/native/2.2.0/postgres/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.2.0/postgres/postDataMigrationSQLScript.sql new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql new file mode 100644 index 000000000000..192de1eec334 --- /dev/null +++ b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql @@ -0,0 +1,8 @@ +-- A table binding of an ontology class can say how its table takes part in the class's records: +-- its role, the ordered columns that identify one record, and one row filter. A row written +-- before these columns existed keeps NULL in all three and reads back as an unassigned binding +-- (ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records). +ALTER TABLE ontology_concept_binding + ADD COLUMN IF NOT EXISTS bindingRole VARCHAR(16), + ADD COLUMN IF NOT EXISTS subjectKey JSONB, + ADD COLUMN IF NOT EXISTS rowFilter JSONB; diff --git a/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md b/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md index 2ea3d75d3a46..68329d134fec 100644 --- a/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md +++ b/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md @@ -2,6 +2,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-10-19 (initial) · v2 2026-10-23 (binding rows, bounded paging, the ontology data graph) · v3 2026-10-24 (write confirmation and complete read recovery) · v4 2026-10-26 (paged cleanup under the lock, lineage between returned assets) · v5 2026-10-26 (stateless combined graph pages) · v6 2026-10-30 (Data mode bindings page size and stale reload budget) · v7 2026-11-15 (UI guards moved to Collate) + · v8 2026-11-21 (a table binding carries a role, a subject key, a row filter and joins) - **Deciders:** Ontology Studio implementation review - **Guard:** OntologyConceptBindingsIT, OntologyConceptBindingCleanupIT, NativeOntologyDataGraphIT, NativeOntologyDataGraphEdgeScanIT, NativeOntologyDataGraphBindingScanIT, NativeOntologyDataGraphPageIT, NativeOntologyDataGraphContextIT, NativeOntologyDataGraphPagerTest, NativeOntologyDataGraphPagerRequestTest (including #aTokenTheServerKeySealedGetsTheRandomBytesRefusalBeforeAnyRead and #withoutAServerKeyAContinuedTopologyIssuesACursorTheNextRequestAccepts), NativeOntologyTopologyCursorCodecTest (including #aCursorKeyIsTheHmacOfItsServerKeyAndTheCursorLabel, #aCursorSealedUnderTheDerivedSecondKeyOfARotatedListStillOpens, #withoutAServerKeyOneKeyHeldForTheProcessSealsAndOpensCursors and #withoutAServerKeyACursorSealedWithAnotherKeyGetsTheSameRefusal), OntologyPrefixLineageDaoTest, OntologyBindingRulesTest, OntologyConceptBindingMigrationTest, ontologyAPI.test.ts, useOntologyConceptBindings.test.tsx *(openmetadata-collate)*, OntologyConceptAssets.test.tsx *(openmetadata-collate)*, OntologyColumnBindingEditor.test.tsx *(openmetadata-collate)*, OntologyPropertyBindings.test.tsx *(openmetadata-collate)*, OntologyConceptDataGraph.test.tsx, OntologyConceptInspector.test.tsx *(openmetadata-collate)* - **Related:** ADR:2026-10-17-glossaries-do-not-own-ontology-models, @@ -68,3 +69,15 @@ Every bindings selection asks for `limit` 25 (`NATIVE_ASSET_PAGE_SIZE` in `Ontol A 412 gets one automatic reload. `useNativeOntologyDataGraph` holds a load generation (`Generation` in the hook, unrelated to the server's topology generation above): an `AbortController` for its requests, a count of stale reloads, and a flag for its single topology restart after a 400. `beginGeneration` starts a new load generation when the hook mounts or its ontology changes, when a model revision or a binding write marks the graph stale (at once if Data mode shows, otherwise when it next shows), and when the user presses Retry. A new load generation aborts the previous one's requests and drops their answers. Within a load generation, the first 412 abandons the selection that received it and reloads from the first clusters page with an empty context. A second 412 before a selection completes and drains its topology ends loading with the stale message and a Retry, which begins a new load generation. A completed selection resets the count, so a later 412 in the same load generation again gets one reload. The reason recorded with the choice is that the client must never retry in a loop. After the second 412 the hook sends nothing on its own, but a **Load more** pressed before the failure still sends its one queued request, because the queue skips only requests from an earlier load generation. A 412 on that request shows the same error without another reload, and nothing else is sent until the user acts. `useNativeOntologyDataGraph.test.tsx` and `OntologyNativeDataGraph.utils.test.ts` assert the limit of 25 and the 412 sequence. The `Guard` line above still names `OntologyConceptDataGraph.test.tsx`, which #36724 deletes. `useNativeOntologyDataGraph.test.tsx`, `OntologyNativeDataGraph.utils.test.ts` and `OntologyNativeDataMode.test.tsx` guard this amendment. v7 (2026-11-15): the Ontology Studio UI moved to Collate (ADR:2026-11-15-ontology-studio-ui-ships-only-in-collate). The guard files marked *(openmetadata-collate)* moved with it, at the same paths under `collate-ui/src/main/resources/ui/`, and the parts of this rule they check now govern Collate's code. The rest is unchanged. + +## Amendment 2026-11-21. A table binding carries a role, a subject key, a row filter and joins + +ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records extends this record in three places. + +The binding row gains three nullable columns, `bindingRole`, `subjectKey` and `rowFilter`, and a column assignment gains an optional `join`. They are operational metadata like the rest of the row. They stay out of concept JSON, semantic working revisions, release digests and RDF import and export. + +Writes still require concept `EditAll` and target `ViewBasic`. A write that sets or changes a row filter also requires `ViewSampleData` on the table. A write that adds or changes a join also requires `ViewBasic` on the join target. + +The decision above describes a column assignment as a data-property UUID. The API also accepts an OBJECT property, and a column assignment to one that a write adds or changes must now carry a join. Once the ontology names a mapping source, a table binding that a write adds or changes must sit in that database. + +The identical-retry rule is unchanged. A write that repeats the stored row is a no-op and is checked against none of these rules, so a row written before them stays as it is until someone changes it. The tests that the new record names guard this amendment. diff --git a/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md b/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md new file mode 100644 index 000000000000..e9987a8aa339 --- /dev/null +++ b/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md @@ -0,0 +1,107 @@ +# A table binding says how its rows become records + +- **Status:** Accepted +- **Revisions:** v1 2026-11-21 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyBindingRulesTest`, `OntologyMappingHealthRulesTest`, `OntologyConceptBindingDaoTest`, `OntologyReleaseManifestTest#theMappingSourceOfAnOntologyIsNotCapturedDefinitionContent`, `IndependentOntologyTableBindingIT`, `IndependentOntologyMappingSourceIT`, `IndependentOntologyMappingHealthIT` +- **Related:** ADR:2026-10-19-native-concept-bindings-remain-operational-metadata (amended by this + record), ADR:2026-10-14-ontology-releases-seal-canonical-sql-members + +## Context + +A binding links a class to a catalog asset, and a column binding links a property to a column +(ADR:2026-10-19-native-concept-bindings-remain-operational-metadata). That tells a reader which +tables hold data about a class. It does not tell a reader how one row of such a table becomes one +record of the class. The binding did not say which columns identify a record, which of several +bound tables decides that a record exists, which rows belong to the class, or which table a +foreign-key column points at. Every consumer of a binding had to guess, and two consumers could +guess differently. + +A class can also be bound to tables in several databases. One SQL statement cannot be relied on to +join tables across databases, so such a class has no single query that reads its records. + +## Decision + +**An ontology may name one database as its mapping source.** `mappingSource` on the ontology is a +reference to one `database` entity. The server stores it as a `MAPPED_TO` relationship from the +ontology to the database, not in the ontology JSON, and returns it when a request asks for +`fields=mappingSource`. Setting, changing or clearing it requires `EditAll` on the ontology. A PUT +that names no mapping source keeps the stored one. A PATCH removes it. Setting it never reads, +changes or rejects the bindings that already exist, and a deleted database cannot become one. + +**A table binding may carry a role, a subject key and a row filter.** All three are absent on a +binding nobody has assigned, which includes every binding written before they existed. The server +never fills in a default. + +- `role` is `identity` or `contributing`. The identity table decides which records of the class + exist. A contributing table adds columns to those records. A class has at most one identity table. +- `subjectKey` is an ordered list of 1 to 16 column paths. A role and a subject key are set + together, and each key column must exist in the bound table when the key is set or changed. +- `rowFilter` is `{column, operator, value}`. `operator` is one of `equals`, `notEquals`, + `lessThan`, `lessThanOrEquals`, `greaterThan`, `greaterThanOrEquals`, `in`, `isNull` and + `isNotNull`. A comparison takes a string of at most 1024 characters, a number or a boolean. `in` + takes a list of 1 to 100 of them. `isNull` and `isNotNull` take no value. The server stores the + value as given. It does not compare the value with the column's data type and renders no SQL + from it. + +Only a table binding takes these fields. The native 2.2.0 migration adds three nullable columns to +`ontology_concept_binding` (`bindingRole`, `subjectKey` and `rowFilter`) and backfills nothing. +Each statement adds the columns only where they are missing, so running it again changes nothing. + +**A column bound to an OBJECT property carries a join.** `join` is +`{targetAssetId, status, on: [{child, parent}]}` with 1 to 16 pairs. Each `child` is a column of +the bound table and each `parent` is a column of the target table. `status` is `inferred` or +`confirmed`. The target is a table that the writer may view and that sits in the database of the +bound table. A column bound to a DATA property takes no join. + +**One step checks every binding write.** The step that saves a binding row runs under the ontology +lock and applies these rules, so no write path can skip them. + +- A write that sets or changes a row filter requires `ViewSampleData` on the table, on top of + `EditAll` on the class and `ViewBasic` on the table. A filter is a question about the rows of a + table, so it takes the right that reads those rows. Removing a filter requires no extra right, + because deleting the binding and writing it again without one already reaches that state. +- Once the ontology names a mapping source, a table binding that a write adds or changes must sit + in that database. A change of the mapping source takes the same lock. +- A write that repeats the stored row stays a no-op and is checked against no rule. A binding + written before a rule existed therefore stays as it is until someone changes it, and it can + always be deleted. + +**`GET /v1/ontologies/{id}/mappingHealth` lists what an editor still has to fix.** It requires view +access to the ontology and reads catalog metadata only. It never queries a bound table. It pages +the ontology's table bindings in class, then table id order, with a `limit` of at most 100 (default +50) and an opaque `after` cursor. It names only the classes, tables and properties that the caller +may view. The entry types are `noIdentityTable`, `unassignedBinding`, `relationColumnWithoutJoin`, +`joinNotConfirmed`, `keyLengthMismatch`, `keyTypeMismatch`, `joinTypeMismatch`, +`outsideMappingSource` and `multipleDatabases`. + +Two columns hold the same kind of data when their data types are equal or both belong to one of +four groups: numbers, character strings, timestamps, and binary strings. The key and join type +entries report a pair that fails this test. + +## Consequences + +Existing bindings read back unchanged and appear in mapping health as unassigned. An ontology whose +bindings span databases is reported and never migrated. An editor chooses a mapping source and +rebinds or deletes the bindings outside it. + +A key that differs from the identity table's key in length or type is a mapping health entry, not a +rejected write. The answer depends on another binding of the class, and an editor may write the two +in either order. + +The bindings PUT still replaces one whole asset association. A client that does not send `role`, +`subjectKey` or `rowFilter` clears them, and a client that adds an OBJECT property column without a +join gets a 400. + +The mapping source and the three binding fields stay out of release content. A release digest also +binds the version of every member, the ontology among them. A change of the mapping source therefore +writes its relationship row and records no field change. The ontology keeps its version and its +working revision, the release digest stays the same, and the change leaves no entry in the version +history and no change event. + +The mapping health cursor remembers one table for each of the first 8 databases it finds. An +ontology bound across more than 8 databases gets `multipleDatabases` again on later pages. + +Revisit the single mapping source if a class must be read across databases. The rule would then +name a set of databases, and every consumer of a join would have to handle a join that crosses +them. diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntology.json b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntology.json index 0db39fb23a65..c1f82b340a2d 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntology.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntology.json @@ -41,6 +41,9 @@ }, "approvalRule": { "$ref": "../../entity/data/ontology.json#/properties/approvalRule" + }, + "mappingSource": { + "$ref": "../../entity/data/ontology.json#/properties/mappingSource" } }, "required": [ diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json new file mode 100644 index 000000000000..11acd50e7e66 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json @@ -0,0 +1,105 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyMappingHealth.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyMappingHealth", + "description": "One page of what an editor must fix before the table bindings of an ontology's classes can be read as records. The check reads catalog metadata only and never queries a bound table. It examines table bindings in class then table id order, a bounded number per request, and names only tables the caller may view. A hidden or deleted table contributes no entry, name or count.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyMappingHealth", + "definitions": { + "columnPath": { + "description": "The exact name segments from a top-level column to the column named, as a column binding spells them. Absent on a finding that names no column.", + "type": "array", + "items": { "type": "string" }, + "default": null + }, + "entryType": { + "description": "What is wrong. `noIdentityTable`: the class has table bindings and none is its identity table. `unassignedBinding`: the table binding has no role. `relationColumnWithoutJoin`: a column bound to an OBJECT property has no join. `joinNotConfirmed`: a join is still `inferred`. `keyLengthMismatch`: a contributing table's subject key has a different number of columns than the identity table's. `keyTypeMismatch`: a contributing table's key column and the identity table's key column at the same position hold different kinds of data. `joinTypeMismatch`: the two columns of a join pair hold different kinds of data. `outsideMappingSource`: the bound table sits outside the ontology's mapping source. `multipleDatabases`: the ontology names no mapping source and its bound tables sit in more than one database. It is reported on each page that finds a database no earlier page found, once two are known.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyMappingHealthEntryType", + "enum": [ + "noIdentityTable", + "unassignedBinding", + "relationColumnWithoutJoin", + "joinNotConfirmed", + "keyLengthMismatch", + "keyTypeMismatch", + "joinTypeMismatch", + "outsideMappingSource", + "multipleDatabases" + ] + }, + "entry": { + "description": "One finding. `type` decides which of the other fields are present.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyMappingHealthEntry", + "properties": { + "type": { "$ref": "#/definitions/entryType" }, + "concept": { + "description": "The class the finding is about. Absent on `multipleDatabases`.", + "$ref": "../../type/entityReference.json" + }, + "asset": { + "description": "The bound table the finding is about. Absent on `noIdentityTable` and `multipleDatabases`.", + "$ref": "../../type/entityReference.json" + }, + "relatedAsset": { + "description": "The identity table on the key findings, and the join target on the join findings when the caller may view it.", + "$ref": "../../type/entityReference.json" + }, + "property": { + "description": "The property of the bound column on the relation column and join findings, when the caller may view it.", + "$ref": "../../type/entityReference.json" + }, + "columnPath": { + "description": "A column of `asset`: the bound column on `relationColumnWithoutJoin` and `joinNotConfirmed`, the key column on `keyTypeMismatch`, and the child column on `joinTypeMismatch`.", + "$ref": "#/definitions/columnPath" + }, + "relatedColumnPath": { + "description": "The column of `relatedAsset` that `columnPath` is paired with, on `keyTypeMismatch` and `joinTypeMismatch`.", + "$ref": "#/definitions/columnPath" + }, + "dataType": { + "description": "Data type of `columnPath` on the type findings.", + "$ref": "../../entity/data/table.json#/definitions/dataType" + }, + "relatedDataType": { + "description": "Data type of `relatedColumnPath` on the type findings.", + "$ref": "../../entity/data/table.json#/definitions/dataType" + }, + "keyLength": { + "description": "Number of subject key columns of `asset`, on `keyLengthMismatch`.", + "type": "integer" + }, + "relatedKeyLength": { + "description": "Number of subject key columns of the identity table, on `keyLengthMismatch`.", + "type": "integer" + }, + "databases": { + "description": "The database of `asset` on `outsideMappingSource`, and every database found so far on `multipleDatabases`.", + "type": "array", + "items": { "$ref": "../../type/entityReference.json" }, + "default": null + } + }, + "required": ["type"], + "additionalProperties": false + } + }, + "properties": { + "mappingSource": { + "description": "The ontology's mapping source, when it names one.", + "$ref": "../../type/entityReference.json" + }, + "entries": { + "type": "array", + "items": { "$ref": "#/definitions/entry" }, + "default": [] + }, + "after": { + "description": "Cursor for the next page. Absent when no table bindings follow. A page can hold no entries while a cursor follows.", + "type": "string" + } + }, + "required": ["entries"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontology.json b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontology.json index 02da5912e1c2..5a29ac754853 100644 --- a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontology.json +++ b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontology.json @@ -95,6 +95,10 @@ "approvalRule": { "description": "How many reviewers must approve a release review. Frozen into each review task when a review is requested.", "$ref": "../../type/ontologyApprovalRule.json" + }, + "mappingSource": { + "description": "The one database whose tables this ontology's classes bind. Once it is set, every table binding written for a class of this ontology must sit in this database. Bindings written earlier are left as they are and listed by the mapping health read. It is operational metadata. A change of it records no new version of the ontology, and releases and their digests leave it out. Setting, changing or clearing it requires EditAll on the ontology. Request it with `fields=mappingSource`.", + "$ref": "../../type/entityReference.json" } }, "required": [ diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindings.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindings.json index ad3f7f400b4e..255a8717bccd 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindings.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindings.json @@ -24,12 +24,87 @@ "minItems": 1, "maxItems": 32 }, + "role": { + "description": "How a bound table takes part in the records of its class. An `identity` table defines the records, and a class has at most one. A `contributing` table adds columns or relations to records the identity table defines. A binding without a role is unassigned.", + "type": "string", + "javaType": "org.openmetadata.schema.type.OntologyBindingRole", + "enum": ["identity", "contributing"] + }, + "subjectKey": { + "description": "The columns of the bound table that identify one record, in order. A contributing table lists its own columns in the order of the identity table's key, so position pairs them.", + "type": "array", + "items": { "$ref": "#/definitions/columnPath" }, + "minItems": 1, + "maxItems": 16, + "default": null + }, + "rowFilterOperator": { + "description": "The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value.", + "type": "string", + "javaType": "org.openmetadata.schema.type.OntologyRowFilterOperator", + "enum": ["equals", "notEquals", "lessThan", "lessThanOrEquals", "greaterThan", "greaterThanOrEquals", "in", "isNull", "isNotNull"] + }, + "rowFilter": { + "description": "One comparison on one column of the bound table that says which rows belong to the class. It is stored as written and is not checked against the column's data type here.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyRowFilter", + "properties": { + "column": { "$ref": "#/definitions/columnPath" }, + "operator": { "$ref": "#/definitions/rowFilterOperator" }, + "value": { + "description": "The value the column is compared with. A string of at most 1024 characters, a number or a boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent for `isNull` and `isNotNull`." + } + }, + "required": ["column", "operator"], + "additionalProperties": false + }, + "joinStatus": { + "description": "Whether a person has confirmed a join. An `inferred` join is a proposal, for example one read from a declared foreign key.", + "type": "string", + "javaType": "org.openmetadata.schema.type.OntologyJoinStatus", + "enum": ["inferred", "confirmed"] + }, + "joinColumnPair": { + "description": "One equality of a join. `child` is a column of the bound table and `parent` is a column of the target table.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyJoinColumnPair", + "properties": { + "child": { "$ref": "#/definitions/columnPath" }, + "parent": { "$ref": "#/definitions/columnPath" } + }, + "required": ["child", "parent"], + "additionalProperties": false + }, + "columnJoin": { + "description": "How a column bound to an OBJECT property reaches the table that holds the related records. A key of several columns takes one pair per column.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyColumnJoin", + "properties": { + "targetAssetId": { + "description": "The table that holds the related records. It sits in the same database as the bound table.", + "$ref": "basic.json#/definitions/uuid" + }, + "status": { "$ref": "#/definitions/joinStatus" }, + "on": { + "type": "array", + "items": { "$ref": "#/definitions/joinColumnPair" }, + "minItems": 1, + "maxItems": 16 + } + }, + "required": ["targetAssetId", "status", "on"], + "additionalProperties": false + }, "columnBinding": { "type": "object", "javaType": "org.openmetadata.schema.type.OntologyColumnBinding", "properties": { "propertyId": { "$ref": "basic.json#/definitions/uuid" }, - "columnPath": { "$ref": "#/definitions/columnPath" } + "columnPath": { "$ref": "#/definitions/columnPath" }, + "join": { + "description": "Required when the property is an OBJECT property, and not allowed otherwise. Columns bound before joins existed carry none.", + "$ref": "#/definitions/columnJoin" + } }, "required": ["propertyId", "columnPath"], "additionalProperties": false @@ -40,6 +115,18 @@ "properties": { "assetType": { "$ref": "#/definitions/assetType" }, "assetId": { "$ref": "basic.json#/definitions/uuid" }, + "role": { + "description": "Tables only. Absent on bindings written before roles existed and on bindings nobody has assigned.", + "$ref": "#/definitions/role" + }, + "subjectKey": { + "description": "Tables only. Present exactly when the binding has a role.", + "$ref": "#/definitions/subjectKey" + }, + "rowFilter": { + "description": "Tables only. Setting or changing it also requires ViewSampleData on the table.", + "$ref": "#/definitions/rowFilter" + }, "columns": { "type": "array", "items": { "$ref": "#/definitions/columnBinding" }, diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindingsResponse.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindingsResponse.json index 393db033affa..802ae6408198 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindingsResponse.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindingsResponse.json @@ -33,7 +33,15 @@ "enum": ["resolved", "unresolved"] }, "property": { "$ref": "entityReference.json" }, - "column": { "$ref": "#/definitions/column" } + "column": { "$ref": "#/definitions/column" }, + "join": { + "description": "The join as stored, so a client can send the binding back unchanged.", + "$ref": "ontologyConceptBindings.json#/definitions/columnJoin" + }, + "joinTarget": { + "description": "The join's target table. Absent when the column has no join, or when the table is deleted or hidden from the reader.", + "$ref": "entityReference.json" + } }, "required": ["propertyId", "columnPath", "state"], "additionalProperties": false @@ -49,6 +57,9 @@ "description": "Service type of the asset, for asset types that record one.", "type": "string" }, + "role": { "$ref": "ontologyConceptBindings.json#/definitions/role" }, + "subjectKey": { "$ref": "ontologyConceptBindings.json#/definitions/subjectKey" }, + "rowFilter": { "$ref": "ontologyConceptBindings.json#/definitions/rowFilter" }, "columns": { "type": "array", "items": { "$ref": "#/definitions/columnBinding" }, diff --git a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl index ec7c7d3df04c..a5d2d3dbcaa8 100644 --- a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl +++ b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl @@ -3261,6 +3261,10 @@ om:manifest a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "manifest" . +om:mappingSource a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "mappingSource" . + om:maximumMessageSize a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "maximumMessageSize" . From 7e4e6b4a31eacbf5dd5570a7d6bff9811a5254b3 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 22:19:30 -0800 Subject: [PATCH 013/203] Store and check the role, key, filter and joins of a table binding The binding DAO reads and writes the three new columns, and the store gains the reads the checks need: the identity rows of a class, the table rows of an ontology and the ontology's mapping source. A DAO test runs the migration over a table that already holds rows, then runs it a second time, and reads every row back as it was. The test database of the ontology DAO tests now runs the 2.2.0 statements as well. One step saves a binding row, under the ontology lock. It now checks that a role comes with key columns of the bound table, that a class has at most one identity table, that a row filter names a column of the table, and that a column bound to an OBJECT property joins to a table the writer may view in the same database. Once the ontology names a mapping source, the table must sit in that database. A write that sets or changes a row filter needs ViewSampleData on the table. A write that repeats the stored row stays a no-op, so a binding written before these rules stays valid until someone changes it. OntologyBindingAccess takes over the entity loading and authorization that the binding service did inline, so the checks and the service share it. Two integration tests change with the code they call. One writes a row through the new DAO signature. The other gives its relation columns the join they now need. --- .../NativeOntologyDataGraphBindingScanIT.java | 15 +- .../it/tests/OntologyConceptQueryIT.java | 26 +- .../jdbi3/OntologyConceptBindingDAO.java | 112 ++++++- .../jdbi3/OntologyConceptBindingStore.java | 66 +++- .../ontology/OntologyBindingAccess.java | 135 ++++++++ .../ontology/OntologyBindingRules.java | 141 ++++++++- .../OntologyConceptBindingService.java | 205 +++++------- .../ontology/OntologyTableBindingChecks.java | 132 ++++++++ .../jdbi3/OntologyConceptBindingDaoTest.java | 174 ++++++++++ .../service/jdbi3/OntologyTestDatabase.java | 17 +- .../ontology/OntologyBindingRulesTest.java | 296 ++++++++++++++++++ 11 files changed, 1163 insertions(+), 156 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableBindingChecks.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java index 2bec8513190d..ae359c7da2d8 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java @@ -41,6 +41,7 @@ import org.openmetadata.schema.type.OntologyBindingAssetType; import org.openmetadata.schema.type.OntologyHydratedAssetBinding; import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; import org.openmetadata.service.util.FullyQualifiedName; import org.openmetadata.service.util.RestUtil; @@ -189,11 +190,15 @@ void bindingKeysetsAdvanceAcrossConceptsSharingTheSameAsset(final TestNamespace Entity.getCollectionDAO() .ontologyConceptBindingDAO() .upsert( - concept.getId(), - topic.getId(), - OntologyBindingAssetType.TOPIC.value(), - FullyQualifiedName.buildHash(topic.getFullyQualifiedName()), - "[]"); + new StoredBinding( + concept.getId().toString(), + topic.getId().toString(), + OntologyBindingAssetType.TOPIC.value(), + FullyQualifiedName.buildHash(topic.getFullyQualifiedName()), + "[]", + null, + null, + null)); } final var observed = new ScanObservation(); final var graph = observed.watch(() -> graph(admin(), ontology, "")); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java index ff3c5a90bc56..37f372980218 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java @@ -46,6 +46,9 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; import org.openmetadata.schema.type.OntologyPropertyKind; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.utils.JsonUtils; @@ -136,7 +139,9 @@ void aHopWithoutAConstraintJoinsAnObjectPropertyBindingToTheTargetIdentifier( bind( payments.transfer(), transfers, - List.of(column(transferId, "transfer_id"), column(payments.partOf(), "payer_id")), + List.of( + column(transferId, "transfer_id"), + relation(payments.partOf(), "payer_id", customers, "customer_id")), 0L); bind(payments.customer(), customers, List.of(column(customerId, "customer_id")), 0L); @@ -383,7 +388,9 @@ private SelfKey selfKeyEmployees(final TestNamespace ns, final String name) { bind( employee, employees, - List.of(column(employeeId, "employee_id"), column(managedBy, "manager_id")), + List.of( + column(employeeId, "employee_id"), + relation(managedBy, "manager_id", employees, "employee_id")), 0L); return new SelfKey(employee, managedBy, manages, payments.schema().getName()); } @@ -525,6 +532,21 @@ private static OntologyColumnBinding column(final OntologyProperty property, fin .withColumnPath(List.of(name)); } + /** A column bound to an OBJECT property, joined to the key of the table it points at. */ + private static OntologyColumnBinding relation( + final OntologyProperty property, final String name, final Table target, final String key) { + return column(property, name) + .withJoin( + new OntologyColumnJoin() + .withTargetAssetId(target.getId()) + .withStatus(OntologyJoinStatus.CONFIRMED) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(name)) + .withParent(List.of(key))))); + } + private static OntologyProperty dataProperty( final Ontology ontology, final String name, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java index 912c55f4b992..72a6b808a133 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java @@ -16,6 +16,7 @@ import static org.openmetadata.service.jdbi3.locator.ConnectionType.MYSQL; import static org.openmetadata.service.jdbi3.locator.ConnectionType.POSTGRES; +import com.fasterxml.jackson.core.type.TypeReference; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -28,31 +29,56 @@ import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.BindList; +import org.jdbi.v3.sqlobject.customizer.BindMethods; import org.jdbi.v3.sqlobject.customizer.Define; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyRowFilter; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlQuery; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlUpdate; -import org.openmetadata.service.util.jdbi.BindJson; import org.openmetadata.service.util.jdbi.BindUUID; /** One row per native concept and bound catalog asset, ordered by asset id within a concept. */ public interface OntologyConceptBindingDAO { - String COLUMNS = "conceptId, assetId, assetType, assetFqnHash, columnBindings"; + String COLUMNS = + "conceptId, assetId, assetType, assetFqnHash, columnBindings, bindingRole, subjectKey, " + + "rowFilter"; + String BINDING_COLUMNS = + "binding.conceptId, binding.assetId, binding.assetType, binding.assetFqnHash, " + + "binding.columnBindings, binding.bindingRole, binding.subjectKey, binding.rowFilter"; + String IDENTITY_ROLE = "identity"; String BOUND_CONCEPTS = "FROM ontology_concept_binding binding " + "JOIN ontology_concept_entity concept ON concept.id = binding.conceptId " + "WHERE concept.ontologyId = :ontologyId AND concept.deleted = FALSE"; + /** + * {@code role}, {@code subjectKey} and {@code rowFilter} are null on every asset that is not a + * table and on table rows nobody has assigned, which includes every row written before they + * existed. + */ record BindingRow( UUID conceptId, UUID assetId, OntologyBindingAssetType assetType, String assetFqnHash, - List columns) { + List columns, + OntologyBindingRole role, + List> subjectKey, + OntologyRowFilter rowFilter) { + public BindingRow( + final UUID conceptId, + final UUID assetId, + final OntologyBindingAssetType assetType, + final String assetFqnHash, + final List columns) { + this(conceptId, assetId, assetType, assetFqnHash, columns, null, null, null); + } + public static Map> assetIdsByType( final List rows) { final Map> ids = @@ -64,6 +90,17 @@ public static Map> assetIdsByType( } } + /** One row as the values its columns take, with each JSON column already serialized. */ + record StoredBinding( + String conceptId, + String assetId, + String assetType, + String assetFqnHash, + String columnBindings, + String bindingRole, + String subjectKey, + String rowFilter) {} + record ConceptAssetCount(UUID conceptId, long assetCount) {} record BindingPosition(UUID conceptId, UUID assetId) {} @@ -74,25 +111,26 @@ record LiveAsset(UUID id, String serviceType) {} value = "INSERT INTO ontology_concept_binding(" + COLUMNS - + ") VALUES (:conceptId, :assetId, :assetType, :assetFqnHash, :columnBindings) " + + ") VALUES (:conceptId, :assetId, :assetType, :assetFqnHash, :columnBindings, " + + ":bindingRole, :subjectKey, :rowFilter) " + "ON DUPLICATE KEY UPDATE assetType = VALUES(assetType), " - + "assetFqnHash = VALUES(assetFqnHash), columnBindings = VALUES(columnBindings)", + + "assetFqnHash = VALUES(assetFqnHash), columnBindings = VALUES(columnBindings), " + + "bindingRole = VALUES(bindingRole), subjectKey = VALUES(subjectKey), " + + "rowFilter = VALUES(rowFilter)", connectionType = MYSQL) @ConnectionAwareSqlUpdate( value = "INSERT INTO ontology_concept_binding(" + COLUMNS + ") VALUES (:conceptId, :assetId, :assetType, :assetFqnHash, " - + "(:columnBindings :: jsonb)) " + + "(:columnBindings :: jsonb), :bindingRole, (:subjectKey :: jsonb), " + + "(:rowFilter :: jsonb)) " + "ON CONFLICT (conceptId, assetId) DO UPDATE SET assetType = EXCLUDED.assetType, " - + "assetFqnHash = EXCLUDED.assetFqnHash, columnBindings = EXCLUDED.columnBindings", + + "assetFqnHash = EXCLUDED.assetFqnHash, columnBindings = EXCLUDED.columnBindings, " + + "bindingRole = EXCLUDED.bindingRole, subjectKey = EXCLUDED.subjectKey, " + + "rowFilter = EXCLUDED.rowFilter", connectionType = POSTGRES) - void upsert( - @BindUUID("conceptId") UUID conceptId, - @BindUUID("assetId") UUID assetId, - @Bind("assetType") String assetType, - @Bind("assetFqnHash") String assetFqnHash, - @BindJson("columnBindings") String columnBindings); + void upsert(@BindMethods StoredBinding binding); @SqlUpdate( "DELETE FROM ontology_concept_binding WHERE conceptId = :conceptId AND assetId = :assetId") @@ -162,6 +200,35 @@ List listForConceptsAfter( List listFirstTablesForConcepts( @BindList("conceptIds") List conceptIds, @Bind("perConcept") int perConcept); + /** The identity table rows of these concepts. A concept holds at most one live identity table. */ + @SqlQuery( + "SELECT " + + COLUMNS + + " FROM ontology_concept_binding WHERE conceptId IN () " + + "AND bindingRole = '" + + IDENTITY_ROLE + + "' ORDER BY conceptId ASC, assetId ASC") + @RegisterRowMapper(BindingRowMapper.class) + List listIdentityRows(@BindList("conceptIds") List conceptIds); + + /** One page of the table rows of an ontology's live concepts, in concept then asset id order. */ + @SqlQuery( + "SELECT " + + BINDING_COLUMNS + + " " + + BOUND_CONCEPTS + + " AND binding.assetType = 'table' " + + "AND (:hasAfter = FALSE OR binding.conceptId > :afterConceptId " + + "OR (binding.conceptId = :afterConceptId AND binding.assetId > :afterAssetId)) " + + "ORDER BY binding.conceptId ASC, binding.assetId ASC LIMIT :limit") + @RegisterRowMapper(BindingRowMapper.class) + List listTablesForOntologyAfter( + @BindUUID("ontologyId") UUID ontologyId, + @Bind("hasAfter") boolean hasAfter, + @Bind("afterConceptId") String afterConceptId, + @Bind("afterAssetId") String afterAssetId, + @Bind("limit") int limit); + @SqlQuery( "SELECT binding.conceptId, COUNT(*) AS assetCount " + BOUND_CONCEPTS @@ -191,6 +258,8 @@ List listBoundConcepts( List findLiveAssets(@Define("table") String table, @BindList("ids") List ids); class BindingRowMapper implements RowMapper { + private static final TypeReference>> SUBJECT_KEY = new TypeReference<>() {}; + @Override public BindingRow map(final ResultSet rs, final StatementContext ctx) throws SQLException { return new BindingRow( @@ -198,7 +267,22 @@ public BindingRow map(final ResultSet rs, final StatementContext ctx) throws SQL UUID.fromString(rs.getString("assetId")), OntologyBindingAssetType.fromValue(rs.getString("assetType")), rs.getString("assetFqnHash"), - JsonUtils.readObjects(rs.getString("columnBindings"), OntologyColumnBinding.class)); + JsonUtils.readObjects(rs.getString("columnBindings"), OntologyColumnBinding.class), + role(rs.getString("bindingRole")), + subjectKey(rs.getString("subjectKey")), + rowFilter(rs.getString("rowFilter"))); + } + + private static OntologyBindingRole role(final String stored) { + return stored == null ? null : OntologyBindingRole.fromValue(stored); + } + + private static List> subjectKey(final String stored) { + return stored == null ? null : JsonUtils.readValue(stored, SUBJECT_KEY); + } + + private static OntologyRowFilter rowFilter(final String stored) { + return stored == null ? null : JsonUtils.readValue(stored, OntologyRowFilter.class); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 0b471948073b..93c16e2d5b9f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -1,6 +1,7 @@ package org.openmetadata.service.jdbi3; import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import java.net.URI; import java.util.Collection; @@ -18,16 +19,20 @@ import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyBindingAssetType; import org.openmetadata.schema.type.OntologyConceptBindings; +import org.openmetadata.schema.type.Relationship; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.CoreRelationshipDAOs.EntityRelationshipRecord; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingPosition; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.ConceptAssetCount; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.LiveAsset; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; import org.openmetadata.service.ontology.OntologyClassHierarchy; import org.openmetadata.service.ontology.OntologyWriteClosureLimits; import org.openmetadata.service.util.FreshReadScope; +import org.openmetadata.service.util.JsonStorageUtils; /** * Operational catalog associations share the ontology lock without advancing semantic revisions. @@ -43,6 +48,9 @@ public final class OntologyConceptBindingStore { */ public static final int SCAN_PAGE_SIZE = 500; + /** How an ontology points at its mapping source database. */ + public static final Relationship MAPPING_SOURCE_RELATION = Relationship.MAPPED_TO; + private static final String SCHEMA = "ontologyConceptBindings"; private static final String FIRST_PAGE = ""; private static final int MAX_ANCESTORS = OntologyWriteClosureLimits.BINDING_ANCESTORS; @@ -139,6 +147,46 @@ public List liveProperties(final UUID ontologyId, final Collec .toList(); } + /** The identity table rows of these concepts, whether or not their tables still exist. */ + public List identityRows(final Collection conceptIds) { + return conceptIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + conceptIds.stream().map(UUID::toString).distinct().toList(), + chunk -> dao.ontologyConceptBindingDAO().listIdentityRows(chunk)); + } + + /** One page of an ontology's table rows in concept then asset id order, after a position. */ + public List tableRows( + final UUID ontologyId, final BindingPosition after, final int limit) { + return dao.ontologyConceptBindingDAO() + .listTablesForOntologyAfter( + ontologyId, + after != null, + after == null ? FIRST_PAGE : after.conceptId().toString(), + after == null ? FIRST_PAGE : after.assetId().toString(), + limit); + } + + /** + * The database an ontology names as its mapping source, or null when it names none. A binding + * write reads it under the ontology lock that a change of the mapping source also takes. + */ + public UUID mappingSource(final UUID ontologyId) { + return mappingSource(dao, ontologyId); + } + + /** The stored mapping source of an ontology, read from its relationship row. */ + public static UUID mappingSource(final CollectionDAO dao, final UUID ontologyId) { + return dao + .relationshipDAO() + .findTo(ontologyId, Entity.ONTOLOGY, MAPPING_SOURCE_RELATION.ordinal(), Entity.DATABASE) + .stream() + .map(EntityRelationshipRecord::getId) + .findFirst() + .orElse(null); + } + public List firstTables(final Collection conceptIds, final int perConcept) { return conceptIds.isEmpty() ? List.of() @@ -202,11 +250,19 @@ private long updateLocked(final OntologyConcept concept, final Mutation mutation public void save(final UUID conceptId, final OntologyAssetBinding asset, final String fqnHash) { dao.ontologyConceptBindingDAO() .upsert( - conceptId, - asset.getAssetId(), - asset.getAssetType().value(), - fqnHash, - JsonUtils.pojoToJson(listOrEmpty(asset.getColumns()))); + new StoredBinding( + conceptId.toString(), + asset.getAssetId().toString(), + asset.getAssetType().value(), + fqnHash, + storedJson(listOrEmpty(asset.getColumns())), + asset.getRole() == null ? null : asset.getRole().value(), + nullOrEmpty(asset.getSubjectKey()) ? null : storedJson(asset.getSubjectKey()), + asset.getRowFilter() == null ? null : storedJson(asset.getRowFilter()))); + } + + private static String storedJson(final Object value) { + return JsonStorageUtils.sanitizeNulCharacters(JsonUtils.pojoToJson(value)); } public void remove(final UUID conceptId, final UUID assetId) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java new file mode 100644 index 000000000000..0a14f6fc10ca --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java @@ -0,0 +1,135 @@ +package org.openmetadata.service.ontology; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.BulkFieldHydrator; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.util.EntityUtil.Fields; + +/** + * Loads the catalog entities a binding names through their canonical repositories and applies the + * caller's current policies to each one. + */ +@Slf4j +final class OntologyBindingAccess { + private final Authorizer authorizer; + private final Function> repositories; + + OntologyBindingAccess( + final Authorizer authorizer, final Function> repositories) { + this.authorizer = authorizer; + this.repositories = repositories; + } + + /** The live entity, or an authorization or not-found failure for the caller. */ + EntityInterface authorized( + final Access access, final String type, final UUID id, final MetadataOperation operation) { + return authorized(access, repositories.apply(type), id, operation); + } + + /** The live entity when the caller may view it, and empty when it is hidden or gone. */ + Optional> readable(final Access access, final String type, final UUID id) { + try { + return Optional.of(authorized(access, type, id, MetadataOperation.VIEW_BASIC)); + } catch (final AuthorizationException | EntityNotFoundException unavailable) { + LOG.debug("Binding target {} {} is unavailable to the current reader", type, id); + return Optional.empty(); + } + } + + /** Applies one more operation to an entity of {@code type} already loaded for the caller. */ + void require( + final Access access, + final String type, + final EntityInterface entity, + final MetadataOperation operation) { + require(access, repositories.apply(type), entity, operation); + } + + /** The live entities of one type that the caller may view, by id, read in one statement. */ + Map> viewable( + final Access access, final String type, final Collection ids) { + final Map> viewable = new HashMap<>(); + loadViewable(access, repositories.apply(type), ids.stream().distinct().toList(), viewable); + return viewable; + } + + private > void loadViewable( + final Access access, + final EntityRepository repository, + final List ids, + final Map> viewable) { + if (ids.isEmpty()) { + return; + } + final List entities = + repository.get(access.uriInfo(), ids, fields(repository), Include.NON_DELETED); + final var tags = BulkFieldHydrator.forTags(repository, entities); + for (final T entity : entities) { + try { + authorizer.authorize( + access.securityContext(), + new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), + new ResourceContext<>(repository.getEntityType(), entity, repository, tags)); + viewable.put(entity.getId(), entity); + } catch (final AuthorizationException hidden) { + LOG.debug( + "Binding target {} {} is hidden from the reader", + repository.getEntityType(), + entity.getId()); + } + } + } + + private > T authorized( + final Access access, + final EntityRepository repository, + final UUID id, + final MetadataOperation operation) { + final T entity = + repository.get(access.uriInfo(), id, fields(repository), Include.NON_DELETED, false); + authorizer.authorize( + access.securityContext(), + new OperationContext(repository.getEntityType(), operation), + new ResourceContext<>(repository.getEntityType(), entity, repository)); + return entity; + } + + private > void require( + final Access access, + final EntityRepository repository, + final EntityInterface entity, + final MetadataOperation operation) { + authorizer.authorize( + access.securityContext(), + new OperationContext(repository.getEntityType(), operation), + new ResourceContext<>( + repository.getEntityType(), repository.getEntityClass().cast(entity), repository)); + } + + private static Fields fields(final EntityRepository repository) { + final var fieldNames = + new HashSet<>(ResourceContext.authorizationFields(repository).getFieldList()); + if (Entity.TABLE.equals(repository.getEntityType())) { + fieldNames.add(Entity.FIELD_COLUMNS); + } + return new Fields(fieldNames); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java index 29cc839ae1c5..b255537e5217 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java @@ -6,7 +6,9 @@ import jakarta.ws.rs.core.Response; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Set; +import java.util.UUID; import org.openmetadata.schema.FieldInterface; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; @@ -14,15 +16,24 @@ import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.util.ChildFieldResolver; public final class OntologyBindingRules { public static final int MAX_ASSET_COLUMNS = 100; public static final int MAX_CONCEPT_COLUMNS = 500; + public static final int MAX_KEY_COLUMNS = 16; + public static final int MAX_JOIN_PAIRS = 16; + public static final int MAX_FILTER_VALUES = 100; + public static final int MAX_FILTER_TEXT_LENGTH = 1024; private static final int MAX_PATH_DEPTH = 32; private static final int MAX_SEGMENT_LENGTH = 256; private static final long MAX_REVISION = 9_007_199_254_740_991L; @@ -49,16 +60,114 @@ public static void validate(final OntologyAssetBinding asset) { "Only tables support column bindings, with at most 100 per asset"); } columns.forEach(OntologyBindingRules::validateColumn); - if (new HashSet<>(columns).size() != columns.size()) { + if (columns.stream().map(ColumnKey::of).distinct().count() != columns.size()) { throw new BadRequestException("Duplicate property and column bindings are not allowed"); } + validateRecordMapping(asset); + } + + /** One property bound to one column. Two bindings of the pair differ at most in their join. */ + private record ColumnKey(UUID propertyId, List columnPath) { + private static ColumnKey of(final OntologyColumnBinding binding) { + return new ColumnKey(binding.getPropertyId(), binding.getColumnPath()); + } } private static void validateColumn(final OntologyColumnBinding binding) { if (binding == null || binding.getPropertyId() == null) { throw new BadRequestException("A column binding requires a property UUID"); } - final var path = listOrEmpty(binding.getColumnPath()); + requireColumnPath(binding.getColumnPath()); + if (binding.getJoin() != null) { + validateJoin(binding.getJoin()); + } + } + + private static void validateJoin(final OntologyColumnJoin join) { + final var pairs = listOrEmpty(join.getOn()); + if (join.getTargetAssetId() == null + || join.getStatus() == null + || pairs.isEmpty() + || pairs.size() > MAX_JOIN_PAIRS + || pairs.stream().anyMatch(Objects::isNull) + || new HashSet<>(pairs).size() != pairs.size()) { + throw new BadRequestException( + "A join requires a target table, a status and 1 to 16 distinct column pairs"); + } + pairs.forEach(OntologyBindingRules::validatePair); + } + + private static void validatePair(final OntologyJoinColumnPair pair) { + requireColumnPath(pair.getChild()); + requireColumnPath(pair.getParent()); + } + + private static void validateRecordMapping(final OntologyAssetBinding asset) { + final var key = listOrEmpty(asset.getSubjectKey()); + final boolean mapped = + asset.getRole() != null || !key.isEmpty() || asset.getRowFilter() != null; + if (mapped && asset.getAssetType() != OntologyBindingAssetType.TABLE) { + throw new BadRequestException( + "Only table bindings take a role, a subject key or a row filter"); + } + validateSubjectKey(asset.getRole(), key); + if (asset.getRowFilter() != null) { + validateRowFilter(asset.getRowFilter()); + } + } + + private static void validateSubjectKey( + final OntologyBindingRole role, final List> key) { + if ((role == null) != key.isEmpty()) { + throw new BadRequestException( + "A role and a subject key are set together. A binding with a role names its key columns, and a binding without a role names none"); + } + if (key.size() > MAX_KEY_COLUMNS || new HashSet<>(key).size() != key.size()) { + throw new BadRequestException("A subject key takes 1 to 16 distinct columns"); + } + key.forEach(OntologyBindingRules::requireColumnPath); + } + + private static void validateRowFilter(final OntologyRowFilter filter) { + if (filter.getOperator() == null) { + throw new BadRequestException("A row filter requires a column and a supported operator"); + } + requireColumnPath(filter.getColumn()); + final Object value = filter.getValue(); + final boolean valid = + switch (filter.getOperator()) { + case IS_NULL, IS_NOT_NULL -> value == null; + case IN -> isFilterList(value); + case EQUALS, + NOT_EQUALS, + LESS_THAN, + LESS_THAN_OR_EQUALS, + GREATER_THAN, + GREATER_THAN_OR_EQUALS -> isFilterScalar(value); + }; + if (!valid) { + throw new BadRequestException( + "A row filter compares with a string of at most 1024 characters, a number or a boolean. `in` takes a list of 1 to 100 of them, and `isNull` and `isNotNull` take no value"); + } + } + + private static boolean isFilterList(final Object value) { + return value instanceof List values + && !values.isEmpty() + && values.size() <= MAX_FILTER_VALUES + && values.stream().allMatch(OntologyBindingRules::isFilterScalar); + } + + private static boolean isFilterScalar(final Object value) { + return value instanceof Number + || value instanceof Boolean + || (value instanceof String text + && text.length() <= MAX_FILTER_TEXT_LENGTH + && text.indexOf('\u0000') < 0); + } + + private static void requireColumnPath(final List columnPath) { + final var path = listOrEmpty(columnPath); if (path.isEmpty() || path.size() > MAX_PATH_DEPTH || path.stream().anyMatch(OntologyBindingRules::invalidSegment)) { @@ -80,6 +189,18 @@ public static boolean sameColumns( return new HashSet<>(listOrEmpty(stored)).equals(new HashSet<>(listOrEmpty(requested))); } + /** + * Whether a write would leave the stored binding as it is. Such a write is a no-op. It commits no + * revision and is checked against no rule. + */ + public static boolean sameBinding(final BindingRow stored, final OntologyAssetBinding requested) { + return stored.assetType() == requested.getAssetType() + && sameColumns(stored.columns(), requested.getColumns()) + && stored.role() == requested.getRole() + && listOrEmpty(stored.subjectKey()).equals(listOrEmpty(requested.getSubjectKey())) + && Objects.equals(stored.rowFilter(), requested.getRowFilter()); + } + /** The revision a changed write commits, or 409 when the writer did not see the current one. */ public static long nextRevision(final long current, final long expected) { if (current != expected || current == MAX_REVISION) { @@ -109,6 +230,22 @@ public static Column resolveColumn(final Table table, final List path) { return selected instanceof Column column ? column : null; } + /** + * A column bound to an OBJECT property says where its related records live, so it carries a join. + * A column bound to a DATA property holds the values themselves and carries none. + */ + public static void requireJoinFor( + final OntologyProperty property, final OntologyColumnBinding binding) { + final boolean relation = property.getKind() == OntologyPropertyKind.OBJECT; + if (relation && binding.getJoin() == null) { + throw new BadRequestException( + "A column bound to an OBJECT property requires a join to the table that holds the related records"); + } + if (!relation && binding.getJoin() != null) { + throw new BadRequestException("Only a column bound to an OBJECT property takes a join"); + } + } + /** * A DATA property binds the column that holds its values. An OBJECT property binds a foreign-key * column that refers to the target concept's identifier column, which SQL generation joins on. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java index dbf57dc4c7ee..dd395fdb745a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java @@ -7,7 +7,6 @@ import jakarta.ws.rs.core.UriInfo; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -21,9 +20,8 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.Column; -import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; -import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyAssetConceptLink; import org.openmetadata.schema.type.OntologyAssetConceptLinks; import org.openmetadata.schema.type.OntologyBindingAssetType; @@ -39,12 +37,9 @@ import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyTableBindingChecks.Write; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; -import org.openmetadata.service.security.policyevaluator.BulkFieldHydrator; -import org.openmetadata.service.security.policyevaluator.OperationContext; -import org.openmetadata.service.security.policyevaluator.ResourceContext; -import org.openmetadata.service.util.EntityUtil.Fields; import org.openmetadata.service.util.FreshReadScope; import org.openmetadata.service.util.FullyQualifiedName; import org.openmetadata.service.util.RestUtil; @@ -57,8 +52,8 @@ public final class OntologyConceptBindingService { private static final int MAX_CURSOR_LENGTH = 256; private final OntologyConceptBindingStore store; - private final Authorizer authorizer; - private final Function> repositories; + private final OntologyBindingAccess targets; + private final OntologyTableBindingChecks tableChecks; public record Access(UriInfo uriInfo, SecurityContext securityContext) {} @@ -67,8 +62,8 @@ public OntologyConceptBindingService( final Authorizer authorizer, final Function> repositories) { this.store = store; - this.authorizer = authorizer; - this.repositories = repositories; + this.targets = new OntologyBindingAccess(authorizer, repositories); + this.tableChecks = new OntologyTableBindingChecks(targets); } public OntologyConceptBindingsResponse get( @@ -90,7 +85,8 @@ public OntologyAssetConceptLinks linksForAsset( final Access access, final String assetType, final UUID assetId) { final var type = assetType(assetType); try (final var ignored = FreshReadScope.enter()) { - final var asset = authorized(access, type.value(), assetId, MetadataOperation.VIEW_BASIC); + final var asset = + targets.authorized(access, type.value(), assetId, MetadataOperation.VIEW_BASIC); final Map> properties = new HashMap<>(); final List links = new ArrayList<>(); // Rows are paged by concept id and filtered afterwards, so concepts the reader cannot see @@ -167,7 +163,7 @@ public OntologyConceptBindingsResponse remove( concept, (lockedConcept, locked, current) -> { concept(access, lockedConcept.getId(), MetadataOperation.EDIT_ALL); - authorized(access, type.value(), assetId, MetadataOperation.VIEW_BASIC); + targets.authorized(access, type.value(), assetId, MetadataOperation.VIEW_BASIC); if (locked.find(lockedConcept.getId(), assetId) == null) { return current; } @@ -188,19 +184,20 @@ private long replace( concept(access, concept.getId(), MetadataOperation.EDIT_ALL); final var asset = request.getAsset(); final var target = - authorized( + targets.authorized( access, asset.getAssetType().value(), asset.getAssetId(), MetadataOperation.VIEW_BASIC); final var existing = locked.find(concept.getId(), asset.getAssetId()); - if (existing != null - && existing.assetType() == asset.getAssetType() - && OntologyBindingRules.sameColumns(existing.columns(), asset.getColumns())) { + if (existing != null && OntologyBindingRules.sameBinding(existing, asset)) { return current; } final long next = OntologyBindingRules.nextRevision(current, request.getExpectedRevision()); final int retained = prune(locked, concept.getId(), asset.getAssetId()); OntologyBindingRules.requireColumnCapacity(retained + listOrEmpty(asset.getColumns()).size()); - validateColumns( - access, concept, existing == null ? List.of() : existing.columns(), asset, target); + if (target instanceof Table table) { + final var write = new Write(access, concept, locked, existing, asset, table); + tableChecks.check(write); + validateColumns(write); + } locked.save( concept.getId(), asset, FullyQualifiedName.buildHash(target.getFullyQualifiedName())); return next; @@ -240,31 +237,38 @@ private static int retainLive( .sum(); } - private void validateColumns( - final Access access, - final OntologyConcept concept, - final List retained, - final OntologyAssetBinding asset, - final EntityInterface target) { + /** + * Checks the column bindings this write adds or changes. One sent back exactly as stored is left + * alone, so a column whose property or path no longer resolves stays until it is rebound. + */ + private void validateColumns(final Write write) { + final List retained = + write.existing() == null ? List.of() : write.existing().columns(); final var additions = - listOrEmpty(asset.getColumns()).stream() + listOrEmpty(write.asset().getColumns()).stream() .filter(binding -> !retained.contains(binding)) .toList(); - final var ancestors = additions.isEmpty() ? Set.of() : store.ancestors(concept); - for (final var binding : additions) { - final var property = - (OntologyProperty) - authorized( - access, - Entity.ONTOLOGY_PROPERTY, - binding.getPropertyId(), - MetadataOperation.VIEW_BASIC); - if (!OntologyBindingRules.isApplicable(concept, property, ancestors) - || !(target instanceof Table table) - || OntologyBindingRules.resolveColumn(table, binding.getColumnPath()) == null) { - throw new BadRequestException( - "Bindings require an applicable same-ontology DATA or OBJECT property and an existing exact column path"); - } + final var ancestors = additions.isEmpty() ? Set.of() : store.ancestors(write.concept()); + additions.forEach(binding -> validateColumn(write, binding, ancestors)); + } + + private void validateColumn( + final Write write, final OntologyColumnBinding binding, final Set ancestors) { + final var property = + (OntologyProperty) + targets.authorized( + write.access(), + Entity.ONTOLOGY_PROPERTY, + binding.getPropertyId(), + MetadataOperation.VIEW_BASIC); + if (!OntologyBindingRules.isApplicable(write.concept(), property, ancestors) + || OntologyBindingRules.resolveColumn(write.table(), binding.getColumnPath()) == null) { + throw new BadRequestException( + "Bindings require an applicable same-ontology DATA or OBJECT property and an existing exact column path"); + } + OntologyBindingRules.requireJoinFor(property, binding); + if (binding.getJoin() != null) { + tableChecks.checkJoin(write, binding.getJoin()); } } @@ -324,11 +328,9 @@ private List visibleAssets(final Access access, final List BindingRow.assetIdsByType(rows) .forEach( (type, ids) -> - loadViewable( - access, - repositories.apply(type.value()), - ids.stream().filter(live::containsKey).toList(), - viewable)); + viewable.putAll( + targets.viewable( + access, type.value(), ids.stream().filter(live::containsKey).toList()))); return rows.stream() .filter(row -> viewable.containsKey(row.assetId())) .map( @@ -338,33 +340,6 @@ private List visibleAssets(final Access access, final List .toList(); } - private > void loadViewable( - final Access access, - final EntityRepository repository, - final List ids, - final Map> viewable) { - if (ids.isEmpty()) { - return; - } - final List entities = - repository.get(access.uriInfo(), ids, fields(repository), Include.NON_DELETED); - final var tags = BulkFieldHydrator.forTags(repository, entities); - for (final T entity : entities) { - try { - authorizer.authorize( - access.securityContext(), - new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), - new ResourceContext<>(repository.getEntityType(), entity, repository, tags)); - viewable.put(entity.getId(), entity); - } catch (final AuthorizationException hidden) { - LOG.debug( - "Binding target {} {} is hidden from the reader", - repository.getEntityType(), - entity.getId()); - } - } - } - private OntologyHydratedAssetBinding hydrateAsset( final Hydration hydration, final Visible visible) { return new OntologyHydratedAssetBinding() @@ -372,6 +347,9 @@ private OntologyHydratedAssetBinding hydrateAsset( .withAssetId(visible.row().assetId()) .withAsset(visible.entity().getEntityReference()) .withServiceType(visible.serviceType()) + .withRole(visible.row().role()) + .withSubjectKey(visible.row().subjectKey()) + .withRowFilter(visible.row().rowFilter()) .withColumns( visible.row().columns().stream() .map(column -> hydrateColumn(hydration, visible.entity(), column)) @@ -388,7 +366,8 @@ private OntologyHydratedColumnBinding hydrateColumn( .computeIfAbsent( binding.getPropertyId(), id -> - readable(hydration.access(), Entity.ONTOLOGY_PROPERTY, id) + targets + .readable(hydration.access(), Entity.ONTOLOGY_PROPERTY, id) .map(OntologyProperty.class::cast)); final var column = asset instanceof Table table @@ -408,7 +387,24 @@ private OntologyHydratedColumnBinding hydrateColumn( .withState( resolved ? OntologyColumnBindingState.RESOLVED : OntologyColumnBindingState.UNRESOLVED) .withProperty(property.map(OntologyProperty::getEntityReference).orElse(null)) - .withColumn(column == null ? null : columnMetadata(column)); + .withColumn(column == null ? null : columnMetadata(column)) + .withJoin(binding.getJoin()) + .withJoinTarget(joinTarget(hydration, binding)); + } + + private EntityReference joinTarget( + final Hydration hydration, final OntologyColumnBinding binding) { + return binding.getJoin() == null + ? null + : hydration + .joinTargets() + .computeIfAbsent( + binding.getJoin().getTargetAssetId(), + id -> + targets + .readable(hydration.access(), Entity.TABLE, id) + .map(EntityInterface::getEntityReference)) + .orElse(null); } private static OntologyBoundColumn columnMetadata(final Column column) { @@ -421,55 +417,9 @@ private static OntologyBoundColumn columnMetadata(final Column column) { .withDataTypeDisplay(column.getDataTypeDisplay()); } - private Optional> readable( - final Access access, final String type, final UUID id) { - try { - return Optional.of(authorized(access, type, id, MetadataOperation.VIEW_BASIC)); - } catch (final AuthorizationException | EntityNotFoundException unavailable) { - LOG.debug("Binding target {} {} is unavailable to the current reader", type, id); - return Optional.empty(); - } - } - private OntologyConcept concept( final Access access, final UUID id, final MetadataOperation operation) { - return (OntologyConcept) authorized(access, Entity.ONTOLOGY_CONCEPT, id, operation); - } - - private EntityInterface authorized( - final Access access, final String type, final UUID id, final MetadataOperation operation) { - return authorized(access, repositories.apply(type), id, operation); - } - - private > T authorized( - final Access access, - final EntityRepository repository, - final UUID id, - final MetadataOperation operation) { - final T entity = - repository.get(access.uriInfo(), id, fields(repository), Include.NON_DELETED, false); - authorize(access, repository, entity, operation); - return entity; - } - - private > void authorize( - final Access access, - final EntityRepository repository, - final T entity, - final MetadataOperation operation) { - authorizer.authorize( - access.securityContext(), - new OperationContext(repository.getEntityType(), operation), - new ResourceContext<>(repository.getEntityType(), entity, repository)); - } - - private static Fields fields(final EntityRepository repository) { - final var fieldNames = - new HashSet<>(ResourceContext.authorizationFields(repository).getFieldList()); - if (Entity.TABLE.equals(repository.getEntityType())) { - fieldNames.add(Entity.FIELD_COLUMNS); - } - return new Fields(fieldNames); + return (OntologyConcept) targets.authorized(access, Entity.ONTOLOGY_CONCEPT, id, operation); } static UUID decodeCursor(final String after) { @@ -500,5 +450,14 @@ private record Hydration( Access access, OntologyConcept concept, Set ancestors, - Map> properties) {} + Map> properties, + Map> joinTargets) { + private Hydration( + final Access access, + final OntologyConcept concept, + final Set ancestors, + final Map> properties) { + this(access, concept, ancestors, properties, new HashMap<>()); + } + } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableBindingChecks.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableBindingChecks.java new file mode 100644 index 000000000000..8fad5d69d884 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableBindingChecks.java @@ -0,0 +1,132 @@ +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; + +/** + * What a table binding must satisfy before it is saved. Every check runs under the ontology lock, + * after the rows of deleted assets are gone, so it reads the state the write commits against. + */ +final class OntologyTableBindingChecks { + static final String OUTSIDE_MAPPING_SOURCE = + "Once an ontology names a mapping source, every table binding must sit in that database"; + static final String SECOND_IDENTITY_TABLE = + "A class has at most one identity table. Change the role of the current one or remove its binding first"; + static final String MISSING_KEY_COLUMN = "Every subject key column must exist in the bound table"; + static final String MISSING_FILTER_COLUMN = "A row filter column must exist in the bound table"; + static final String JOIN_OUTSIDE_DATABASE = + "A join target must be a table in the same database as the bound table"; + static final String MISSING_JOIN_COLUMN = + "Join columns must exist: each child in the bound table and each parent in the target table"; + + private final OntologyBindingAccess targets; + + /** One table binding write: the stored row it replaces, if any, and the table it binds. */ + record Write( + Access access, + OntologyConcept concept, + OntologyConceptBindingStore locked, + BindingRow existing, + OntologyAssetBinding asset, + Table table) {} + + OntologyTableBindingChecks(final OntologyBindingAccess targets) { + this.targets = targets; + } + + void check(final Write write) { + requireInsideMappingSource(write); + requireKeyColumns(write); + requireSingleIdentity(write); + requireRowFilter(write); + } + + /** A join added or changed by this write. One already stored is left as it is. */ + void checkJoin(final Write write, final OntologyColumnJoin join) { + final var target = + (Table) + targets.authorized( + write.access(), + Entity.TABLE, + join.getTargetAssetId(), + MetadataOperation.VIEW_BASIC); + if (!databaseOf(target).equals(databaseOf(write.table()))) { + throw new BadRequestException(JOIN_OUTSIDE_DATABASE); + } + final boolean resolved = + join.getOn().stream() + .allMatch( + pair -> + OntologyBindingRules.resolveColumn(write.table(), pair.getChild()) != null + && OntologyBindingRules.resolveColumn(target, pair.getParent()) != null); + if (!resolved) { + throw new BadRequestException(MISSING_JOIN_COLUMN); + } + } + + private static void requireInsideMappingSource(final Write write) { + final UUID source = write.locked().mappingSource(write.concept().getOntology().getId()); + if (source != null && !source.equals(databaseOf(write.table()))) { + throw new BadRequestException(OUTSIDE_MAPPING_SOURCE); + } + } + + private static void requireKeyColumns(final Write write) { + final List> key = listOrEmpty(write.asset().getSubjectKey()); + final boolean changed = + write.existing() == null || !key.equals(listOrEmpty(write.existing().subjectKey())); + if (changed + && key.stream() + .anyMatch(path -> OntologyBindingRules.resolveColumn(write.table(), path) == null)) { + throw new BadRequestException(MISSING_KEY_COLUMN); + } + } + + private static void requireSingleIdentity(final Write write) { + if (write.asset().getRole() != OntologyBindingRole.IDENTITY) { + return; + } + final boolean taken = + write.locked().identityRows(List.of(write.concept().getId())).stream() + .anyMatch(row -> !row.assetId().equals(write.asset().getAssetId())); + if (taken) { + throw new BadRequestException(SECOND_IDENTITY_TABLE); + } + } + + /** + * A row filter is a question about the rows of a table, so setting or changing one takes the + * right that reads those rows. Removing a filter, or sending the stored one back, asks nothing. + */ + private void requireRowFilter(final Write write) { + final var filter = write.asset().getRowFilter(); + final boolean unchanged = + write.existing() != null && Objects.equals(filter, write.existing().rowFilter()); + if (filter == null || unchanged) { + return; + } + if (OntologyBindingRules.resolveColumn(write.table(), filter.getColumn()) == null) { + throw new BadRequestException(MISSING_FILTER_COLUMN); + } + targets.require( + write.access(), Entity.TABLE, write.table(), MetadataOperation.VIEW_SAMPLE_DATA); + } + + private static UUID databaseOf(final Table table) { + return table.getDatabase().getId(); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDaoTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDaoTest.java index 6b33951d9821..efda7616d014 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDaoTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDaoTest.java @@ -1,7 +1,9 @@ package org.openmetadata.service.jdbi3; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.openmetadata.service.jdbi3.OntologyTestDatabase.migrate; +import static org.openmetadata.service.jdbi3.OntologyTestDatabase.repositoryRoot; import static org.openmetadata.service.jdbi3.OntologyTestDatabase.withDatabase; import java.util.List; @@ -9,7 +11,12 @@ import org.jdbi.v3.core.Handle; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.migration.utils.MigrationFile; class OntologyConceptBindingDaoTest { private static final UUID TRANSFER = new UUID(0xa1, 0); @@ -47,6 +54,173 @@ void firstTablesReadsTheEarliestTableRowsOfEveryConceptInOneStatement( }); } + @ParameterizedTest + @EnumSource( + value = ConnectionType.class, + names = {"MYSQL", "POSTGRES"}) + void aRowKeepsItsRoleKeyFilterAndJoinAndARowWrittenBeforeThemReadsBackUnassigned( + final ConnectionType dialect) { + withDatabase( + dialect, + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_concept_binding"); + migrate(handle, dialect); + bind(handle, CUSTOMER, 1, "table"); + final var dao = handle.attach(CollectionDAO.class).ontologyConceptBindingDAO(); + dao.upsert(stored(CUSTOMER, 2, "identity", "[[\"tenant\"],[\"id\"]]")); + dao.upsert(stored(CUSTOMER, 3, "contributing", "[[\"customer_id\"]]")); + dao.upsert(stored(TRANSFER, 4, "contributing", "[[\"customer_id\"]]")); + dao.upsert(stored(TRANSFER, 5, "identity", "[[\"id\"]]")); + + final var older = dao.find(CUSTOMER, asset(1)); + assertNull(older.role()); + assertNull(older.subjectKey()); + assertNull(older.rowFilter()); + assertEquals(List.of(), older.columns()); + + final var identity = dao.find(CUSTOMER, asset(2)); + assertEquals(OntologyBindingRole.IDENTITY, identity.role()); + assertEquals(List.of(List.of("tenant"), List.of("id")), identity.subjectKey()); + assertEquals(List.of("status"), identity.rowFilter().getColumn()); + assertEquals(OntologyRowFilterOperator.IN, identity.rowFilter().getOperator()); + assertEquals(List.of("OPEN", 7, true), identity.rowFilter().getValue()); + final var join = identity.columns().getFirst().getJoin(); + assertEquals(asset(9), join.getTargetAssetId()); + assertEquals(OntologyJoinStatus.INFERRED, join.getStatus()); + assertEquals(List.of("customer_id"), join.getOn().getFirst().getChild()); + assertEquals(List.of("id"), join.getOn().getFirst().getParent()); + + assertEquals( + List.of(TRANSFER + "/" + asset(5), CUSTOMER + "/" + asset(2)), + dao + .listIdentityRows( + List.of(CUSTOMER.toString(), TRANSFER.toString(), UNBOUND.toString())) + .stream() + .map(row -> row.conceptId() + "/" + row.assetId()) + .toList()); + }); + } + + @ParameterizedTest + @EnumSource( + value = ConnectionType.class, + names = {"MYSQL", "POSTGRES"}) + void rewritingARowReplacesItsRoleKeyAndFilterAndCanClearThem(final ConnectionType dialect) { + withDatabase( + dialect, + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_concept_binding"); + migrate(handle, dialect); + final var dao = handle.attach(CollectionDAO.class).ontologyConceptBindingDAO(); + dao.upsert(stored(CUSTOMER, 2, "identity", "[[\"id\"]]")); + + dao.upsert( + new StoredBinding( + CUSTOMER.toString(), + asset(2).toString(), + "table", + "hash2", + "[]", + null, + null, + null)); + + final var cleared = dao.find(CUSTOMER, asset(2)); + assertNull(cleared.role()); + assertNull(cleared.subjectKey()); + assertNull(cleared.rowFilter()); + assertEquals(List.of(), cleared.columns()); + assertEquals(List.of(), dao.listIdentityRows(List.of(CUSTOMER.toString()))); + }); + } + + @ParameterizedTest + @EnumSource( + value = ConnectionType.class, + names = {"MYSQL", "POSTGRES"}) + void theMigrationAddsItsColumnsToATableThatHoldsRowsAndASecondRunChangesNothing( + final ConnectionType dialect) { + withDatabase( + dialect, + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_concept_binding"); + createTableAsFirstShipped(handle, dialect); + bind(handle, CUSTOMER, 1, "table"); + assertEquals( + List.of("conceptid", "assetid", "assettype", "assetfqnhash", "columnbindings"), + columnNames(handle, dialect)); + + migrate(handle, dialect); + final var dao = handle.attach(CollectionDAO.class).ontologyConceptBindingDAO(); + dao.upsert(stored(CUSTOMER, 2, "identity", "[[\"tenant\"],[\"id\"]]")); + migrate(handle, dialect); + + assertEquals( + List.of( + "conceptid", + "assetid", + "assettype", + "assetfqnhash", + "columnbindings", + "bindingrole", + "subjectkey", + "rowfilter"), + columnNames(handle, dialect)); + final var older = dao.find(CUSTOMER, asset(1)); + assertNull(older.role()); + assertNull(older.subjectKey()); + assertNull(older.rowFilter()); + final var identity = dao.find(CUSTOMER, asset(2)); + assertEquals(OntologyBindingRole.IDENTITY, identity.role()); + assertEquals(List.of(List.of("tenant"), List.of("id")), identity.subjectKey()); + assertEquals(List.of("OPEN", 7, true), identity.rowFilter().getValue()); + assertEquals(asset(9), identity.columns().getFirst().getJoin().getTargetAssetId()); + }); + } + + /** The table as the 2.1.0 migration creates it, before 2.2.0 adds its three columns. */ + private static void createTableAsFirstShipped(final Handle handle, final ConnectionType dialect) { + final var migration = + repositoryRoot() + .resolve("bootstrap/sql/migrations/native/2.1.0") + .resolve(dialect == ConnectionType.MYSQL ? "mysql" : "postgres") + .resolve("schemaChanges.sql"); + MigrationFile.parseSQLFile(migration.toFile(), dialect).stream() + .filter( + statement -> + statement.contains("CREATE TABLE IF NOT EXISTS ontology_concept_binding (")) + .forEach(handle::execute); + } + + private static List columnNames(final Handle handle, final ConnectionType dialect) { + return handle + .createQuery( + "SELECT lower(column_name) FROM information_schema.columns" + + " WHERE table_name = 'ontology_concept_binding' AND table_schema = " + + (dialect == ConnectionType.MYSQL ? "DATABASE()" : "current_schema()") + + " ORDER BY ordinal_position") + .mapTo(String.class) + .list(); + } + + /** A table row with one relation column joined to asset 9 and a list row filter. */ + private static StoredBinding stored( + final UUID concept, final int asset, final String role, final String subjectKey) { + return new StoredBinding( + concept.toString(), + asset(asset).toString(), + "table", + "hash" + asset, + """ + [{"propertyId":"%s","columnPath":["customer_id"],"join":{"targetAssetId":"%s",\ + "status":"inferred","on":[{"child":["customer_id"],"parent":["id"]}]}}]\ + """ + .formatted(new UUID(0xb1, 0), asset(9)), + role, + subjectKey, + "{\"column\":[\"status\"],\"operator\":\"in\",\"value\":[\"OPEN\",7,true]}"); + } + private static void bind( final Handle handle, final UUID concept, final int asset, final String assetType) { handle.execute( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyTestDatabase.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyTestDatabase.java index c208ffc9fa00..910291ff72cb 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyTestDatabase.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyTestDatabase.java @@ -162,16 +162,23 @@ private static void migrateTableColumns( static void migrate(Handle handle, ConnectionType dialect) { migrateRepositoryTables(handle, dialect); + ontologyStatements(dialect, "2.1.0").stream() + .dropWhile(statement -> !statement.contains("CREATE TABLE IF NOT EXISTS ontology_entity (")) + .forEach(handle::execute); + ontologyStatements(dialect, "2.2.0").forEach(handle::execute); + } + + /** Only ontology statements: the rest of a version's file needs tables this database lacks. */ + private static List ontologyStatements(ConnectionType dialect, String version) { Path migration = repositoryRoot() - .resolve("bootstrap/sql/migrations/native/2.1.0") + .resolve("bootstrap/sql/migrations/native") + .resolve(version) .resolve(dialect == ConnectionType.MYSQL ? "mysql" : "postgres") .resolve("schemaChanges.sql"); - // Only ontology statements: the rest of the file needs tables this database lacks. - MigrationFile.parseSQLFile(migration.toFile(), dialect).stream() - .dropWhile(statement -> !statement.contains("CREATE TABLE IF NOT EXISTS ontology_entity (")) + return MigrationFile.parseSQLFile(migration.toFile(), dialect).stream() .filter(statement -> statement.toLowerCase(Locale.ROOT).contains("ontology")) - .forEach(handle::execute); + .toList(); } static Path repositoryRoot() { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingRulesTest.java index 9082e82e5c75..b23266dcf57d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingRulesTest.java @@ -10,7 +10,9 @@ import jakarta.ws.rs.ClientErrorException; import java.net.URI; +import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.IntStream; @@ -23,12 +25,34 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; class OntologyBindingRulesTest { private static final long MAX_REVISION = 9_007_199_254_740_991L; + private static final String ROLE_AND_KEY = + "A role and a subject key are set together. A binding with a role names its key columns, and a binding without a role names none"; + private static final String KEY_SIZE = "A subject key takes 1 to 16 distinct columns"; + private static final String COLUMN_PATH = + "Column paths require 1 to 32 nonblank name segments of at most 256 characters"; + private static final String TABLES_ONLY = + "Only table bindings take a role, a subject key or a row filter"; + private static final String FILTER_VALUE = + "A row filter compares with a string of at most 1024 characters, a number or a boolean. `in` takes a list of 1 to 100 of them, and `isNull` and `isNotNull` take no value"; + private static final String FILTER_SHAPE = + "A row filter requires a column and a supported operator"; + private static final String JOIN_SHAPE = + "A join requires a target table, a status and 1 to 16 distinct column pairs"; + private static final String DUPLICATE_COLUMNS = + "Duplicate property and column bindings are not allowed"; @Test void staleChangedWritesConflictAndTheRevisionAdvancesByOne() { @@ -149,6 +173,214 @@ void rejectsMalformedAndOversizedAssociations() { } } + @Test + void aRoleAndASubjectKeyAreSetTogether() { + assertDoesNotThrow(() -> OntologyBindingRules.validate(identity(key("tenant"), key("id")))); + assertDoesNotThrow( + () -> + OntologyBindingRules.validate( + asset().withRole(OntologyBindingRole.CONTRIBUTING).withSubjectKey(keys(16)))); + assertRejected(ROLE_AND_KEY, asset().withRole(OntologyBindingRole.IDENTITY)); + assertRejected( + ROLE_AND_KEY, asset().withRole(OntologyBindingRole.IDENTITY).withSubjectKey(List.of())); + assertRejected(ROLE_AND_KEY, asset().withSubjectKey(List.of(key("id")))); + assertRejected(KEY_SIZE, identity(key("id"), key("id"))); + assertRejected( + KEY_SIZE, asset().withRole(OntologyBindingRole.IDENTITY).withSubjectKey(keys(17))); + assertRejected(COLUMN_PATH, identity(key(" "))); + assertRejected(COLUMN_PATH, identity(List.of())); + } + + @Test + void onlyATableBindingTakesARoleAKeyOrAFilter() { + final var dashboard = asset().withAssetType(OntologyBindingAssetType.DASHBOARD); + assertDoesNotThrow(() -> OntologyBindingRules.validate(dashboard)); + assertRejected( + TABLES_ONLY, identity(key("id")).withAssetType(OntologyBindingAssetType.DASHBOARD)); + assertRejected( + TABLES_ONLY, + asset() + .withAssetType(OntologyBindingAssetType.TOPIC) + .withRowFilter(filter(OntologyRowFilterOperator.IS_NULL, null))); + } + + @Test + void aRowFilterTakesTheValueItsOperatorNeeds() { + for (final Object value : List.of("DELETED", "", 7, 2.5, true, "x".repeat(1024))) { + assertDoesNotThrow( + () -> OntologyBindingRules.validate(filtered(OntologyRowFilterOperator.EQUALS, value))); + } + for (final Object value : List.of("x".repeat(1025), "a\u0000b", List.of("a"), Map.of("a", 1))) { + assertRejected(FILTER_VALUE, filtered(OntologyRowFilterOperator.NOT_EQUALS, value)); + } + for (final var comparison : + List.of( + OntologyRowFilterOperator.EQUALS, + OntologyRowFilterOperator.NOT_EQUALS, + OntologyRowFilterOperator.LESS_THAN, + OntologyRowFilterOperator.LESS_THAN_OR_EQUALS, + OntologyRowFilterOperator.GREATER_THAN, + OntologyRowFilterOperator.GREATER_THAN_OR_EQUALS)) { + assertDoesNotThrow(() -> OntologyBindingRules.validate(filtered(comparison, 10))); + assertRejected(FILTER_VALUE, filtered(comparison, null)); + } + } + + @Test + void aListFilterTakesOneToAHundredValuesAndANullCheckTakesNone() { + assertDoesNotThrow( + () -> + OntologyBindingRules.validate( + filtered(OntologyRowFilterOperator.IN, List.of("EU", 44, false)))); + assertDoesNotThrow( + () -> + OntologyBindingRules.validate( + filtered(OntologyRowFilterOperator.IN, Collections.nCopies(100, "EU")))); + for (final Object value : + List.of( + "EU", + List.of(), + Collections.nCopies(101, "EU"), + List.of(List.of("EU")), + List.of("a\u0000b"))) { + assertRejected(FILTER_VALUE, filtered(OntologyRowFilterOperator.IN, value)); + } + assertRejected(FILTER_VALUE, filtered(OntologyRowFilterOperator.IN, null)); + for (final var check : + List.of(OntologyRowFilterOperator.IS_NULL, OntologyRowFilterOperator.IS_NOT_NULL)) { + assertDoesNotThrow(() -> OntologyBindingRules.validate(filtered(check, null))); + assertRejected(FILTER_VALUE, filtered(check, "x")); + } + } + + @Test + void aRowFilterNamesOneColumnAndOneOperator() { + assertRejected(FILTER_SHAPE, filtered(null, "x")); + assertRejected( + COLUMN_PATH, + asset() + .withRowFilter( + new OntologyRowFilter() + .withOperator(OntologyRowFilterOperator.IS_NULL) + .withColumn(List.of()))); + assertRejected( + COLUMN_PATH, + asset() + .withRowFilter( + new OntologyRowFilter() + .withOperator(OntologyRowFilterOperator.EQUALS) + .withColumn(List.of("status", " ")) + .withValue("x"))); + } + + @Test + void aJoinNamesItsTargetItsStatusAndItsColumnPairs() { + assertDoesNotThrow( + () -> OntologyBindingRules.validate(joined(join(pair("customer_id", "id"))))); + assertDoesNotThrow(() -> OntologyBindingRules.validate(joined(join(pairs(16))))); + assertRejected(JOIN_SHAPE, joined(join(pair("customer_id", "id")).withTargetAssetId(null))); + assertRejected(JOIN_SHAPE, joined(join(pair("customer_id", "id")).withStatus(null))); + assertRejected(JOIN_SHAPE, joined(join())); + assertRejected(JOIN_SHAPE, joined(join(pairs(17)))); + assertRejected(JOIN_SHAPE, joined(join(pair("customer_id", "id"), pair("customer_id", "id")))); + assertRejected(COLUMN_PATH, joined(join(pair("customer_id", " ")))); + assertRejected(COLUMN_PATH, joined(join(pair("", "id")))); + } + + @Test + void aRelationColumnNeedsAJoinAndADataColumnTakesNone() { + final var relation = new OntologyProperty().withKind(OntologyPropertyKind.OBJECT); + final var attribute = new OntologyProperty().withKind(OntologyPropertyKind.DATA); + final var withJoin = column().withJoin(join(pair("customer_id", "id"))); + assertDoesNotThrow(() -> OntologyBindingRules.requireJoinFor(relation, withJoin)); + assertDoesNotThrow(() -> OntologyBindingRules.requireJoinFor(attribute, column())); + assertEquals( + "A column bound to an OBJECT property requires a join to the table that holds the related records", + assertThrows( + BadRequestException.class, + () -> OntologyBindingRules.requireJoinFor(relation, column())) + .getMessage()); + assertEquals( + "Only a column bound to an OBJECT property takes a join", + assertThrows( + BadRequestException.class, + () -> OntologyBindingRules.requireJoinFor(attribute, withJoin)) + .getMessage()); + } + + @Test + void onePropertyBoundTwiceToOneColumnIsADuplicateWhateverItsJoin() { + final var plain = column(); + final var joined = + new OntologyColumnBinding() + .withPropertyId(plain.getPropertyId()) + .withColumnPath(plain.getColumnPath()) + .withJoin(join(pair("value", "id"))); + assertRejected(DUPLICATE_COLUMNS, asset().withColumns(List.of(plain, joined))); + } + + @Test + void aWriteThatRepeatsTheStoredBindingIsTheSameBinding() { + final var relation = column().withJoin(join(pair("customer_id", "id"))); + final var requested = + identity(key("tenant"), key("id")) + .withRowFilter(filter(OntologyRowFilterOperator.NOT_EQUALS, "DELETED")) + .withColumns(List.of(relation)); + final var stored = + new BindingRow( + UUID.randomUUID(), + requested.getAssetId(), + OntologyBindingAssetType.TABLE, + "hash", + List.of(relation), + OntologyBindingRole.IDENTITY, + List.of(key("tenant"), key("id")), + filter(OntologyRowFilterOperator.NOT_EQUALS, "DELETED")); + assertTrue(OntologyBindingRules.sameBinding(stored, requested)); + assertFalse( + OntologyBindingRules.sameBinding( + stored, copy(requested).withRole(OntologyBindingRole.CONTRIBUTING))); + assertFalse( + OntologyBindingRules.sameBinding( + stored, copy(requested).withSubjectKey(List.of(key("id"), key("tenant"))))); + assertFalse( + OntologyBindingRules.sameBinding( + stored, + copy(requested) + .withRowFilter(filter(OntologyRowFilterOperator.NOT_EQUALS, "ARCHIVED")))); + assertFalse(OntologyBindingRules.sameBinding(stored, copy(requested).withRowFilter(null))); + final var confirmed = + new OntologyColumnBinding() + .withPropertyId(relation.getPropertyId()) + .withColumnPath(relation.getColumnPath()) + .withJoin( + join(pair("customer_id", "id")) + .withTargetAssetId(relation.getJoin().getTargetAssetId()) + .withStatus(OntologyJoinStatus.CONFIRMED)); + assertFalse( + OntologyBindingRules.sameBinding(stored, copy(requested).withColumns(List.of(confirmed)))); + } + + @Test + void aRowWrittenBeforeRolesExistedEqualsARequestThatAssignsNothing() { + final var requested = asset(); + final var stored = + new BindingRow( + UUID.randomUUID(), + requested.getAssetId(), + OntologyBindingAssetType.TABLE, + "hash", + List.of()); + assertTrue(OntologyBindingRules.sameBinding(stored, requested)); + assertTrue(OntologyBindingRules.sameBinding(stored, copy(requested).withSubjectKey(null))); + assertFalse( + OntologyBindingRules.sameBinding( + stored, + copy(requested) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(key("id"))))); + } + @Test void revisionMustBePresentAndExactlyRepresentable() { for (final Long invalid : new Long[] {null, -1L, MAX_REVISION + 1}) { @@ -173,4 +405,68 @@ private static OntologyColumnBinding column() { private static List columns(int count) { return IntStream.range(0, count).mapToObj(index -> column()).toList(); } + + private static void assertRejected(final String message, final OntologyAssetBinding asset) { + assertEquals( + message, + assertThrows(BadRequestException.class, () -> OntologyBindingRules.validate(asset)) + .getMessage()); + } + + @SafeVarargs + private static OntologyAssetBinding identity(final List... key) { + return asset().withRole(OntologyBindingRole.IDENTITY).withSubjectKey(List.of(key)); + } + + private static List key(final String column) { + return List.of(column); + } + + private static List> keys(final int count) { + return IntStream.range(0, count).mapToObj(index -> key("k" + index)).toList(); + } + + private static OntologyRowFilter filter( + final OntologyRowFilterOperator operator, final Object value) { + return new OntologyRowFilter() + .withColumn(List.of("status")) + .withOperator(operator) + .withValue(value); + } + + private static OntologyAssetBinding filtered( + final OntologyRowFilterOperator operator, final Object value) { + return asset().withRowFilter(filter(operator, value)); + } + + private static OntologyAssetBinding joined(final OntologyColumnJoin join) { + return asset().withColumns(List.of(column().withJoin(join))); + } + + private static OntologyColumnJoin join(final OntologyJoinColumnPair... pairs) { + return new OntologyColumnJoin() + .withTargetAssetId(UUID.randomUUID()) + .withStatus(OntologyJoinStatus.INFERRED) + .withOn(List.of(pairs)); + } + + private static OntologyJoinColumnPair pair(final String child, final String parent) { + return new OntologyJoinColumnPair().withChild(List.of(child)).withParent(List.of(parent)); + } + + private static OntologyJoinColumnPair[] pairs(final int count) { + return IntStream.range(0, count) + .mapToObj(index -> pair("c" + index, "p" + index)) + .toArray(OntologyJoinColumnPair[]::new); + } + + private static OntologyAssetBinding copy(final OntologyAssetBinding asset) { + return new OntologyAssetBinding() + .withAssetId(asset.getAssetId()) + .withAssetType(asset.getAssetType()) + .withColumns(asset.getColumns()) + .withRole(asset.getRole()) + .withSubjectKey(asset.getSubjectKey()) + .withRowFilter(asset.getRowFilter()); + } } From 643a723291515127ec1a79a195a4864ff2170856 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 21 Nov 2026 22:19:43 -0800 Subject: [PATCH 014/203] Let an ontology name one database as its mapping source mappingSource is a reference to one database entity, stored as a MAPPED_TO relationship row and returned for fields=mappingSource, which a reader with ViewBasic on the ontology may ask for. A create request can name it, a PATCH sets, changes or removes it, and a PUT that names none keeps the stored one. A deleted database is refused only where the mapping source is set or changed. A change records no new version of the ontology. A release digest hashes the version of every member, so a versioned change would alter the digest of the next capture although the mapping source is not release content. --- .../service/jdbi3/OntologyRepository.java | 105 +++++++++++++++++- .../resources/ontology/OntologyMapper.java | 1 + .../resources/ontology/OntologyResource.java | 4 +- .../ontology/OntologyReleaseManifestTest.java | 23 ++++ 4 files changed, 131 insertions(+), 2 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java index a1dcaaf1502b..408e3213430a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java @@ -45,6 +45,7 @@ public class OntologyRepository extends OntologyEntityRepository { private static final String ARCHIVED_REVIEW_COMMENT = "Closed because the ontology was archived"; private static final String PUBLICATION_STATUS = "publicationStatus"; + private static final String MAPPING_SOURCE = "mappingSource"; private final OntologyPublicationStatusResolver publication; public OntologyRepository() { @@ -55,6 +56,9 @@ public OntologyRepository() { COLLECTION_PATH, "iri,namespace,layer,prefixes,approvalRule"); fieldFetchers.put(PUBLICATION_STATUS, this::fetchPublicationStatus); + fieldFetchers.put(MAPPING_SOURCE, this::fetchMappingSources); + getPatchFields().addField(allowedFields, MAPPING_SOURCE); + putFields.addField(allowedFields, MAPPING_SOURCE); publication = new OntologyPublicationStatusResolver(Entity.getCollectionDAO()); } @@ -62,6 +66,7 @@ public OntologyRepository() { public void setFields( final Ontology entity, final Fields fields, final RelationIncludes includes) { fetchPublicationStatus(List.of(entity), fields); + fetchMappingSources(List.of(entity), fields); } @Override @@ -69,6 +74,9 @@ public void clearFields(final Ontology entity, final Fields fields) { if (!fields.contains(PUBLICATION_STATUS)) { entity.setPublicationStatus(null); } + if (!fields.contains(MAPPING_SOURCE)) { + entity.setMappingSource(null); + } } @Override @@ -85,9 +93,10 @@ protected void validatePatch( } } + /** The mapping source is a relationship row, so a renamed or deleted database is never stale. */ @Override protected List getFieldsStrippedFromStorageJson() { - return List.of(PUBLICATION_STATUS); + return List.of(PUBLICATION_STATUS, MAPPING_SOURCE); } @Override @@ -102,6 +111,67 @@ private void fetchPublicationStatus(final List ontologies, final Field } } + private void fetchMappingSources(final List ontologies, final Fields fields) { + if (fields.contains(MAPPING_SOURCE)) { + ontologies.forEach( + ontology -> + ontology.setMappingSource( + getToEntityRef( + ontology.getId(), + OntologyConceptBindingStore.MAPPING_SOURCE_RELATION, + Entity.DATABASE, + false))); + } + } + + /** + * The mapping source names one database. Bindings written before it was set are never checked + * here. The mapping health read lists the ones that sit elsewhere. A deleted database is refused + * only where the mapping source is set, so it never blocks another edit of the ontology. + */ + private static void resolveMappingSource(final Ontology entity) { + final EntityReference source = entity.getMappingSource(); + if (source == null) { + return; + } + if (!Entity.DATABASE.equals(source.getType())) { + throw new BadRequestException("An ontology's mapping source must be a database"); + } + entity.setMappingSource( + Entity.getEntityReferenceById(Entity.DATABASE, source.getId(), Include.ALL)); + } + + private static void requireLiveMappingSource(final EntityReference source) { + if (source != null && Boolean.TRUE.equals(source.getDeleted())) { + throw new BadRequestException("An ontology's mapping source must not be a deleted database"); + } + } + + private static UUID mappingSourceId(final Ontology ontology) { + return ontology.getMappingSource() == null ? null : ontology.getMappingSource().getId(); + } + + @Override + public void prepare(final Ontology entity, final boolean update) { + super.prepare(entity, update); + if (!update) { + requireLiveMappingSource(entity.getMappingSource()); + } + } + + @Override + public void storeRelationships(final Ontology entity) { + super.storeRelationships(entity); + if (entity.getMappingSource() != null) { + addRelationship( + entity.getId(), + entity.getMappingSource().getId(), + Entity.ONTOLOGY, + Entity.DATABASE, + OntologyConceptBindingStore.MAPPING_SOURCE_RELATION); + } + } + @Override protected OntologyUpdater newUpdater( final Ontology original, @@ -211,6 +281,38 @@ protected void entitySpecificUpdate(final boolean consolidatingChanges) { requireNoOpenReview(original.getId()); } super.entitySpecificUpdate(consolidatingChanges); + compareAndUpdate(MAPPING_SOURCE, this::updateMappingSource); + } + + /** + * The mapping source is operational metadata. A change writes its relationship row and records + * no field change, so the ontology keeps its version and a release digest, which binds that + * version, stays the same. A PUT that names no mapping source keeps the stored one, so a client + * that does not know the field cannot clear it. A PATCH removes it. The change runs under the + * ontology state lock that a binding write holds while it reads the mapping source. + */ + private void updateMappingSource() { + if (operation.isPut() && updated.getMappingSource() == null) { + updated.setMappingSource(original.getMappingSource()); + return; + } + final UUID requested = mappingSourceId(updated); + if (!Objects.equals(storedMappingSource(), requested)) { + requireLiveMappingSource(updated.getMappingSource()); + replaceMappingSource(requested); + } + } + + private void replaceMappingSource(final UUID requested) { + final Relationship relation = OntologyConceptBindingStore.MAPPING_SOURCE_RELATION; + deleteFrom(original.getId(), Entity.ONTOLOGY, relation, Entity.DATABASE); + if (requested != null) { + addRelationship(original.getId(), requested, Entity.ONTOLOGY, Entity.DATABASE, relation); + } + } + + private UUID storedMappingSource() { + return OntologyConceptBindingStore.mappingSource(daoCollection, original.getId()); } } @@ -219,6 +321,7 @@ protected void validateDefinition(final Ontology entity) { entity.setPublicationStatus(null); requireAbsoluteIri(entity.getNamespace(), "namespace"); OntologyLayerValidator.validatePrefixes(entity.getPrefixes()); + resolveMappingSource(entity); } @Override diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyMapper.java index f5a6fb262e4e..f5dad6f007fe 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyMapper.java @@ -13,6 +13,7 @@ public Ontology createToEntity(final CreateOntology request, final String user) .withLayer(request.getLayer()) .withPrefixes(request.getPrefixes()) .withApprovalRule(request.getApprovalRule()) + .withMappingSource(request.getMappingSource()) .withProvider(request.getProvider()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java index 4acc3dd52a85..de0fe9162337 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java @@ -134,6 +134,8 @@ @Collection(name = "ontologies", order = 3) public class OntologyResource extends EntityResource { public static final String COLLECTION_PATH = "/v1/ontologies/"; + private static final String MAPPING_SOURCE = "mappingSource"; + private static final String VIEW_BASIC_FIELDS = "publicationStatus," + MAPPING_SOURCE; private final OntologyMapper mapper = new OntologyMapper(); private final OntologyReleaseCapture releaseCapture; private final OntologyReleaseActivation releaseActivation; @@ -161,7 +163,7 @@ public class OntologyResource extends EntityResource Date: Sat, 21 Nov 2026 22:19:58 -0800 Subject: [PATCH 015/203] Report what the table bindings of an ontology still need GET /v1/ontologies/{id}/mappingHealth pages the table bindings of an ontology's classes and lists what an editor has to fix: a class with no identity table, a binding with no role, a relation column with no join, a join that is not confirmed, a key or a join whose columns do not pair, and tables outside the mapping source or spread over several databases. The read uses catalog metadata only and never queries a bound table. It names only the classes, tables and properties the caller may view. The generated API reference lists the endpoint. --- docs/generated/api-reference.md | 3 +- .../ontology/OntologyMappingHealthRules.java | 272 +++++++++++ .../OntologyMappingHealthService.java | 232 ++++++++++ .../resources/ontology/OntologyResource.java | 25 + .../OntologyMappingHealthRulesTest.java | 429 ++++++++++++++++++ 5 files changed, 960 insertions(+), 1 deletion(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingHealthRulesTest.java diff --git a/docs/generated/api-reference.md b/docs/generated/api-reference.md index 5a3be5f6faae..f6af72689f8d 100644 --- a/docs/generated/api-reference.md +++ b/docs/generated/api-reference.md @@ -13,7 +13,7 @@ hand-edit; run `make generate-api-reference` (or `make generate-reference-docs`) - Source is the annotations, **not** `openapi.yml` (a config stub with no endpoints; the full spec is assembled at runtime by Dropwizard). -**2013 endpoints** across 75 resource packages · 2003 carry a summary. +**2014 endpoints** across 75 resource packages · 2004 carry a summary. ## (root) @@ -1378,6 +1378,7 @@ hand-edit; run `make generate-api-reference` (or `make generate-reference-docs`) | `POST` | `/v1/ontologies/{id}/library/{packId}/preview` | Preview verified library modules as native ontology draft operations | | `POST` | `/v1/ontologies/{id}/library/{packId}/review` | Review verified library modules item by item before they install | | `POST` | `/v1/ontologies/{id}/library/{packId}/summary` | Review verified library modules without returning draft operations | +| `GET` | `/v1/ontologies/{id}/mappingHealth` | List what the table bindings of an ontology's classes still need before their rows can be read as records, from catalog metadata alone | | `GET` | `/v1/ontologies/{id}/references` | Find working definitions that reference an exact IRI in this ontology | | `GET` | `/v1/ontologies/{id}/releases` | List this ontology's sealed releases, newest first | | `POST` | `/v1/ontologies/{id}/releases` | Capture immutable ontology release content | diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java new file mode 100644 index 000000000000..e67db9ace572 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java @@ -0,0 +1,272 @@ +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.IntStream; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntryType; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; + +/** + * What the table bindings of an ontology still need before their rows can be read as records. The + * rules read the catalog metadata handed to them and nothing else, so they never reach a bound + * table, and every table, class and property they are handed is one the caller may view. + */ +public final class OntologyMappingHealthRules { + /** Types that compare and join with each other. A type in no group pairs only with itself. */ + private static final List> FAMILIES = + List.of( + EnumSet.of( + ColumnDataType.NUMBER, + ColumnDataType.TINYINT, + ColumnDataType.SMALLINT, + ColumnDataType.INT, + ColumnDataType.BIGINT, + ColumnDataType.BYTEINT, + ColumnDataType.LONG, + ColumnDataType.LARGEINT, + ColumnDataType.UINT, + ColumnDataType.FLOAT, + ColumnDataType.DOUBLE, + ColumnDataType.DECIMAL, + ColumnDataType.NUMERIC, + ColumnDataType.MONEY), + EnumSet.of( + ColumnDataType.STRING, + ColumnDataType.CHAR, + ColumnDataType.VARCHAR, + ColumnDataType.TEXT, + ColumnDataType.MEDIUMTEXT, + ColumnDataType.NTEXT, + ColumnDataType.CLOB), + EnumSet.of(ColumnDataType.TIMESTAMP, ColumnDataType.TIMESTAMPZ, ColumnDataType.DATETIME), + EnumSet.of( + ColumnDataType.BINARY, + ColumnDataType.VARBINARY, + ColumnDataType.BYTES, + ColumnDataType.BYTEA, + ColumnDataType.BLOB, + ColumnDataType.MEDIUMBLOB, + ColumnDataType.LONGBLOB)); + + private OntologyMappingHealthRules() {} + + /** One table binding of a class, with the class and the table as the caller may read them. */ + public record BoundTable(BindingRow row, EntityReference concept, Table table) {} + + /** The identity binding of a class. {@code table} is null when the caller may not view it. */ + public record Identity(BindingRow row, Table table) {} + + /** The catalog state a page of bound tables is checked against. */ + public record Context( + EntityReference mappingSource, + Map identities, + Map properties, + Map joinTargets) {} + + /** + * What the pages before this one settled: the classes already checked for an identity table, + * and one table for each database the bound tables were found in. + */ + public record Progress(Set settledConcepts, List databaseWitnesses) { + public static Progress start() { + return new Progress(Set.of(), List.of()); + } + } + + public record Page(List entries, Progress progress) {} + + /** The findings for {@code tables}, in the order given, and the progress the next page takes. */ + public static Page check( + final List tables, final Context context, final Progress earlier) { + final List entries = new ArrayList<>(); + final Set settled = new HashSet<>(earlier.settledConcepts()); + for (final BoundTable bound : tables) { + final UUID conceptId = bound.row().conceptId(); + if (settled.add(conceptId) && !context.identities().containsKey(conceptId)) { + entries.add( + entry(OntologyMappingHealthEntryType.NO_IDENTITY_TABLE).withConcept(bound.concept())); + } + entries.addAll(tableEntries(bound, context)); + } + final List
witnesses = databaseWitnesses(tables, earlier.databaseWitnesses()); + if (spansDatabases(context, witnesses, earlier.databaseWitnesses())) { + entries.add( + entry(OntologyMappingHealthEntryType.MULTIPLE_DATABASES) + .withDatabases(witnesses.stream().map(Table::getDatabase).toList())); + } + return new Page(entries, new Progress(settled, witnesses)); + } + + /** Reported on each page that finds a database no earlier page found, once two are known. */ + private static boolean spansDatabases( + final Context context, final List
witnesses, final List
earlier) { + return context.mappingSource() == null + && witnesses.size() > 1 + && witnesses.size() > earlier.size(); + } + + private static List
databaseWitnesses( + final List tables, final List
earlier) { + final Map byDatabase = new LinkedHashMap<>(); + earlier.forEach(table -> byDatabase.putIfAbsent(table.getDatabase().getId(), table)); + tables.forEach( + bound -> byDatabase.putIfAbsent(bound.table().getDatabase().getId(), bound.table())); + return List.copyOf(byDatabase.values()); + } + + private static List tableEntries( + final BoundTable bound, final Context context) { + final List entries = new ArrayList<>(); + if (bound.row().role() == null) { + entries.add(entry(OntologyMappingHealthEntryType.UNASSIGNED_BINDING, bound)); + } + final EntityReference source = context.mappingSource(); + if (source != null && !source.getId().equals(bound.table().getDatabase().getId())) { + entries.add( + entry(OntologyMappingHealthEntryType.OUTSIDE_MAPPING_SOURCE, bound) + .withDatabases(List.of(bound.table().getDatabase()))); + } + entries.addAll(keyEntries(bound, context.identities().get(bound.row().conceptId()))); + listOrEmpty(bound.row().columns()) + .forEach(column -> entries.addAll(columnEntries(bound, column, context))); + return entries; + } + + /** A contributing table's key pairs with the identity table's key column by column. */ + private static List keyEntries( + final BoundTable bound, final Identity identity) { + if (bound.row().role() != OntologyBindingRole.CONTRIBUTING + || identity == null + || identity.table() == null) { + return List.of(); + } + final List> own = listOrEmpty(bound.row().subjectKey()); + final List> other = listOrEmpty(identity.row().subjectKey()); + if (own.size() != other.size()) { + return List.of( + entry(OntologyMappingHealthEntryType.KEY_LENGTH_MISMATCH, bound) + .withRelatedAsset(identity.table().getEntityReference()) + .withKeyLength(own.size()) + .withRelatedKeyLength(other.size())); + } + return IntStream.range(0, own.size()) + .mapToObj(i -> ColumnPair.of(bound.table(), own.get(i), identity.table(), other.get(i))) + .filter(ColumnPair::mismatched) + .map(pair -> pair.entry(OntologyMappingHealthEntryType.KEY_TYPE_MISMATCH, bound)) + .toList(); + } + + private static List columnEntries( + final BoundTable bound, final OntologyColumnBinding column, final Context context) { + final OntologyProperty property = context.properties().get(column.getPropertyId()); + final EntityReference propertyRef = property == null ? null : property.getEntityReference(); + if (column.getJoin() == null) { + return property != null && property.getKind() == OntologyPropertyKind.OBJECT + ? List.of( + entry(OntologyMappingHealthEntryType.RELATION_COLUMN_WITHOUT_JOIN, bound) + .withProperty(propertyRef) + .withColumnPath(column.getColumnPath())) + : List.of(); + } + final List entries = new ArrayList<>(); + final Table target = context.joinTargets().get(column.getJoin().getTargetAssetId()); + if (column.getJoin().getStatus() != OntologyJoinStatus.CONFIRMED) { + entries.add( + entry(OntologyMappingHealthEntryType.JOIN_NOT_CONFIRMED, bound) + .withRelatedAsset(target == null ? null : target.getEntityReference()) + .withProperty(propertyRef) + .withColumnPath(column.getColumnPath())); + } + entries.addAll(joinTypeEntries(bound, column, target, propertyRef)); + return entries; + } + + private static List joinTypeEntries( + final BoundTable bound, + final OntologyColumnBinding column, + final Table target, + final EntityReference property) { + if (target == null) { + return List.of(); + } + return listOrEmpty(column.getJoin().getOn()).stream() + .map(pair -> ColumnPair.of(bound.table(), pair.getChild(), target, pair.getParent())) + .filter(ColumnPair::mismatched) + .map( + pair -> + pair.entry(OntologyMappingHealthEntryType.JOIN_TYPE_MISMATCH, bound) + .withProperty(property)) + .toList(); + } + + /** + * Two columns that must hold the same kind of data: a key column and the identity table's key + * column at the same position, or the two sides of a join pair. A column that no longer exists + * is no type finding. + */ + private record ColumnPair( + List path, Column column, EntityReference relatedTable, RelatedColumn related) { + private record RelatedColumn(List path, Column column) {} + + private static ColumnPair of( + final Table table, + final List path, + final Table relatedTable, + final List relatedPath) { + return new ColumnPair( + path, + OntologyBindingRules.resolveColumn(table, path), + relatedTable.getEntityReference(), + new RelatedColumn( + relatedPath, OntologyBindingRules.resolveColumn(relatedTable, relatedPath))); + } + + private boolean mismatched() { + return column != null + && related.column() != null + && !sameFamily(column.getDataType(), related.column().getDataType()); + } + + private OntologyMappingHealthEntry entry( + final OntologyMappingHealthEntryType type, final BoundTable bound) { + return OntologyMappingHealthRules.entry(type, bound) + .withRelatedAsset(relatedTable) + .withColumnPath(path) + .withRelatedColumnPath(related.path()) + .withDataType(column.getDataType()) + .withRelatedDataType(related.column().getDataType()); + } + } + + static boolean sameFamily(final ColumnDataType left, final ColumnDataType right) { + return left == right + || FAMILIES.stream().anyMatch(family -> family.contains(left) && family.contains(right)); + } + + private static OntologyMappingHealthEntry entry(final OntologyMappingHealthEntryType type) { + return new OntologyMappingHealthEntry().withType(type); + } + + private static OntologyMappingHealthEntry entry( + final OntologyMappingHealthEntryType type, final BoundTable bound) { + return entry(type).withConcept(bound.concept()).withAsset(bound.table().getEntityReference()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java new file mode 100644 index 000000000000..d3ab4226bfb5 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java @@ -0,0 +1,232 @@ +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.data.OntologyMappingHealth; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingPosition; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.BoundTable; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Context; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Identity; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Progress; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.util.FreshReadScope; +import org.openmetadata.service.util.RestUtil; + +/** + * Reads one page of an ontology's table bindings with the catalog metadata the mapping health + * rules need. It loads tables, classes and properties through their repositories under the + * caller's policies and never opens a connection to a bound table. + */ +public final class OntologyMappingHealthService { + public static final int MAX_PAGE_SIZE = 100; + + /** The cursor remembers this many databases. A wider span is reported again on later pages. */ + static final int MAX_CURSOR_DATABASES = 8; + + private static final int MAX_CURSOR_LENGTH = 1024; + private static final String INVALID_CURSOR = "Invalid ontology mapping health cursor"; + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess targets; + + public OntologyMappingHealthService( + final OntologyConceptBindingStore store, + final Authorizer authorizer, + final Function> repositories) { + this.store = store; + this.targets = new OntologyBindingAccess(authorizer, repositories); + } + + /** {@code ontology} is one the caller may view, read with its mapping source. */ + public OntologyMappingHealth page( + final Access access, final Ontology ontology, final String after, final int limit) { + final Cursor cursor = Cursor.decode(after); + try (final var ignored = FreshReadScope.enter()) { + final List scanned = + store.tableRows(ontology.getId(), cursor.position(), limit + 1); + final List rows = scanned.subList(0, Math.min(limit, scanned.size())); + final List tables = boundTables(access, rows); + final var page = + OntologyMappingHealthRules.check( + tables, context(access, ontology, tables), progress(access, cursor)); + return new OntologyMappingHealth() + .withMappingSource(ontology.getMappingSource()) + .withEntries(page.entries()) + .withAfter(scanned.size() > limit ? Cursor.next(rows.getLast(), page.progress()) : null); + } + } + + /** The rows whose table and class are both live and viewable. Every other row says nothing. */ + private List boundTables(final Access access, final List rows) { + final Map tables = viewableTables(access, rows); + final var concepts = + targets.viewable( + access, + Entity.ONTOLOGY_CONCEPT, + rows.stream() + .filter(row -> tables.containsKey(row.assetId())) + .map(BindingRow::conceptId) + .toList()); + return rows.stream() + .filter(row -> tables.containsKey(row.assetId()) && concepts.containsKey(row.conceptId())) + .map( + row -> + new BoundTable( + row, + concepts.get(row.conceptId()).getEntityReference(), + tables.get(row.assetId()))) + .toList(); + } + + private Context context( + final Access access, final Ontology ontology, final List tables) { + final List columns = + tables.stream().flatMap(bound -> listOrEmpty(bound.row().columns()).stream()).toList(); + return new Context( + ontology.getMappingSource(), + identities(access, tables), + typed( + targets.viewable( + access, + Entity.ONTOLOGY_PROPERTY, + columns.stream().map(OntologyColumnBinding::getPropertyId).toList()), + OntologyProperty.class), + typed( + targets.viewable( + access, + Entity.TABLE, + columns.stream() + .map(OntologyColumnBinding::getJoin) + .filter(Objects::nonNull) + .map(join -> join.getTargetAssetId()) + .toList()), + Table.class)); + } + + /** + * A class has an identity table when a live one is stored, whether or not the caller may view + * it, so a hidden identity table never reads as a missing one. + */ + private Map identities(final Access access, final List tables) { + final List rows = + store.identityRows(tables.stream().map(bound -> bound.row().conceptId()).toList()); + final Set live = store.liveAssets(rows).keySet(); + final Map viewable = viewableTables(access, rows); + final Map identities = new HashMap<>(); + rows.stream() + .filter(row -> live.contains(row.assetId())) + .forEach( + row -> + identities.putIfAbsent( + row.conceptId(), new Identity(row, viewable.get(row.assetId())))); + return identities; + } + + private Map viewableTables(final Access access, final List rows) { + final Set live = store.liveAssets(rows).keySet(); + return typed( + targets.viewable( + access, + Entity.TABLE, + rows.stream().map(BindingRow::assetId).filter(live::contains).toList()), + Table.class); + } + + /** + * The cursor names one table for each database found so far. Each is read again under the + * caller's policies, so a cursor can only name what its holder may already view. + */ + private Progress progress(final Access access, final Cursor cursor) { + final Map witnesses = + typed(targets.viewable(access, Entity.TABLE, cursor.databaseWitnesses()), Table.class); + return new Progress( + cursor.settled() ? Set.of(cursor.position().conceptId()) : Set.of(), + cursor.databaseWitnesses().stream().map(witnesses::get).filter(Objects::nonNull).toList()); + } + + private static Map typed( + final Map> entities, final Class type) { + final Map typed = new HashMap<>(); + entities.forEach((id, entity) -> typed.put(id, type.cast(entity))); + return typed; + } + + /** + * Where the next page starts and what the pages before it settled: whether the class at the + * position was already checked for an identity table, and one table per database found. + */ + record Cursor(BindingPosition position, boolean settled, List databaseWitnesses) { + private static final Cursor START = new Cursor(null, false, List.of()); + private static final String SEPARATOR = "|"; + private static final String LIST_SEPARATOR = ","; + private static final String SETTLED = "1"; + private static final String UNSETTLED = "0"; + private static final int PARTS = 4; + + static String next(final BindingRow last, final Progress progress) { + final String witnesses = + String.join( + LIST_SEPARATOR, + progress.databaseWitnesses().stream() + .limit(MAX_CURSOR_DATABASES) + .map(table -> table.getId().toString()) + .toList()); + return RestUtil.encodeCursor( + String.join( + SEPARATOR, + last.conceptId().toString(), + last.assetId().toString(), + progress.settledConcepts().contains(last.conceptId()) ? SETTLED : UNSETTLED, + witnesses)); + } + + static Cursor decode(final String after) { + if (after == null || after.isEmpty()) { + return START; + } + if (after.length() > MAX_CURSOR_LENGTH) { + throw new BadRequestException(INVALID_CURSOR); + } + try { + return parse(RestUtil.decodeCursor(after).split("\\" + SEPARATOR, -1)); + } catch (final IllegalArgumentException invalid) { + throw new BadRequestException(INVALID_CURSOR, invalid); + } + } + + private static Cursor parse(final String[] parts) { + if (parts.length != PARTS || !Set.of(SETTLED, UNSETTLED).contains(parts[2])) { + throw new IllegalArgumentException(INVALID_CURSOR); + } + final List witnesses = + parts[3].isEmpty() + ? List.of() + : Arrays.stream(parts[3].split(LIST_SEPARATOR, -1)).map(UUID::fromString).toList(); + if (witnesses.size() > MAX_CURSOR_DATABASES) { + throw new IllegalArgumentException(INVALID_CURSOR); + } + return new Cursor( + new BindingPosition(UUID.fromString(parts[0]), UUID.fromString(parts[1])), + SETTLED.equals(parts[2]), + witnesses); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java index de0fe9162337..736891b56edb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java @@ -62,6 +62,7 @@ import org.openmetadata.schema.api.data.NativeOntologyImportFormat; import org.openmetadata.schema.api.data.NativeOntologyImportPreview; import org.openmetadata.schema.api.data.NativeOntologyImportSummary; +import org.openmetadata.schema.api.data.OntologyMappingHealth; import org.openmetadata.schema.api.data.OntologyPackInstallJob; import org.openmetadata.schema.api.data.OntologyProfileReport; import org.openmetadata.schema.api.data.OntologyReleaseExportOptions; @@ -98,6 +99,7 @@ import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.ontology.OntologyDraftQuery; import org.openmetadata.service.ontology.OntologyFormatDetector; +import org.openmetadata.service.ontology.OntologyMappingHealthService; import org.openmetadata.service.ontology.OntologyPackCatalog; import org.openmetadata.service.ontology.OntologyPackContentLoader; import org.openmetadata.service.ontology.OntologyPackInstallJobManager; @@ -160,6 +162,8 @@ public class OntologyResource extends EntityResource
tables = - IntStream.range(0, 12) + IntStream.range(0, 3) .mapToObj(index -> table(payments, "transfers_" + index, List.of("amount_" + index))) .sorted(Comparator.comparing(table -> table.getId().toString())) .toList(); - final Table twelfth = tables.getLast(); - try (var fixtures = new RdfAccessFixtures("conceptQuery12" + ns.shortPrefix())) { + final Table identity = tables.getLast(); + final String column = identity.getColumns().getFirst().getName(); + for (final Table other : tables.subList(0, 2)) { + bindData( + payments.transfer(), other, payments.ontology(), other.getColumns().getFirst().getName()); + } + bindIdentity(payments.transfer(), identity, payments.ontology(), column); + try (var fixtures = new RdfAccessFixtures("conceptQueryRoot" + ns.shortPrefix())) { final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); - final var current = admin().tables().get(twelfth.getId().toString(), "owners"); - admin() - .tables() - .update(twelfth.getId().toString(), current.withOwners(List.of(readerReference(reader)))); - for (final Table table : tables) { - bindData( - payments.transfer(), - table, - payments.ontology(), - table.getColumns().getFirst().getName()); - } + own(tables.getFirst(), reader); - final OntologyConceptQuery visible = query(reader, payments.transfer()); + assertRefused(403, HIDDEN_IDENTITY_TABLE, () -> query(reader, payments.transfer())); + own(identity, reader); + final OntologyConceptQuery asReader = query(reader, payments.transfer()); + final OntologyConceptQuery asAdmin = query(admin(), payments.transfer()); assertEquals( "SELECT " - + twelfth.getColumns().getFirst().getName() + + column + "\nFROM " + payments.schema().getName() + "." - + twelfth.getName() + + identity.getName() + "\nLIMIT 50", + asReader.getSql()); + assertEquals(asReader.getSql(), asAdmin.getSql()); + assertEquals(List.of(identity.getFullyQualifiedName()), asReader.getTables()); + assertEquals(List.of(identity.getFullyQualifiedName()), asAdmin.getTables()); + } + } + + @Test + void aReaderWhoMayViewOnlyTheTwelfthTableOfAHopTargetGetsSqlOverIt(final TestNamespace ns) { + final Payments payments = + payments(ns, "twelfthPayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table customers = table(payments, "customers", List.of("customer_id")); + final List
tables = + IntStream.range(0, 12) + .mapToObj( + index -> + table( + payments, + "transfers_" + index, + List.of("amount_" + index, "customer_id"), + foreignKey("customer_id", customers, "customer_id"))) + .sorted(Comparator.comparing(table -> table.getId().toString())) + .toList(); + final Table twelfth = tables.getLast(); + bindIdentity(payments.customer(), customers, payments.ontology(), "customer_id"); + for (final Table table : tables) { + bindData( + payments.transfer(), table, payments.ontology(), table.getColumns().getFirst().getName()); + } + try (var fixtures = new RdfAccessFixtures("conceptQuery12" + ns.shortPrefix())) { + final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); + own(customers, reader); + own(twelfth, reader); + final OntologyConceptQueryHop toTransfers = + hop(payments.partOf(), INCOMING, payments.transfer()); + + final OntologyConceptQuery visible = query(reader, payments.customer(), toTransfers); + + assertEquals( + String.join( + "\n", + "SELECT t1." + twelfth.getColumns().getFirst().getName(), + "FROM " + payments.schema().getName() + ".customers t0", + "JOIN " + + payments.schema().getName() + + "." + + twelfth.getName() + + " t1 ON t0.customer_id = t1.customer_id", + "LIMIT 50"), visible.getSql()); - assertEquals(List.of(twelfth.getFullyQualifiedName()), visible.getTables()); assertEquals( - tables.getFirst().getFullyQualifiedName(), - query(admin(), payments.transfer()).getTables().getFirst()); + List.of(customers.getFullyQualifiedName(), twelfth.getFullyQualifiedName()), + visible.getTables()); + assertEquals( + List.of(customers.getFullyQualifiedName(), tables.getFirst().getFullyQualifiedName()), + query(admin(), payments.customer(), toTransfers).getTables()); } } @@ -295,7 +346,7 @@ void anInverseTheReaderMayViewAsItsOwnerLabelsAnIncomingHop(final TestNamespace "accounts", List.of("account_id", "customer_id"), foreignKey("customer_id", customers, "customer_id")); - bindData(payments.account(), accounts, payments.ontology(), "account_id"); + bindIdentity(payments.account(), accounts, payments.ontology(), "account_id"); bindData(payments.customer(), customers, payments.ontology(), "name"); try (var fixtures = new RdfAccessFixtures("conceptQueryInverse" + ns.shortPrefix())) { final OpenMetadataClient reader = ownerOnlyPropertyReader(fixtures); @@ -395,10 +446,11 @@ private SelfKey selfKeyEmployees(final TestNamespace ns, final String name) { dataProperty(payments.ontology(), "employeeId", employee, true); bind( employee, - employees, - List.of( - column(employeeId, "employee_id"), - relation(managedBy, "manager_id", employees, "employee_id")), + binding(employees, OntologyBindingRole.IDENTITY, "employee_id") + .withColumns( + List.of( + column(employeeId, "employee_id"), + relation(managedBy, "manager_id", employees, "employee_id"))), 0L); return new SelfKey(employee, managedBy, manages, payments.schema().getName()); } @@ -425,14 +477,10 @@ void theSqlKeepsOnlyTheRowsThatTheRowFilterOfATableKeeps(final TestNamespace ns) final OntologyConceptQuery filtered = query(admin(), payments.transfer()); - assertEquals( - String.join( - "\n", - "SELECT transfer_id", - "FROM " + payments.schema().getName() + ".transfers", - "WHERE status <> E'a''b\\\\c\\:d'", - "LIMIT 50"), - filtered.getSql()); + final String selected = + "SELECT transfer_id\nFROM " + payments.schema().getName() + ".transfers\n"; + assertEquals(selected + "WHERE status <> E'a''b\\\\c:d'\nLIMIT 50", filtered.getSql()); + assertEquals(selected + "WHERE status <> E'a''b\\\\c\\:d'\nLIMIT 50", filtered.getEscapedSql()); } @Test @@ -474,7 +522,7 @@ private static void bindFiltered( put( admin(), payments.transfer(), - binding(transfers) + binding(transfers, OntologyBindingRole.IDENTITY, "transfer_id") .withColumns(List.of(column(transferId, "transfer_id"))) .withRowFilter(filter(column, operator, value)), 0L); @@ -491,7 +539,7 @@ void generatingSqlWritesNothing(final TestNamespace ns) { "transfers", List.of("transfer_id", "customer_id"), foreignKey("customer_id", customers, "customer_id")); - bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + bindIdentity(payments.transfer(), transfers, payments.ontology(), "transfer_id"); bindData(payments.customer(), customers, payments.ontology(), "customer_id"); final List before = observedState(payments, transfers); @@ -584,20 +632,47 @@ private static void bindData( bind( concept, table, - List.of(columns).stream() - .map( - name -> - column( - dataProperty( - ontology, - "p" + UUID.randomUUID().toString().substring(0, 8), - concept, - false), - name)) - .toList(), + dataColumns(concept, ontology, columns), bindings(concept, "").getRevision()); } + /** Binds the table as the identity table of the concept, keyed by the first of the columns. */ + private static void bindIdentity( + final OntologyConcept concept, + final Table table, + final Ontology ontology, + final String... columns) { + bind( + concept, + binding(table, OntologyBindingRole.IDENTITY, columns[0]) + .withColumns(dataColumns(concept, ontology, columns)), + bindings(concept, "").getRevision()); + } + + /** Each column bound to a data property of its own. */ + private static List dataColumns( + final OntologyConcept concept, final Ontology ontology, final String... columns) { + return List.of(columns).stream() + .map( + name -> + column( + dataProperty( + ontology, + "p" + UUID.randomUUID().toString().substring(0, 8), + concept, + false), + name)) + .toList(); + } + + /** Makes the reader the owner of the table, which a rule on ownership then shows them. */ + private static void own(final Table table, final OpenMetadataClient reader) { + final var current = admin().tables().get(table.getId().toString(), "owners"); + admin() + .tables() + .update(table.getId().toString(), current.withOwners(List.of(readerReference(reader)))); + } + private static OntologyColumnBinding column(final OntologyProperty property, final String name) { return new OntologyColumnBinding() .withPropertyId(property.getId()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java index 4191d4d25e5c..85a38d18461e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java @@ -65,16 +65,22 @@ /** * Reads what SQL generation needs in a fixed number of batched statements, whatever the hop count: - * the concepts, the hop properties and their inverses, each concept's first bound tables, those - * tables twice (for the view check, then columns of the kept ones), and the properties their - * columns bind. Tables the reader may not view are treated as unbound, so their columns never - * appear in the SQL. The call writes nothing. + * the concepts, the hop properties and their inverses, the identity table of the concept the + * statement starts from, the first bound tables of each concept a hop reaches, those tables twice + * (for the view check, then columns of the kept ones), and the properties their columns bind. The + * call writes nothing. + * + *

The statement starts from the identity table of its concept, as every statement about the + * records of that concept does (ADR:2026-11-22-record-statements-start-from-the-identity-table). + * A table that a hop reaches and the reader may not view is treated as unbound, so its columns + * never appear in the SQL. */ @Slf4j public final class OntologyConceptQueryService { /** - * Each concept reads its first 100 table bindings and keeps the first 10 the reader may view, in - * asset-id order (ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension). + * Each concept a hop reaches reads its first 100 table bindings and keeps the first 10 the reader + * may view, in asset-id order + * (ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension). */ public static final int TABLE_BINDINGS_READ = 100; @@ -83,6 +89,7 @@ public final class OntologyConceptQueryService { private final OntologyConceptBindingStore store; private final Authorizer authorizer; private final Function> repositories; + private final OntologyMappingReader mapping; public OntologyConceptQueryService( final OntologyConceptBindingStore store, @@ -91,6 +98,8 @@ public OntologyConceptQueryService( this.store = store; this.authorizer = authorizer; this.repositories = repositories; + this.mapping = + new OntologyMappingReader(store, new OntologyBindingAccess(authorizer, repositories)); } public OntologyConceptQuery generate( @@ -103,7 +112,8 @@ public OntologyConceptQuery generate( store.requireLiveOntology(root); final Map relations = relations(access, root, hops); final Inverses inverses = inverses(access, root, relations.values()); - final Map bound = bind(access, concepts.values()); + final Map bound = + bind(access, hops.stream().map(hop -> concepts.get(hop.getTarget())).distinct().toList()); final List steps = new ArrayList<>(); final List labeled = new ArrayList<>(); for (final OntologyConceptQueryHop hop : hops) { @@ -121,7 +131,7 @@ public OntologyConceptQuery generate( .withDirection(hop.getDirection()) .withLabel(step.label())); } - return response(OntologyConceptSqlGenerator.generate(bound.get(conceptId), steps), labeled); + return response(OntologyConceptSqlGenerator.generate(start(access, root), steps), labeled); } } @@ -266,6 +276,21 @@ private Map relations( return properties; } + /** + * The concept a statement starts from, with the one table it starts from: its identity table. A + * concept without one is a 409, and one whose identity table the reader may not view is a 403. + */ + private BoundConcept start(final Access access, final OntologyConcept root) { + final BindingRow identity = mapping.identityRows(List.of(root.getId())).get(root.getId()); + final List rows = identity == null ? List.of() : List.of(identity); + OntologyMappingReader.identity(root.getIri(), identity, mapping.tables(access, rows)); + final Table table = tablesWithColumns(access, rows).get(identity.assetId()); + return new BoundConcept( + label(root), + List.of(OntologyBoundTables.of(table, identity, boundProperties(access, rows)))); + } + + /** The tables that each concept a hop reaches binds and the reader may view. */ private Map bind( final Access access, final Collection concepts) { final List rows = @@ -425,7 +450,8 @@ private static OntologyConceptQuery response( final Generated generated, final List hops) { return new OntologyConceptQuery() .withHops(hops) - .withSql(generated.escapedSql()) + .withSql(generated.sql()) + .withEscapedSql(generated.escapedSql()) .withDialect(generated.dialect()) .withService(generated.service()) .withServiceType(generated.serviceType()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index 9d676e7f7dbb..53dbee3f9a6f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -109,7 +109,10 @@ public BoundTable( } } - /** A concept and the tables it binds that the reader may view, in asset id order. */ + /** + * A concept and the tables it binds that the reader may view, in asset id order. The concept a + * statement starts from holds one table, its identity table. + */ public record BoundConcept(String label, List tables) {} /** @@ -410,15 +413,13 @@ private static void requireSameDatabase(final MappedClass type, final MappedTabl } } + /** The one table a statement starts from, which its caller found as the identity table. */ private static BoundTable rootTable(final BoundConcept root) { final List tables = listOrEmpty(root.tables()); if (tables.isEmpty()) { throw new BadRequestException(String.format("Concept %s %s", root.label(), NO_VISIBLE_TABLE)); } - return tables.stream() - .filter(table -> !table.columns().isEmpty()) - .findFirst() - .orElse(tables.getFirst()); + return tables.getFirst(); } /** diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json index 9a20d4a9aef1..b19d9626955f 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json @@ -50,7 +50,11 @@ "default": [] }, "sql": { - "description": "Generated SELECT limited to 50 rows. It applies the row filter of each table it reads. Every colon is written as a backslash and a colon, so a consumer that reads `:name` as a bind parameter finds none. Set by the server.", + "description": "Generated SELECT limited to 50 rows, for a person to read. It starts from the identity table of the concept and applies the row filter of each table it reads. Every colon is written as a colon. Do not pass it to a library that reads `:name` as a bind parameter. Set by the server.", + "type": "string" + }, + "escapedSql": { + "description": "The same statement with every colon written as a backslash and a colon. It is the only form to run through a SQLAlchemy `text()` call, which reads `\\:` as a colon and would read a bare colon as the start of a bind parameter. Set by the server.", "type": "string" }, "dialect": { "$ref": "#/definitions/dialect" }, From 17e5b082d871aa9504edb0a1299c48c9dcedb36a Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 12:05:33 -0800 Subject: [PATCH 035/203] Test the record statements on MySQL and Postgres OntologyRecordStatementIT creates the six mapping shapes as real tables with known rows. It binds them, asks each endpoint, runs the statement that comes back, and compares the rows, the column plan and the golden text. It covers the 26th row of expand and several contributing rows for one key. It also shows that a contributing table the reader may not view leaves the plan, that a class only the draft holds is a 404 through `release`, and that a binding write moves the binding revision of the next plan. OntologyStatementRefusalIT asserts the status and the message of each refusal. They are a hidden identity table, a hidden link table, no identity table, an inferred join, no join, a draft read without EditAll, an ontology without an active release, and a key that does not fit. OntologyStatementValueIT sends every key and search text case of the value cases file through open and find on all nine engine families. A rendered case must put its expected text in `escapedSql`, and a refused case must get its 400. --- ...tatements-start-from-the-identity-table.md | 2 +- .../it/tests/OntologyRecordStatementIT.java | 370 ++++++++++++++++ .../it/tests/OntologyShapeFixture.java | 406 ++++++++++++++++++ .../it/tests/OntologySqlValueCases.java | 12 +- .../it/tests/OntologyStatementRefusalIT.java | 379 ++++++++++++++++ .../it/tests/OntologyStatementValueIT.java | 378 ++++++++++++++++ 6 files changed, 1545 insertions(+), 2 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementValueIT.java diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md index 7b46f6af2e42..e2babe062d17 100644 --- a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-11-22 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyConceptQueryIT` +- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyRecordStatementIT`, `OntologyStatementRefusalIT`, `OntologyStatementValueIT`, `OntologyConceptQueryIT` - **Related:** ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles and the subject key that a statement reads), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (amended by this record), ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension (three of its rules are replaced here), ADR:2026-11-21-a-class-has-at-most-one-display-name-property ## Context diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java new file mode 100644 index 000000000000..828d6c3c8a74 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java @@ -0,0 +1,370 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.columnPlan; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.function.Executable; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementBindingRevision; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementRelation; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Asks the four statement endpoints of a class about each mapping shape, with the tables of the + * shape created in the database this suite runs on, and runs every statement that comes back. A + * statement must be the golden text of its engine family, and must return the rows that the shape + * says its tables hold. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyRecordStatementIT extends BaseOntologyApprovalIT { + /** The rows a statement may return: its row cap, and whether it asks for one row more. */ + private record Limit(int rowCap, boolean extraRow) { + int rows() { + return extraRow ? rowCap + 1 : rowCap; + } + } + + private static final Limit FIND = new Limit(25, false); + private static final Limit OPEN = new Limit(100, true); + private static final Limit EXPAND = new Limit(25, true); + private static final Limit TOP_RECORDS = new Limit(8, false); + private static final Limit COUNT = new Limit(1, false); + + @Test + void anIdentityTableWithoutAFilterAnswersEveryStatement(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, UNFILTERED_IDENTITY); + + assertEquals(List.of(List.of("3")), rows.get("count")); + } + + @Test + void twoClassesOverOneFilteredTableEachAnswerWithTheirOwnRows(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, FILTERED_IDENTITY); + + assertEquals(List.of(List.of("2")), rows.get("person-count")); + assertEquals(List.of(List.of("2")), rows.get("organization-count")); + } + + @Test + void aTwoColumnKeyPairsWithItsContributingTableByPosition(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, COMPOSITE_KEY); + + assertEquals(List.of(List.of("eu", "42", "Northwind", "gold")), rows.get("open")); + } + + @Test + void aContributingTableWithSeveralRowsForOneKeyGivesSeveralRows(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, REPEATED_CONTRIBUTION); + + assertEquals(3, rows.get("open").size()); + } + + @Test + void aRelationHeldInAColumnIsFollowedBothWaysAndPagedByOneExtraRow(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, COLUMN_RELATION); + + assertEquals(26, rows.get("expand-inverse-page").size()); + assertEquals(25, rows.get("find").size()); + assertEquals(List.of(List.of("31", "2", "Grace Hopper")), rows.get("expand-forward")); + } + + @Test + void aRelationHeldInALinkTableIsFollowedBothWays(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, LINK_TABLE); + + assertEquals( + List.of( + List.of("A-1", "Anvil", "2"), + List.of("B-2", "Bolt", "1"), + List.of("C-3", "Crate", "1")), + rows.get("aggregate-inverse")); + } + + @Test + void aContributingTableTheReaderMayNotViewLeavesTheStatementAndIsNamedNowhere( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenContribution"); + final Ask open = REPEATED_CONTRIBUTION.ask("open"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, REPEATED_CONTRIBUTION).withRows(); + var access = new RdfAccessFixtures("stmtRecord" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.TABLE); + fixture.ownedBy(reader, "customers"); + + final OntologyStatementPlan asReader = fixture.ask(reader, open, null); + final String answer = fixture.answer(reader, open, null); + final OntologyStatementPlan asAdmin = fixture.ask(admin(), open, null); + + assertEquals( + String.join( + "\n", + "SELECT t0." + fixture.name("id") + ", t0." + fixture.name("name"), + "FROM " + fixture.from("customers") + " t0", + "WHERE t0." + fixture.name("id") + " = 1", + "LIMIT 101"), + asReader.getSql()); + assertEquals( + List.of("0 key Customer part 0", "1 displayName Customer customerName"), + columnPlan(asReader.getColumns())); + assertEquals( + List.of(fixture.table("customers").getFullyQualifiedName()), asReader.getTables()); + assertEquals( + List.of(List.of("1", "Ada Lovelace")), OntologyShapeFixture.run(asReader.getSql())); + assertNamesNothingOf(fixture.table("customer_addresses"), answer); + // The hidden table and both properties bound on it have "address" in their names. + assertFalse(answer.contains("address"), answer); + assertEquals(asReader.getColumns(), asAdmin.getColumns().subList(0, 2)); + assertEquals(open.columns(), columnPlan(asAdmin.getColumns())); + } + } + + @Test + void aStatementReadsTheVersionThatItsRequestNames(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "versions"); + final Ask open = LINK_TABLE.ask("open"); + final Ask products = LINK_TABLE.ask("count"); + final Ask contained = LINK_TABLE.ask("expand-forward"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, LINK_TABLE).withRows()) { + fixture.bind(LINK_TABLE.binding("Order", "orders")); + final OntologyRelease release = current(activate(ns, ontology)); + fixture.bind(LINK_TABLE.binding("Product", "products")); + fixture.bind(LINK_TABLE.binding("Order", "order_items")); + final String inRelease = + " is not in the active release of ontology " + ontology.getFullyQualifiedName(); + + final OntologyStatementPlan released = + fixture.ask(admin(), open, OntologyStatementVersion.RELEASE); + final OntologyStatementPlan drafted = + fixture.ask(admin(), open, OntologyStatementVersion.DRAFT); + + assertRefused( + 404, + "Class https://example.org/linkTable#Product" + inRelease, + () -> fixture.ask(admin(), products, OntologyStatementVersion.RELEASE)); + assertRefused( + 404, + "Relation https://example.org/linkTable#contains" + inRelease, + () -> fixture.ask(admin(), contained, OntologyStatementVersion.RELEASE)); + assertEquals( + List.of("0 key Order part 0", "1 property Order orderChannel"), + columnPlan(released.getColumns())); + assertEquals(List.of(fixture.table("orders").getFullyQualifiedName()), released.getTables()); + assertEquals(List.of(List.of("1", "web")), OntologyShapeFixture.run(released.getSql())); + assertEquals(releaseRead(release), released.getVersion()); + assertEquals(open.columns(), columnPlan(drafted.getColumns())); + assertRows(open, OPEN, OntologyShapeFixture.run(drafted.getSql())); + assertEquals( + new OntologyStatementVersionRead() + .withKind(OntologyStatementVersion.DRAFT) + .withWorkingRevision( + admin().ontologies().state(ontology.getId()).getWorkingRevision()), + drafted.getVersion()); + assertEquals( + List.of(List.of("4")), + OntologyShapeFixture.run( + fixture.ask(admin(), products, OntologyStatementVersion.DRAFT).getSql())); + assertRows( + contained, + EXPAND, + OntologyShapeFixture.run( + fixture.ask(admin(), contained, OntologyStatementVersion.DRAFT).getSql())); + } + } + + @Test + void aBindingWriteMovesTheBindingRevisionOfTheNextPlan(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "revisions"); + final Ask find = UNFILTERED_IDENTITY.ask("find"); + final BindingSpec bound = UNFILTERED_IDENTITY.binding("Customer", "customers"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, UNFILTERED_IDENTITY)) { + fixture.bindAll(); + + final OntologyStatementPlan first = + fixture.ask(admin(), find, OntologyStatementVersion.DRAFT); + fixture.bind( + new BindingSpec( + bound.type(), + bound.table(), + bound.role(), + bound.key(), + null, + List.of(bound.columns().getLast()))); + final OntologyStatementPlan second = + fixture.ask(admin(), find, OntologyStatementVersion.DRAFT); + + assertEquals(List.of(fixture.revision("Customer", 1L)), first.getBindingRevisions()); + assertEquals(find.columns(), columnPlan(first.getColumns())); + assertEquals(List.of(fixture.revision("Customer", 2L)), second.getBindingRevisions()); + assertEquals( + List.of("0 key Customer part 0", "1 displayName Customer customerName"), + columnPlan(second.getColumns())); + } + } + + /** + * Binds the shape over real tables, activates a release and asks every statement of the shape as + * a request that names no version. + * + * @return the rows each statement returned, by the name of its ask + */ + private static Map>> everyStatement( + final TestNamespace ns, final Shape shape) { + final Ontology ontology = createOntology(ns, shape.name()); + final Map>> rows = new ConcurrentHashMap<>(); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, shape).withRows()) { + fixture.bindAll(); + final OntologyRelease release = current(activate(ns, ontology)); + assertAll( + shape.asks().stream() + .map( + ask -> + (Executable) + () -> rows.put(ask.name(), answered(fixture, shape, ask, release)))); + } + return rows; + } + + /** Checks the plan of one statement, runs the statement and checks its rows. */ + private static List> answered( + final OntologyShapeFixture fixture, + final Shape shape, + final Ask ask, + final OntologyRelease release) { + final OntologyStatementPlan plan = fixture.ask(admin(), ask, null); + final Limit limit = limitOf(ask); + final String name = ask.name(); + + assertEquals(fixture.golden(ask), plan.getSql() + "\n", name + " sql"); + assertEquals(plan.getSql(), plan.getEscapedSql(), name + " escapedSql"); + assertEquals(ask.kind(), plan.getStatement(), name + " statement"); + assertEquals(fixture.family(), plan.getFamily().value(), name + " family"); + assertEquals(fixture.dialect(), plan.getDialect(), name + " dialect"); + assertEquals(fixture.service().getName(), plan.getService(), name + " service"); + assertEquals( + fixture.service().getServiceType().value(), plan.getServiceType(), name + " serviceType"); + assertEquals(fixture.tablesOf(ask), plan.getTables(), name + " tables"); + assertEquals(ask.columns(), columnPlan(plan.getColumns()), name + " columns"); + assertEquals(relationOf(shape, ask), plan.getRelation(), name + " relation"); + assertEquals(limit.rowCap(), plan.getRowCap(), name + " rowCap"); + assertEquals(limit.extraRow(), plan.getExtraRow(), name + " extraRow"); + assertEquals(releaseRead(release), plan.getVersion(), name + " version"); + assertEquals(revisionsOf(fixture, shape, ask), plan.getBindingRevisions(), name + " revisions"); + final List> rows = OntologyShapeFixture.run(plan.getSql()); + assertRows(ask, limit, rows); + return rows; + } + + private static Limit limitOf(final Ask ask) { + return switch (ask.kind()) { + case FIND -> FIND; + case OPEN -> OPEN; + case EXPAND -> EXPAND; + case AGGREGATE -> ask.relation() == null ? COUNT : TOP_RECORDS; + }; + } + + /** + * An aggregate returns exactly its rows, in order. Any other statement returns rows that the + * shape lists, each as often as the shape lists it, and stops at its row limit. + */ + private static void assertRows(final Ask ask, final Limit limit, final List> rows) { + if (ask.kind() == OntologyStatementKind.AGGREGATE) { + assertEquals(ask.rows(), rows, ask.name() + " rows"); + return; + } + final List> listed = new ArrayList<>(ask.rows()); + for (final List row : rows) { + assertTrue(listed.remove(row), () -> ask.name() + " returned " + row); + } + assertEquals(Math.min(ask.rows().size(), limit.rows()), rows.size(), ask.name() + " row count"); + } + + /** What a plan says about the relation that the ask follows, and null when it follows none. */ + private static OntologyStatementRelation relationOf(final Shape shape, final Ask ask) { + return ask.relation() == null + ? null + : new OntologyStatementRelation() + .withPropertyIri(shape.iri(ask.relation())) + .withDirection(ask.direction()) + .withRelatedClassIri(shape.iri(relatedTo(shape, ask))); + } + + /** The class at the far end of the relation: its range forward and its domain going back. */ + private static String relatedTo(final Shape shape, final Ask ask) { + final PropertySpec relation = shape.property(ask.relation()); + return ask.direction() == OntologyStatementDirection.FORWARD + ? relation.range() + : relation.domain(); + } + + /** The binding revision of each class the statement reads, as the bindings endpoint gives it. */ + private static List revisionsOf( + final OntologyShapeFixture fixture, final Shape shape, final Ask ask) { + return ask.relation() == null + ? List.of(fixture.revisionOf(ask.type())) + : List.of(fixture.revisionOf(ask.type()), fixture.revisionOf(relatedTo(shape, ask))); + } + + private static OntologyStatementVersionRead releaseRead(final OntologyRelease release) { + return new OntologyStatementVersionRead() + .withKind(OntologyStatementVersion.RELEASE) + .withReleaseId(release.getId()) + .withReleaseRevision(release.getReleaseRevision()) + .withSemanticVersion(release.getSemanticVersion()); + } + + private static void assertNamesNothingOf(final Table hidden, final String answer) { + assertFalse(answer.contains(hidden.getName()), answer); + assertFalse(answer.contains(hidden.getId().toString()), answer); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java new file mode 100644 index 000000000000..5aa22ccdf5f5 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java @@ -0,0 +1,406 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.jdbi.v3.core.Handle; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.factories.DatabaseTestFactory; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.OntologyAggregateStatementRequest; +import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; +import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; +import org.openmetadata.schema.api.data.OntologyFindStatementRequest; +import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; +import org.openmetadata.schema.api.data.OntologyStatementBindingRevision; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.services.CreateDatabaseService; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.services.DatabaseService; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyConceptBindingsResponse; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.ontology.OntologyMappingShapes; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; + +/** + * One mapping shape of {@link OntologyMappingShapes} made through the API over the database this + * suite runs on: a database service of the type of that database, and a table entry for each table + * of the shape. A class or a property is created the first time a binding names it, so a test + * decides what a release of the ontology holds by what it binds before it activates one. + * + *

{@link #withRows} also creates the tables in the database with the rows of the shape, so a + * generated statement can run. Every shape names its tables as a shop would and the suite has one + * database, so each fixture gives its tables a prefix of its own. + */ +final class OntologyShapeFixture implements AutoCloseable { + private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + private static final Pattern GOLDEN_TABLE = + Pattern.compile("(?:FROM|JOIN) `?" + OntologyMappingShapes.GOLDEN_SCHEMA + "`?\\.`?(\\w+)"); + private static final Map COLUMN_TYPES = + Map.of( + ColumnDataType.INT, "INT", + ColumnDataType.VARCHAR, "VARCHAR(64)", + ColumnDataType.DECIMAL, "DECIMAL(10,2)"); + + private final Shape shape; + private final Ontology ontology; + private final boolean mysql = TestSuiteBootstrap.getConnectionType() == ConnectionType.MYSQL; + private final String prefix = "s" + UUID.randomUUID().toString().substring(0, 8) + "_"; + private final String schemaName; + private final DatabaseService service; + private final Map tables = new HashMap<>(); + private final Map classes = new HashMap<>(); + private final Map properties = new HashMap<>(); + private final List created = new ArrayList<>(); + + OntologyShapeFixture(final TestNamespace ns, final Ontology ontology, final Shape shape) { + this.shape = shape; + this.ontology = ontology; + this.schemaName = + TestSuiteBootstrap.getJdbi() + .withHandle( + handle -> + handle + .createQuery(mysql ? "SELECT DATABASE()" : "SELECT current_schema()") + .mapTo(String.class) + .one()); + this.service = + ns.trackRoot( + Entity.DATABASE_SERVICE, + admin() + .databaseServices() + .create( + new CreateDatabaseService() + .withName(ns.prefix("shapes")) + .withServiceType( + mysql ? DatabaseServiceType.Mysql : DatabaseServiceType.Postgres))); + final DatabaseSchema schema = + DatabaseSchemaTestFactory.create( + DatabaseTestFactory.create(ns, service.getFullyQualifiedName()).getFullyQualifiedName(), + schemaName); + for (final TableSpec spec : shape.tables()) { + tables.put( + spec.name(), + OntologyMappingFixtures.table( + schema, + prefix + spec.name(), + spec.columns().stream() + .map(column -> OntologyMappingFixtures.column(column.name(), column.type())) + .toArray(Column[]::new))); + } + } + + /** Creates the tables in the database of the suite and fills them with the rows of the shape. */ + OntologyShapeFixture withRows() { + TestSuiteBootstrap.getJdbi() + .useTransaction(handle -> shape.tables().forEach(spec -> create(handle, spec))); + return this; + } + + private void create(final Handle handle, final TableSpec spec) { + final String name = prefix + spec.name(); + handle.execute( + "CREATE TABLE " + + name + + " (" + + spec.columns().stream() + .map(column -> column.name() + " " + COLUMN_TYPES.get(column.type())) + .collect(Collectors.joining(", ")) + + ")"); + created.add(name); + final String marks = String.join(", ", Collections.nCopies(spec.columns().size(), "?")); + final String insert = "INSERT INTO " + name + " VALUES (" + marks + ")"; + try (PreparedStatement row = handle.getConnection().prepareStatement(insert)) { + for (final List values : spec.rows()) { + for (int column = 0; column < values.size(); column++) { + row.setObject(column + 1, values.get(column)); + } + row.executeUpdate(); + } + } catch (final SQLException failed) { + throw new IllegalStateException(insert, failed); + } + } + + Shape shape() { + return shape; + } + + DatabaseService service() { + return service; + } + + /** The engine family of the database of the suite, as a plan and a golden directory name it. */ + String family() { + return mysql ? "mysql" : "postgres"; + } + + OntologyConceptQueryDialect dialect() { + return mysql ? OntologyConceptQueryDialect.MYSQL : OntologyConceptQueryDialect.ANSI; + } + + /** A column or a table name as a statement for this database writes it. */ + String name(final String plain) { + return mysql ? "`" + plain + "`" : plain; + } + + /** A table of the shape as a statement names it after {@code FROM} or {@code JOIN}. */ + String from(final String tableName) { + return name(schemaName) + "." + name(prefix + tableName); + } + + Table table(final String name) { + return tables.get(name); + } + + /** The class of the shape with this name, declared in the working draft on first use. */ + OntologyConcept type(final String name) { + return classes.computeIfAbsent( + name, term -> BaseOntologyApprovalIT.declareClass(ontology, term, shape.iri(term))); + } + + /** The property of the shape with this name, declared in the working draft on first use. */ + OntologyProperty property(final String name) { + final OntologyProperty declared = properties.get(name); + if (declared != null) { + return declared; + } + final PropertySpec spec = shape.property(name); + final CreateOntologyProperty request = + new CreateOntologyProperty() + .withName(name) + .withIri(shape.iri(name)) + .withOntology(ontology.getFullyQualifiedName()) + .withKind(spec.kind()) + .withDomain(List.of(type(spec.domain()).getIri())) + .withRange(List.of(spec.range() == null ? XSD_STRING : type(spec.range()).getIri())); + final OntologyProperty created = + admin() + .ontologyProperties() + .create(spec.displayName() ? request.withIsDisplayName(true) : request); + properties.put(name, created); + return created; + } + + /** Writes every binding of the shape, in the order the shape lists them. */ + OntologyShapeFixture bindAll() { + shape.bindings().forEach(this::bind); + return this; + } + + /** Writes one binding of the shape, or a changed copy of one, over what the class binds now. */ + OntologyConceptBindingsResponse bind(final BindingSpec spec) { + final OntologyConcept type = type(spec.type()); + final Table table = tables.get(spec.table()); + final OntologyAssetBinding asset = + spec.role() == null + ? binding(table) + : binding(table, spec.role(), spec.key().toArray(String[]::new)); + asset.withColumns(spec.columns().stream().map(this::column).toList()); + if (spec.filter() != null) { + asset.withRowFilter( + filter(spec.filter().column(), spec.filter().operator(), spec.filter().value())); + } + return put(admin(), type, asset, bindings(admin(), type).getRevision()); + } + + private OntologyColumnBinding column(final ColumnBindingSpec spec) { + final OntologyColumnBinding bound = + OntologyMappingFixtures.column(property(spec.property()), spec.column()); + return spec.join() == null ? bound : bound.withJoin(join(spec.join())); + } + + private OntologyColumnJoin join(final JoinSpec spec) { + return new OntologyColumnJoin() + .withTargetAssetId(tables.get(spec.target()).getId()) + .withStatus(spec.status()) + .withOn( + IntStream.range(0, spec.child().size()) + .mapToObj( + pair -> + new OntologyJoinColumnPair() + .withChild(List.of(spec.child().get(pair))) + .withParent(List.of(spec.parent().get(pair)))) + .toList()); + } + + /** Makes {@code reader} the owner of the named tables, which a rule on ownership then shows. */ + void ownedBy(final OpenMetadataClient reader, final String... names) { + final EntityReference owner = OntologyBindingFixtures.readerReference(reader); + for (final String name : names) { + final String id = tables.get(name).getId().toString(); + admin().tables().update(id, admin().tables().get(id, "owners").withOwners(List.of(owner))); + } + } + + /** What a plan says about the bindings of one class: its id, its IRI and its revision now. */ + OntologyStatementBindingRevision revisionOf(final String typeName) { + return revision(typeName, bindings(admin(), type(typeName)).getRevision()); + } + + OntologyStatementBindingRevision revision(final String typeName, final long revision) { + final OntologyConcept type = type(typeName); + return new OntologyStatementBindingRevision() + .withConceptId(type.getId()) + .withClassIri(type.getIri()) + .withRevision(revision); + } + + /** + * Asks the endpoint of one statement, as {@code client}. + * + * @param version the version to read, or null to name none + */ + OntologyStatementPlan ask( + final OpenMetadataClient client, final Ask ask, final OntologyStatementVersion version) { + return client + .getHttpClient() + .execute(HttpMethod.POST, path(ask), request(ask, version), OntologyStatementPlan.class); + } + + /** The body of the answer to {@link #ask}, as the server wrote it. */ + String answer( + final OpenMetadataClient client, final Ask ask, final OntologyStatementVersion version) { + return client + .getHttpClient() + .executeForString(HttpMethod.POST, path(ask), request(ask, version)); + } + + private String path(final Ask ask) { + return "/v1/ontologyConcepts/" + type(ask.type()).getId() + "/statements/" + ask.kind(); + } + + private Object request(final Ask ask, final OntologyStatementVersion version) { + final UUID relation = ask.relation() == null ? null : property(ask.relation()).getId(); + return switch (ask.kind()) { + case FIND -> new OntologyFindStatementRequest() + .withVersion(version) + .withMatchText(ask.matchText()); + case OPEN -> new OntologyOpenStatementRequest().withVersion(version).withKey(ask.key()); + case EXPAND -> new OntologyExpandStatementRequest() + .withVersion(version) + .withKey(ask.key()) + .withRelation(relation) + .withDirection(ask.direction()); + case AGGREGATE -> new OntologyAggregateStatementRequest() + .withVersion(version) + .withRelation(relation) + .withDirection(ask.direction()); + }; + } + + /** + * The golden text of a statement of the shape, as the engine family of this database writes it, + * with the tables of this fixture in place of the tables of the golden schema. + */ + String golden(final Ask ask) { + final String shop = OntologyMappingShapes.GOLDEN_SCHEMA; + return mysql + ? goldenText(ask).replace("`" + shop + "`.`", "`" + schemaName + "`.`" + prefix) + : goldenText(ask).replace(shop + ".", schemaName + "." + prefix); + } + + /** The tables that the golden text of a statement reads, in join order, by full name. */ + List tablesOf(final Ask ask) { + return GOLDEN_TABLE + .matcher(goldenText(ask)) + .results() + .map(named -> tables.get(named.group(1)).getFullyQualifiedName()) + .toList(); + } + + private String goldenText(final Ask ask) { + final String resource = "/" + shape.golden(family(), ask); + try (InputStream file = OntologyShapeFixture.class.getResourceAsStream(resource)) { + return new String(file.readAllBytes(), StandardCharsets.UTF_8); + } catch (final IOException unread) { + throw new UncheckedIOException(resource, unread); + } + } + + /** Runs a statement as a driver sends it and returns its rows, each value as text. */ + static List> run(final String sql) { + try (Handle handle = TestSuiteBootstrap.getJdbi().open(); + Statement statement = handle.getConnection().createStatement()) { + statement.setEscapeProcessing(false); + try (ResultSet rows = statement.executeQuery(sql)) { + final int width = rows.getMetaData().getColumnCount(); + final List> read = new ArrayList<>(); + while (rows.next()) { + final List row = new ArrayList<>(); + for (int column = 1; column <= width; column++) { + row.add(rows.getString(column)); + } + read.add(row); + } + return read; + } + } catch (final SQLException failed) { + throw new IllegalStateException(sql, failed); + } + } + + @Override + public void close() { + TestSuiteBootstrap.getJdbi() + .useHandle(handle -> created.forEach(name -> handle.execute("DROP TABLE " + name))); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlValueCases.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlValueCases.java index dcafb911087d..f826b7f662bb 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlValueCases.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlValueCases.java @@ -32,9 +32,19 @@ private OntologySqlValueCases() {} /** Every case whose outcome is of {@code kind}, in the order of the file. */ static List withOutcome(final String kind) { + return all().stream() + .filter(json -> kind.equals(json.at("/expectedOutcome/kind").asText())) + .toList(); + } + + /** Every case that gives a value on {@code path}, whatever must happen to it. */ + static List onPath(final String path) { + return all().stream().filter(json -> path.equals(json.get("path").asText())).toList(); + } + + private static List all() { try (InputStream cases = OntologySqlValueCases.class.getResourceAsStream(CASES)) { return StreamSupport.stream(JsonUtils.getObjectMapper().readTree(cases).spliterator(), false) - .filter(json -> kind.equals(json.at("/expectedOutcome/kind").asText())) .toList(); } catch (IOException e) { throw new UncheckedIOException(e); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java new file mode 100644 index 000000000000..7a621b84c913 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java @@ -0,0 +1,379 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; + +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; + +/** + * Every way the four statement endpoints of a class refuse a request, each with its status and + * its message. A refusal about a table names the class and never the table. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyStatementRefusalIT extends BaseOntologyApprovalIT { + private static final String ORDER = "https://example.org/columnRelation#Order"; + private static final String CUSTOMER = "https://example.org/columnRelation#Customer"; + private static final String PLACED_BY = "https://example.org/columnRelation#placedBy"; + private static final String ORDER_HIDDEN = + "The identity table of class " + ORDER + " is not visible to you"; + private static final String CUSTOMER_HIDDEN = + "The identity table of class " + CUSTOMER + " is not visible to you"; + private static final String LINK_HIDDEN = + "The table that links class https://example.org/linkTable#Order to class" + + " https://example.org/linkTable#Product for relation" + + " https://example.org/linkTable#contains is not visible to you"; + private static final String CUSTOMER_UNBOUND = "Class " + CUSTOMER + " has no identity table"; + private static final String NO_JOIN = + "Relation " + + PLACED_BY + + " has no join from class " + + ORDER + + " to the identity table of class " + + CUSTOMER; + private static final String JOIN_NOT_CONFIRMED = + "The join of relation " + + PLACED_BY + + " from class " + + ORDER + + " to class " + + CUSTOMER + + " is not confirmed"; + private static final String NOT_A_WHOLE_NUMBER = + " does not parse as INT: a whole number is written in ASCII digits, with a leading minus" + + " sign when negative and no leading zeros"; + private static final String RELATION_OR_COUNT = + "An aggregate over a relation takes the relation and the direction together. A count of the" + + " class takes neither, and no related class"; + private static final List ALONG_THE_RELATION = + List.of("expand-forward", "expand-inverse", "aggregate-forward", "aggregate-inverse"); + + @Test + void aReaderWhoMayNotViewAnIdentityTableIsRefusedByClassAndNeverByTable(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenIdentity"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var first = new RdfAccessFixtures("stmtCustomers" + ns.shortPrefix()); + var second = new RdfAccessFixtures("stmtOrders" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient seesCustomers = ownerReader(first, Entity.TABLE); + fixture.ownedBy(seesCustomers, "customers"); + final OpenMetadataClient seesOrders = ownerReader(second, Entity.TABLE); + fixture.ownedBy(seesOrders, "orders"); + + for (final String start : List.of("find", "open", "count")) { + assertRefused(403, ORDER_HIDDEN, () -> ask(fixture, seesCustomers, start)); + } + for (final String relation : ALONG_THE_RELATION) { + assertRefused(403, ORDER_HIDDEN, () -> ask(fixture, seesCustomers, relation)); + assertRefused(403, CUSTOMER_HIDDEN, () -> ask(fixture, seesOrders, relation)); + } + assertEquals(OntologyStatementKind.FIND, ask(fixture, seesOrders, "find").getStatement()); + } + } + + @Test + void aReaderWhoMayNotViewTheLinkTableOfARelationIsRefusedWithoutItBeingNamed( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenLink"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("stmtLink" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.TABLE); + fixture.ownedBy(reader, "orders", "products"); + + for (final String relation : ALONG_THE_RELATION) { + assertRefused(403, LINK_HIDDEN, () -> ask(fixture, reader, relation)); + } + assertEquals( + List.of(fixture.table("orders").getFullyQualifiedName()), + ask(fixture, reader, "open").getTables()); + } + } + + @Test + void aClassWithoutAnIdentityTableGivesNoStatement(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "noIdentity"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + final List ofCustomer = + List.of( + new Ask( + "find", + OntologyStatementKind.FIND, + "Customer", + null, + null, + null, + null, + null, + null), + new Ask( + "open", + OntologyStatementKind.OPEN, + "Customer", + null, + List.of(1), + null, + null, + null, + null), + new Ask( + "count", + OntologyStatementKind.AGGREGATE, + "Customer", + null, + null, + null, + null, + null, + null)); + + ofCustomer.forEach( + ask -> assertRefused(409, CUSTOMER_UNBOUND, () -> fixture.ask(admin(), ask, DRAFT))); + fixture.bind( + new BindingSpec( + "Customer", + "customers", + null, + List.of(), + null, + List.of(new ColumnBindingSpec("customerName", "name", null)))); + ofCustomer.forEach( + ask -> assertRefused(409, CUSTOMER_UNBOUND, () -> fixture.ask(admin(), ask, DRAFT))); + fixture.bind(COLUMN_RELATION.binding("Order", "orders")); + for (final String relation : ALONG_THE_RELATION) { + assertRefused(409, CUSTOMER_UNBOUND, () -> ask(fixture, admin(), relation, DRAFT)); + } + } + } + + @Test + void aRelationIsFollowedOnlyOverAConfirmedJoin(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "joins"); + final BindingSpec orders = COLUMN_RELATION.binding("Order", "orders"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bind(COLUMN_RELATION.binding("Customer", "customers")); + + fixture.bind(withColumns(orders, List.of(orders.columns().getFirst()))); + for (final String relation : ALONG_THE_RELATION) { + assertRefused(409, NO_JOIN, () -> ask(fixture, admin(), relation, DRAFT)); + } + fixture.bind( + withColumns( + orders, + List.of( + orders.columns().getFirst(), + new ColumnBindingSpec( + "placedBy", + "customer_id", + new JoinSpec( + "customers", + OntologyJoinStatus.INFERRED, + List.of("customer_id"), + List.of("id")))))); + for (final String relation : ALONG_THE_RELATION) { + assertRefused(409, JOIN_NOT_CONFIRMED, () -> ask(fixture, admin(), relation, DRAFT)); + } + fixture.bind(orders); + for (final String relation : ALONG_THE_RELATION) { + final Ask asked = COLUMN_RELATION.ask(relation); + assertEquals(asked.kind(), fixture.ask(admin(), asked, DRAFT).getStatement()); + } + } + } + + @Test + void aDraftReadTakesEditRightsAndAReleaseReadTakesAnActiveRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "versionRights"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, UNFILTERED_IDENTITY); + var access = new RdfAccessFixtures("stmtDraft" + ns.shortPrefix())) { + fixture.bindAll(); + final OpenMetadataClient consumer = client(access.userToken("consumer", List.of())); + final String name = readerReference(consumer).getName(); + + assertRefused( + 404, + "Ontology " + ontology.getFullyQualifiedName() + " has no active release", + () -> ask(fixture, admin(), "find")); + for (final Ask asked : UNFILTERED_IDENTITY.asks()) { + assertRefused( + 403, + "Principal: CatalogPrincipal{name='" + name + "'} operations [EditAll] not allowed", + () -> fixture.ask(consumer, asked, DRAFT)); + } + activate(ns, ontology); + + assertEquals( + OntologyStatementVersion.RELEASE, ask(fixture, consumer, "find").getVersion().getKind()); + assertEquals(DRAFT, ask(fixture, admin(), "find", DRAFT).getVersion().getKind()); + } + } + + @Test + void aReaderWhoMayNotViewTheClassIsRefusedOnEveryStatement(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtClass" + ns.shortPrefix())) { + fixture.bindAll(); + final var denied = access.denyRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT); + final OpenMetadataClient reader = client(access.userToken("reader", List.of(denied.getId()))); + final String refusal = + "Principal: CatalogPrincipal{name='" + + readerReference(reader).getName() + + "'} operation ViewBasic denied"; + + for (final Ask asked : COLUMN_RELATION.asks()) { + final OpenMetadataException refused = + assertThrows(OpenMetadataException.class, () -> fixture.ask(reader, asked, null)); + assertEquals(403, refused.getStatusCode(), asked.name()); + assertTrue(refused.getMessage().startsWith(refusal), refused.getMessage()); + } + } + } + + @Test + void aKeyThatDoesNotFitTheSubjectKeyIsRefusedByColumnAndType(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "keys"); + final Ask open = COMPOSITE_KEY.ask("open"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COMPOSITE_KEY)) { + fixture.bindAll(); + + assertRefused( + 400, + "The key has 2 columns but the request gives 1 value", + () -> fixture.ask(admin(), withKey(open, List.of("eu")), DRAFT)); + assertRefused( + 400, + "The key has 2 columns but the request gives 0 values", + () -> fixture.ask(admin(), withKey(open, List.of()), DRAFT)); + assertRefused( + 400, + "The value for column customer_id" + NOT_A_WHOLE_NUMBER, + () -> fixture.ask(admin(), withKey(open, List.of("eu", "forty-two")), DRAFT)); + assertRefused( + 400, + "The value for column customer_id is null", + () -> fixture.ask(admin(), withKey(open, Arrays.asList("eu", null)), DRAFT)); + assertEquals(OntologyStatementKind.OPEN, fixture.ask(admin(), open, DRAFT).getStatement()); + } + } + + @Test + void aRelationRequestNamesAnObjectPropertyItsDirectionAndAKeyThatFits(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "relationRequests"); + final Ask forward = COLUMN_RELATION.ask("expand-forward"); + final Ask top = COLUMN_RELATION.ask("aggregate-forward"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + + assertRefused( + 400, + "The value for column id" + NOT_A_WHOLE_NUMBER, + () -> fixture.ask(admin(), withKey(forward, List.of("thirty-one")), DRAFT)); + assertRefused( + 400, + "Relation https://example.org/columnRelation#orderTotal is not an object property of" + + " the ontology of class " + + ORDER, + () -> fixture.ask(admin(), along(forward, "orderTotal", forward.direction()), DRAFT)); + assertRefused( + 400, RELATION_OR_COUNT, () -> fixture.ask(admin(), along(top, "placedBy", null), DRAFT)); + assertRefused( + 400, + RELATION_OR_COUNT, + () -> fixture.ask(admin(), along(top, null, OntologyStatementDirection.FORWARD), DRAFT)); + } + } + + private static OntologyStatementPlan ask( + final OntologyShapeFixture fixture, final OpenMetadataClient client, final String name) { + return ask(fixture, client, name, null); + } + + /** Asks the statement that the shape of the fixture lists under {@code name}. */ + private static OntologyStatementPlan ask( + final OntologyShapeFixture fixture, + final OpenMetadataClient client, + final String name, + final OntologyStatementVersion version) { + return fixture.ask(client, fixture.shape().ask(name), version); + } + + private static Ask withKey(final Ask ask, final List key) { + return new Ask( + ask.name(), + ask.kind(), + ask.type(), + ask.matchText(), + key, + ask.relation(), + ask.direction(), + ask.columns(), + ask.rows()); + } + + private static Ask along( + final Ask ask, final String relation, final OntologyStatementDirection direction) { + return new Ask( + ask.name(), + ask.kind(), + ask.type(), + ask.matchText(), + ask.key(), + relation, + direction, + ask.columns(), + ask.rows()); + } + + private static BindingSpec withColumns( + final BindingSpec binding, final List columns) { + return new BindingSpec( + binding.type(), binding.table(), binding.role(), binding.key(), binding.filter(), columns); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementValueIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementValueIT.java new file mode 100644 index 000000000000..29f62ee2adba --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementValueIT.java @@ -0,0 +1,378 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.factories.DatabaseTestFactory; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.OntologyFindStatementRequest; +import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.services.CreateDatabaseService; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.services.DatabaseService; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * Sends every key and every search text of the value cases file through the statement endpoints. + * A key goes to {@code open} and a search text goes to {@code find}, each on a class whose + * identity table sits in a service of the engine family that the case is written for. The text + * that a case expects must be the text in {@code escapedSql}, and a value that a case refuses + * must be a 400 on every family. + * + *

One key case has the outcome {@code bound}. It gives values that a later statement reads + * from an earlier result and binds as parameters. A plan holds its values in its text and has no + * parameters, so no endpoint takes that case. + */ +class OntologyStatementValueIT { + private static final TestNamespace NAMESPACE = new TestNamespace("OntologyStatementValueIT"); + private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + private static final String KEY = "keyValue"; + private static final String SEARCH = "searchText"; + private static final String RENDERED = "rendered"; + private static final String REFUSED = "refusedAtRequest"; + private static final String ANY_FAMILY = "any"; + private static final String TSQL = "tsql"; + private static final Column SEARCHED = column("name", ColumnDataType.VARCHAR); + + /** + * One subject key that the cases give values for. + * + * @param searched the column that holds the display name, or null when the class has none + */ + private record KeyTable(String table, List key, Column searched) { + Column[] columns() { + return Stream.concat(key.stream(), Stream.ofNullable(searched)).toArray(Column[]::new); + } + + String signature() { + return OntologyStatementValueIT.signature(key); + } + } + + private static final List KEY_TABLES = + List.of( + new KeyTable( + "customers_by_number", + List.of(column("customer_no", ColumnDataType.VARCHAR)), + SEARCHED), + new KeyTable( + "customers_by_tenant", + List.of( + column("tenant_id", ColumnDataType.VARCHAR), + column("customer_id", ColumnDataType.INT)), + null), + new KeyTable("customers_by_id", List.of(column("customer_id", ColumnDataType.INT)), null), + new KeyTable( + "customers_by_day", List.of(column("created_on", ColumnDataType.DATE)), null)); + + /** The class of each engine family that each key identifies, by family and key signature. */ + private static final Map CLASSES = new ConcurrentHashMap<>(); + + @BeforeAll + static void bindAClassForEveryKeyInAServiceOfEveryFamily() { + final Ontology ontology = BaseOntologyApprovalIT.createOntology(NAMESPACE, "statementValues"); + firstServiceTypes().forEach((family, serviceType) -> bind(ontology, family, serviceType)); + } + + @AfterAll + static void deleteWhatTheClassCreated() { + BaseOntologyIT.deleteRoots(NAMESPACE); + } + + static Stream renderedKeys() { + return cases(KEY, RENDERED).map(json -> Arguments.of(json.get("id").asText(), json)); + } + + static Stream renderedSearches() { + return cases(SEARCH, RENDERED).map(json -> Arguments.of(json.get("id").asText(), json)); + } + + /** Every refused key and search text, once for each engine family. */ + static Stream refusedOnEveryFamily() { + final List families = List.copyOf(firstServiceTypes().keySet()); + return Stream.concat(cases(KEY, REFUSED), cases(SEARCH, REFUSED)) + .flatMap( + json -> + families.stream() + .map(family -> Arguments.of(json.get("id").asText(), family, json))); + } + + @Test + void everyKeyAndSearchCaseIsSentToAnEndpointOrIsTheOneBoundCase() { + final Map outcomes = + Stream.concat( + OntologySqlValueCases.onPath(KEY).stream(), + OntologySqlValueCases.onPath(SEARCH).stream()) + .collect( + Collectors.groupingBy( + json -> + json.get("path").asText() + " " + json.at("/expectedOutcome/kind").asText(), + Collectors.counting())); + + assertEquals( + Map.of( + "keyValue rendered", 45L, + "keyValue refusedAtRequest", 7L, + "keyValue bound", 1L, + "searchText rendered", 81L, + "searchText refusedAtRequest", 2L), + outcomes); + assertEquals(9, firstServiceTypes().size()); + assertEquals( + List.of(ANY_FAMILY), + Stream.concat(cases(KEY, REFUSED), cases(SEARCH, REFUSED)) + .map(json -> json.get("engineFamily").asText()) + .distinct() + .toList()); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("renderedKeys") + void aKeyReachesTheEscapedStatementAsItsCaseWritesIt(final String id, final JsonNode json) { + final String family = json.get("engineFamily").asText(); + final List key = keyOf(json); + final String[] parts = json.at("/expectedOutcome/text").asText().split(" \\| ", key.size()); + + final OntologyStatementPlan plan = open(typeOf(family, json), key); + + final List where = whereLines(plan.getEscapedSql()); + for (int part = 0; part < parts.length; part++) { + assertTrue(where.get(part).endsWith(" = " + parts[part]), plan::getEscapedSql); + } + assertEquals(limitLines(family, "LIMIT 101"), where.subList(parts.length, where.size())); + assertEquals(family, plan.getFamily().value()); + assertEquals(plan.getEscapedSql().replace("\\:", ":"), plan.getSql()); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("renderedSearches") + void aSearchTextReachesTheEscapedStatementAsItsCaseWritesIt( + final String id, final JsonNode json) { + final String family = json.get("engineFamily").asText(); + final String text = json.at("/expectedOutcome/text").asText(); + + final OntologyStatementPlan plan = find(typeOf(family, json), json.get("input").asText()); + + final List where = whereLines(plan.getEscapedSql()); + assertTrue(where.get(0).endsWith(" IS NOT NULL"), plan::getEscapedSql); + assertTrue(where.get(1).endsWith(" LIKE " + text), plan::getEscapedSql); + assertEquals(limitLines(family, "LIMIT 25"), where.subList(2, where.size())); + assertEquals(family, plan.getFamily().value()); + assertEquals(plan.getEscapedSql().replace("\\:", ":"), plan.getSql()); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("refusedOnEveryFamily") + void aValueThatItsCaseRefusesIsRefusedOnEveryFamily( + final String id, final String family, final JsonNode json) { + final OntologyConcept type = typeOf(family, json); + + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> { + if (KEY.equals(json.get("path").asText())) { + open(type, keyOf(json)); + } else { + find(type, json.get("input").asText()); + } + }); + + assertEquals(json.at("/expectedOutcome/status").asInt(), refused.getStatusCode()); + for (final JsonNode words : json.at("/expectedOutcome/messageContains")) { + assertTrue(refused.getMessage().contains(words.asText()), refused::getMessage); + } + } + + private static Stream cases(final String path, final String outcome) { + return OntologySqlValueCases.onPath(path).stream() + .filter(json -> outcome.equals(json.at("/expectedOutcome/kind").asText())); + } + + /** The first service type that the cases list for each engine family, in the order of the file. */ + private static Map firstServiceTypes() { + final Map first = new LinkedHashMap<>(); + Stream.concat(cases(KEY, RENDERED), cases(SEARCH, RENDERED)) + .forEach( + json -> + first.putIfAbsent( + json.get("engineFamily").asText(), json.at("/serviceTypes/0").asText())); + return first; + } + + private static void bind(final Ontology ontology, final String family, final String serviceType) { + final DatabaseService service = + NAMESPACE.trackRoot( + Entity.DATABASE_SERVICE, + admin() + .databaseServices() + .create( + new CreateDatabaseService() + .withName(NAMESPACE.prefix(family)) + .withServiceType(DatabaseServiceType.fromValue(serviceType)))); + final DatabaseSchema schema = + DatabaseSchemaTestFactory.create( + DatabaseTestFactory.create(NAMESPACE, service.getFullyQualifiedName()) + .getFullyQualifiedName(), + "sales"); + KEY_TABLES.forEach(keyed -> bind(ontology, family, schema, keyed)); + } + + private static void bind( + final Ontology ontology, + final String family, + final DatabaseSchema schema, + final KeyTable keyed) { + final String name = family + "_" + keyed.table(); + final OntologyConcept type = + BaseOntologyApprovalIT.declareClass( + ontology, name, URI.create("https://example.org/values#" + name)); + final Table table = OntologyMappingFixtures.table(schema, keyed.table(), keyed.columns()); + final OntologyAssetBinding identity = + binding( + table, + OntologyBindingRole.IDENTITY, + keyed.key().stream().map(Column::getName).toArray(String[]::new)); + CLASSES.put(family + " " + keyed.signature(), type); + if (keyed.searched() != null) { + identity.withColumns( + List.of(column(displayName(ontology, type), keyed.searched().getName()))); + CLASSES.put(family + " " + signature(List.of(keyed.searched())), type); + } + put(admin(), type, identity, 0L); + } + + private static OntologyProperty displayName(final Ontology ontology, final OntologyConcept type) { + return admin() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName(type.getName() + "_name") + .withOntology(ontology.getFullyQualifiedName()) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(type.getIri())) + .withRange(List.of(XSD_STRING)) + .withIsDisplayName(true)); + } + + /** The class of the family whose key, or whose display name, is the column of the case. */ + private static OntologyConcept typeOf(final String family, final JsonNode json) { + final JsonNode column = json.get("column"); + final List names = new ArrayList<>(); + if (column.get(0).isArray()) { + column.forEach(path -> names.add(path.get(0).asText())); + } else { + names.add(column.get(0).asText()); + } + final String signature = String.join(",", names) + "|" + json.get("columnType").asText(); + return Objects.requireNonNull( + CLASSES.get(family + " " + signature), () -> "No class has the columns " + signature); + } + + private static String signature(final List columns) { + return columns.stream().map(Column::getName).collect(Collectors.joining(",")) + + "|" + + columns.stream() + .map(column -> column.getDataType().value()) + .collect(Collectors.joining(",")); + } + + /** The input of a key case is the whole key when it is a list, and its one value otherwise. */ + private static List keyOf(final JsonNode json) { + final Object input = JsonUtils.treeToValue(json.get("input"), Object.class); + return input instanceof List parts + ? new ArrayList<>(parts) + : Collections.singletonList(input); + } + + private static OntologyStatementPlan open(final OntologyConcept type, final List key) { + return statement( + type, + "open", + new OntologyOpenStatementRequest() + .withVersion(OntologyStatementVersion.DRAFT) + .withKey(key)); + } + + private static OntologyStatementPlan find(final OntologyConcept type, final String matchText) { + return statement( + type, + "find", + new OntologyFindStatementRequest() + .withVersion(OntologyStatementVersion.DRAFT) + .withMatchText(matchText)); + } + + private static OntologyStatementPlan statement( + final OntologyConcept type, final String kind, final Object request) { + return admin() + .getHttpClient() + .execute( + HttpMethod.POST, + "/v1/ontologyConcepts/" + type.getId() + "/statements/" + kind, + request, + OntologyStatementPlan.class); + } + + /** The lines of a statement from its {@code WHERE} on. */ + private static List whereLines(final String sql) { + return sql.substring(sql.indexOf("\nWHERE ") + 1).lines().toList(); + } + + /** T-SQL writes its row limit after {@code SELECT}, so nothing follows its last condition. */ + private static List limitLines(final String family, final String limit) { + return TSQL.equals(family) ? List.of() : List.of(limit); + } +} From b16562ef2a4ad9f988cb04fe55702183bd513615 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 12:39:54 -0800 Subject: [PATCH 036/203] Test a request that names the related class An expand request can name the related class of its relation. A new integration test asks with and without the name and gets the same statement. It then asserts the three refusals that concern this field: - a class of another ontology is a 400; - a relation that names two classes in its range is a 400 when the request names none; - a range that names a class the ontology does not hold is a 404. An aggregate request that names only the related class is a 400. A unit test holds that `open` leaves out a contributing table that adds no result column, so a table that only links two classes cannot repeat the rows of a record. The decision record now states that rule and the 400 for a relation that names several classes. --- ...tatements-start-from-the-identity-table.md | 7 +- .../it/tests/OntologyStatementRefusalIT.java | 91 +++++++++++++++++++ .../ontology/OntologyRecordStatementTest.java | 12 +++ 3 files changed, 108 insertions(+), 2 deletions(-) diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md index e2babe062d17..5c555ee396be 100644 --- a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -47,7 +47,9 @@ identity table, and a table in another database is a 409. is a `LEFT JOIN` that also carries the row filter of the contributing table, so a record with no contributing row still opens. Several contributing rows for one key give several result rows. A contributing table that the reader may not view leaves the statement and the plan, and no response -names it. A class that binds more than 32 contributing tables is a 409. +names it. A contributing table that adds no result column is not joined either, so a table that +only links two classes never repeats the rows of `open`. A class that binds more than 32 +contributing tables is a 409. **`expand` and the relation count follow the stored join of the relation.** The class that binds the relation stores the join, on its identity table or on a contributing table that links the two @@ -59,7 +61,8 @@ table: a reader who may not view one gets a 403 that names the classes and never related record takes its key from the identity table of its class and never from the join column. `forward` goes from a record of the class that binds the relation to the records it names, and `inverse` goes back. A request can name `relatedClass`. Without it, the related class is the one -class in the range of the relation going forward, or in its domain going back. +class in the range of the relation going forward, or in its domain going back. When the relation +names several classes on that side, or none, a request without `relatedClass` is a 400. **Values reach the text only as typed values.** `TypedValues.key` parses a key and `TypedValues.searchText` parses match text diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java index 7a621b84c913..48d40b3e4183 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java @@ -27,22 +27,28 @@ import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import java.net.URI; import java.util.Arrays; import java.util.List; +import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.openmetadata.it.util.RdfAccessFixtures; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyAggregateStatementRequest; +import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; import org.openmetadata.schema.api.data.OntologyStatementDirection; import org.openmetadata.schema.api.data.OntologyStatementKind; import org.openmetadata.schema.api.data.OntologyStatementPlan; import org.openmetadata.schema.api.data.OntologyStatementVersion; import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyJoinStatus; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.service.Entity; import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; @@ -88,6 +94,8 @@ class OntologyStatementRefusalIT extends BaseOntologyApprovalIT { private static final String RELATION_OR_COUNT = "An aggregate over a relation takes the relation and the direction together. A count of the" + " class takes neither, and no related class"; + private static final String STRANGER = "https://example.org/elsewhere#Stranger"; + private static final String THING = "http://www.w3.org/2002/07/owl#Thing"; private static final List ALONG_THE_RELATION = List.of("expand-forward", "expand-inverse", "aggregate-forward", "aggregate-inverse"); @@ -330,6 +338,89 @@ void aRelationRequestNamesAnObjectPropertyItsDirectionAndAKeyThatFits(final Test } } + @Test + void aRequestNamesTheRelatedClassWhenTheRelationDoesNotNameOne(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "relatedClass"); + final Ontology elsewhere = createOntology(ns, "elsewhere"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + final UUID order = fixture.type("Order").getId(); + final UUID customer = fixture.type("Customer").getId(); + final UUID stranger = declareClass(elsewhere, "Stranger", URI.create(STRANGER)).getId(); + final OntologyProperty placedBy = fixture.property("placedBy"); + final String toTheCustomer = fixture.golden(COLUMN_RELATION.ask("expand-forward")); + + final OntologyStatementPlan named = expand(order, placedBy, customer); + + assertEquals(toTheCustomer, named.getSql() + "\n"); + assertEquals(URI.create(CUSTOMER), named.getRelation().getRelatedClassIri()); + assertEquals(toTheCustomer, expand(order, placedBy, null).getSql() + "\n"); + assertRefused( + 400, + "Class " + STRANGER + " is not a class of the ontology of class " + ORDER, + () -> expand(order, placedBy, stranger)); + assertRefused( + 400, + RELATION_OR_COUNT, + () -> + post( + order, + "aggregate", + new OntologyAggregateStatementRequest() + .withVersion(DRAFT) + .withRelatedClass(customer))); + + rangeOf(placedBy, URI.create(CUSTOMER), URI.create(ORDER)); + assertRefused( + 400, + "Relation " + + PLACED_BY + + " names 2 classes in its range, so the request must name the related class", + () -> expand(order, placedBy, null)); + assertEquals(toTheCustomer, expand(order, placedBy, customer).getSql() + "\n"); + + rangeOf(placedBy, URI.create(THING)); + assertRefused( + 404, + "Class " + THING + " is not a class of ontology " + ontology.getFullyQualifiedName(), + () -> expand(order, placedBy, null)); + assertEquals(toTheCustomer, expand(order, placedBy, customer).getSql() + "\n"); + } + } + + /** Asks the expand statement of order 31 with a request that can name the related class. */ + private static OntologyStatementPlan expand( + final UUID type, final OntologyProperty relation, final UUID relatedClass) { + return post( + type, + "expand", + new OntologyExpandStatementRequest() + .withVersion(DRAFT) + .withKey(List.of(31)) + .withRelation(relation.getId()) + .withDirection(OntologyStatementDirection.FORWARD) + .withRelatedClass(relatedClass)); + } + + private static OntologyStatementPlan post( + final UUID type, final String statement, final Object request) { + return admin() + .getHttpClient() + .execute( + HttpMethod.POST, + "/v1/ontologyConcepts/" + type + "/statements/" + statement, + request, + OntologyStatementPlan.class); + } + + /** Makes the relation name these classes as its range in the working draft. */ + private static void rangeOf(final OntologyProperty relation, final URI... classes) { + final String id = relation.getId().toString(); + admin() + .ontologyProperties() + .update(id, admin().ontologyProperties().get(id).withRange(List.of(classes))); + } + private static OntologyStatementPlan ask( final OntologyShapeFixture fixture, final OpenMetadataClient client, final String name) { return ask(fixture, client, name, null); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java index 16823cd2223b..382889da8dd9 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java @@ -23,6 +23,7 @@ import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; @@ -197,6 +198,17 @@ void aContributingTableTheReaderMayNotViewLeavesTheStatementAndThePlan() { assertEquals(List.of("crm_customers"), read(open)); } + @Test + void aContributingTableThatAddsNoResultColumnIsNotJoined() { + final RecordStatement open = + open(model(LINK_TABLE, POSTGRES).omit("itemQuantity"), "Order", List.of(1)); + + assertEquals( + "SELECT t0.id, t0.channel\nFROM shop.orders t0\nWHERE t0.id = 1\nLIMIT 101", sql(open)); + assertEquals(List.of("0 key Order part 0", "1 property Order orderChannel"), plan(open)); + assertEquals(List.of("orders"), read(open)); + } + @Test void aKeyTakesOneValueForEachColumnOfTheSubjectKey() { final OntologyMappingShapeModel model = model(COMPOSITE_KEY, POSTGRES); From eea51c820d821823f4beef31291e0a28a5149030 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 12:46:02 -0800 Subject: [PATCH 037/203] Let a change set carry table bindings and shapes, applied as the caller Add UPSERT_BINDING and UPSERT_SHAPE operations, an evidence list and a shape basis to the change operation schema. A binding operation writes through the bindings write path inside the apply transaction, with the rights of whoever applies the set, and stores each join as inferred. A stale or missing baseVersion on a changed binding is a 412 that names the binding. --- .../jdbi3/OntologyConceptBindingStore.java | 19 +- .../NativeOntologyChangeExecutor.java | 23 +- .../ontology/NativeOntologyChanges.java | 61 ++- .../OntologyBindingChangeExecutor.java | 171 ++++++++ .../ontology/OntologyBindingChanges.java | 172 ++++++++ .../ontology/OntologyBindingRules.java | 2 +- .../OntologyChangeApplicationService.java | 113 +++++- .../OntologyChangeOperationExecutor.java | 5 +- .../ontology/OntologyChangePreflight.java | 8 + .../ontology/OntologyChangeSetValidator.java | 31 +- .../OntologyConceptBindingService.java | 49 ++- .../OntologyBindingAndShapeOperationTest.java | 378 ++++++++++++++++++ .../OntologyBindingChangeExecutorTest.java | 112 ++++++ .../OntologyChangeApplicationServiceTest.java | 143 ++++++- .../ontology/OntologyChangePreflightTest.java | 63 +++ .../ontology/OntologySqlValueCasesTest.java | 4 +- .../schema/type/ontologyBindingChange.json | 74 ++++ .../schema/type/ontologyChangeEvidence.json | 41 ++ .../schema/type/ontologyChangeOperation.json | 45 ++- 19 files changed, 1467 insertions(+), 47 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutor.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChanges.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAndShapeOperationTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutorTest.java create mode 100644 openmetadata-spec/src/main/resources/json/schema/type/ontologyBindingChange.json create mode 100644 openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeEvidence.json diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 93c16e2d5b9f..1d63690d0e66 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -13,6 +13,7 @@ import java.util.UUID; import java.util.function.Function; import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; @@ -29,6 +30,7 @@ import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.ConceptAssetCount; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.LiveAsset; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; +import org.openmetadata.service.jdbi3.RdfInfraDAOs.OntologyMemberDAO; import org.openmetadata.service.ontology.OntologyClassHierarchy; import org.openmetadata.service.ontology.OntologyWriteClosureLimits; import org.openmetadata.service.util.FreshReadScope; @@ -132,18 +134,27 @@ public List page( /** The live properties of one ontology declared with these IRIs, in one statement. */ public List liveProperties(final UUID ontologyId, final Collection iris) { - final var properties = dao.ontologyPropertyDAO(); + return declared(dao.ontologyPropertyDAO(), ontologyId, iris); + } + + /** The live concepts of one ontology declared with these IRIs, in one statement. */ + public List liveConcepts(final UUID ontologyId, final Collection iris) { + return declared(dao.ontologyConceptDAO(), ontologyId, iris); + } + + private static List declared( + final OntologyMemberDAO members, final UUID ontologyId, final Collection iris) { return iris.isEmpty() ? List.of() - : properties + : members .findDeclarations( - properties.getTableName(), + members.getTableName(), ontologyId, iris.stream().map(iri -> DigestUtils.md5Hex(iri.toString())).toList(), iris.size(), "") .stream() - .map(json -> JsonUtils.readValue(json, OntologyProperty.class)) + .map(json -> JsonUtils.readValue(json, members.getEntityClass())) .toList(); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChangeExecutor.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChangeExecutor.java index bbf288c47e3b..a04c52deb94f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChangeExecutor.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChangeExecutor.java @@ -9,6 +9,7 @@ import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.Relationship; @@ -23,18 +24,23 @@ public final class NativeOntologyChangeExecutor { private final OntologyEntityRepository concepts; private final OntologyEntityRepository properties; private final OntologyEntityRepository axioms; + private final OntologyEntityRepository shapes; private final Clock clock; + /** The repository of each kind of definition a draft writes. */ + public record Definitions( + OntologyEntityRepository concepts, + OntologyEntityRepository properties, + OntologyEntityRepository axioms, + OntologyEntityRepository shapes) {} + public NativeOntologyChangeExecutor( - final OntologyRepository ontologies, - final OntologyEntityRepository concepts, - final OntologyEntityRepository properties, - final OntologyEntityRepository axioms, - final Clock clock) { + final OntologyRepository ontologies, final Definitions definitions, final Clock clock) { this.ontologies = ontologies; - this.concepts = concepts; - this.properties = properties; - this.axioms = axioms; + this.concepts = definitions.concepts(); + this.properties = definitions.properties(); + this.axioms = definitions.axioms(); + this.shapes = definitions.shapes(); this.clock = clock; } @@ -49,6 +55,7 @@ public OperationOutcome execute( case UPSERT_CONCEPT -> upsert(concepts, operation, uriInfo, user); case UPSERT_PROPERTY -> upsert(properties, operation, uriInfo, user); case UPSERT_AXIOM -> upsert(axioms, operation, uriInfo, user); + case UPSERT_SHAPE -> upsert(shapes, operation, uriInfo, user); case DELETE_CONCEPT -> outcome( concepts.delete(user, operation.getTargetId(), false, false).entity()); case DELETE_PROPERTY -> outcome( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChanges.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChanges.java index 8bad9f81674b..9b0a69cf1aae 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChanges.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChanges.java @@ -4,13 +4,17 @@ import jakarta.ws.rs.BadRequestException; import java.util.HashSet; +import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeOperationState; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyProfileViolation; import org.openmetadata.service.Entity; /** Typed operations share the memory draft lifecycle, but never the glossary model. */ @@ -22,6 +26,7 @@ public static String entityType(final OntologyChangeOperation operation) { case UPSERT_CONCEPT, DELETE_CONCEPT -> Entity.ONTOLOGY_CONCEPT; case UPSERT_PROPERTY, DELETE_PROPERTY -> Entity.ONTOLOGY_PROPERTY; case UPSERT_AXIOM, DELETE_AXIOM -> Entity.ONTOLOGY_AXIOM; + case UPSERT_SHAPE -> Entity.ONTOLOGY_SHAPE; default -> throw new BadRequestException( "Native ontology drafts require definition operations"); }; @@ -39,6 +44,7 @@ public static OntologyDefinition definition(final OntologyChangeOperation operat case UPSERT_CONCEPT -> operation.getConcept(); case UPSERT_PROPERTY -> operation.getProperty(); case UPSERT_AXIOM -> operation.getAxiom(); + case UPSERT_SHAPE -> operation.getShape(); default -> null; }; } @@ -57,7 +63,7 @@ static void validate(final OntologyChangeSet changeSet, final int cursor) { throw new BadRequestException("A native draft accepts at most 1000 operations"); } final Set operationIds = new HashSet<>(); - final Set definitionIds = new HashSet<>(); + final Written written = new Written(new HashSet<>(), new HashSet<>()); for (int index = 0; index < operations.size(); index++) { final OntologyChangeOperation operation = operations.get(index); if (operation == null @@ -66,12 +72,10 @@ static void validate(final OntologyChangeSet changeSet, final int cursor) { || !operationIds.add(operation.getId())) { throw new BadRequestException("Every ontology operation requires a unique id and type"); } - entityType(operation); - validatePayload(changeSet, operation); - final UUID id = - operation.getTargetId() == null ? definition(operation).getId() : operation.getTargetId(); - if (!definitionIds.add(id)) { - throw new BadRequestException("A native draft may change each definition only once"); + if (OntologyBindingChanges.isBinding(operation)) { + validateBinding(operation, written); + } else { + validateDefinition(changeSet, operation, written); } operation.setState( index < cursor @@ -80,6 +84,49 @@ static void validate(final OntologyChangeSet changeSet, final int cursor) { } } + /** What a draft has written so far: each definition and each binding at most once. */ + private record Written(Set definitions, Set bindings) {} + + private static void validateBinding( + final OntologyChangeOperation operation, final Written written) { + OntologyBindingChanges.validate(operation); + if (!written.bindings().add(OntologyBindingChanges.Target.of(operation.getBinding()))) { + throw new BadRequestException("A native draft may write each binding only once"); + } + } + + private static void validateDefinition( + final OntologyChangeSet changeSet, + final OntologyChangeOperation operation, + final Written written) { + entityType(operation); + validatePayload(changeSet, operation); + final UUID id = + operation.getTargetId() == null ? definition(operation).getId() : operation.getTargetId(); + if (!written.definitions().add(id)) { + throw new BadRequestException("A native draft may change each definition only once"); + } + if (operation.getOperationType() == OntologyChangeOperationType.UPSERT_SHAPE) { + requireValidShape(operation); + } + } + + /** The rules a shape passes on its own, so a draft never stores one its apply would refuse. */ + private static void requireValidShape(final OntologyChangeOperation operation) { + final OntologyShape shape = operation.getShape(); + final String relative = + OntologyPropertyRules.relativeIriMessage(shape.getTargetConcept(), "targetConcept"); + if (relative != null) { + throw OntologyChangeSetValidator.invalid(operation, relative); + } + final List findings = OntologyShapeRules.validate(shape); + if (!findings.isEmpty()) { + final OntologyProfileViolation first = findings.getFirst(); + throw OntologyChangeSetValidator.invalid( + operation, first.getPath() + ": " + first.getMessage()); + } + } + private static void validatePayload( final OntologyChangeSet changeSet, final OntologyChangeOperation operation) { final OntologyDefinition definition = definition(operation); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutor.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutor.java new file mode 100644 index 000000000000..6e07aeb6cea4 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutor.java @@ -0,0 +1,171 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.PreconditionFailedException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyChangeOperationExecutor.OperationOutcome; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyConceptBindingService.RevisionGuard; +import org.openmetadata.service.security.Authorizer; + +/** + * Applies the binding operations of a change set. Each one goes through the write path of the + * bindings API as the caller who applies the set, inside the transaction and under the ontology + * lock that the apply already holds, so it can name a class and properties that earlier operations + * of the same set created. A refusal leaves that transaction as the bindings API would answer it. + */ +public final class OntologyBindingChangeExecutor { + private final OntologyConceptBindingService bindings; + private final OntologyConceptBindingStore store; + + public OntologyBindingChangeExecutor( + final OntologyConceptBindingService bindings, final OntologyConceptBindingStore store) { + this.bindings = bindings; + this.store = store; + } + + /** The write path the bindings API uses, deciding rights with the given authorizer. */ + public static OntologyBindingChangeExecutor production(final Authorizer authorizer) { + final OntologyConceptBindingStore store = + new OntologyConceptBindingStore( + Entity.getCollectionDAO(), OntologyConceptBindingStore.registeredAssetTables()); + return new OntologyBindingChangeExecutor( + new OntologyConceptBindingService(store, authorizer, Entity::getEntityRepository), store); + } + + /** + * Starts the binding writes of one attempt to apply a set as {@code caller}. A set is built + * against the bindings it read, so the attempt keeps the binding revision each class had before + * it wrote to that class and judges every operation on the class against that revision. The + * set's own earlier writes to a class therefore never make its later ones stale. + */ + public Function attempt( + final Access caller, final OntologyChangeSet changeSet) { + final Attempt attempt = new Attempt(caller, changeSet, new HashMap<>()); + return operation -> execute(attempt, operation); + } + + /** A binding operation is only ever part of a set that an ontology scopes. */ + private record Attempt( + Access caller, OntologyChangeSet changeSet, Map revisionsBefore) { + private UUID ontologyId() { + return changeSet.getOntology().getId(); + } + } + + private OperationOutcome execute(final Attempt attempt, final OntologyChangeOperation operation) { + final OntologyBindingChange change = operation.getBinding(); + final OntologyConcept concept = requireClass(attempt.ontologyId(), operation); + final Function propertyIds = requireProperties(attempt.ontologyId(), operation); + bindings.replace( + attempt.caller(), + concept.getId(), + OntologyBindingChanges.assetBinding(change, propertyIds), + revisionGuard(operation, concept.getId(), attempt.revisionsBefore())); + return new OperationOutcome(concept.getEntityReference(), null); + } + + private OntologyConcept requireClass( + final UUID ontologyId, final OntologyChangeOperation operation) { + final URI iri = operation.getBinding().getClassIri(); + return store.liveConcepts(ontologyId, List.of(iri)).stream() + .filter(concept -> iri.toString().equals(concept.getIri().toString())) + .findFirst() + .orElseThrow(() -> undeclared(operation, "class", iri)); + } + + private Function requireProperties( + final UUID ontologyId, final OntologyChangeOperation operation) { + final List iris = OntologyBindingChanges.propertyIris(operation.getBinding()); + final Map declared = + store.liveProperties(ontologyId, iris).stream() + .collect( + Collectors.toMap( + property -> property.getIri().toString(), + OntologyProperty::getId, + (first, second) -> first)); + iris.stream() + .filter(iri -> !declared.containsKey(iri.toString())) + .findFirst() + .ifPresent( + iri -> { + throw undeclared(operation, "property", iri); + }); + return iri -> declared.get(iri.toString()); + } + + private static BadRequestException undeclared( + final OntologyChangeOperation operation, final String kind, final URI iri) { + return new BadRequestException( + "Ontology operation '" + + operation.getId() + + "' needs the " + + kind + + " " + + iri + + ", which the ontology does not declare"); + } + + /** + * An operation that carries a revision was built against that revision of the class. One that + * carries none was built when the table was not yet bound to the class. Either way a class whose + * bindings another writer has changed since answers 412 and names the binding, so a client can + * rebuild that one operation. The first changed write of an attempt to a class records the + * revision the class had before the attempt in {@code revisionsBefore}. + */ + static RevisionGuard revisionGuard( + final OntologyChangeOperation operation, + final UUID conceptId, + final Map revisionsBefore) { + final Long built = OntologyBindingChanges.builtAgainst(operation); + return (current, existing) -> { + final long before = revisionsBefore.computeIfAbsent(conceptId, ignored -> current); + final boolean stale = built == null ? existing != null : built != before; + if (stale) { + throw new PreconditionFailedException(staleMessage(operation, built, before)); + } + return OntologyBindingRules.nextRevision(current, current); + }; + } + + private static String staleMessage( + final OntologyChangeOperation operation, final Long built, final long before) { + final OntologyBindingChange change = operation.getBinding(); + return "The binding of class " + + change.getClassIri() + + " to table " + + change.getTableId() + + " changed since operation '" + + operation.getId() + + "' was built: the operation carries " + + (built == null ? "no binding revision" : "binding revision " + built) + + " and the class is at binding revision " + + before; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChanges.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChanges.java new file mode 100644 index 000000000000..b7228d277e68 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChanges.java @@ -0,0 +1,172 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.function.Function; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.sdk.exception.WebServiceException; + +/** + * A table binding as a change set operation carries it: what the operation must look like before + * anything is read, and the binding it writes once its property IRIs have ids. + */ +public final class OntologyBindingChanges { + private OntologyBindingChanges() {} + + /** One table bound to one class. A draft writes each at most once. */ + record Target(String classIri, UUID tableId) { + static Target of(final OntologyBindingChange change) { + return new Target(change.getClassIri().toString(), change.getTableId()); + } + } + + public static boolean isBinding(final OntologyChangeOperation operation) { + return operation.getOperationType() == OntologyChangeOperationType.UPSERT_BINDING; + } + + /** The checks that read nothing: the payload, its IRIs and the binding rules on its fields. */ + static void validate(final OntologyChangeOperation operation) { + final OntologyBindingChange change = requirePayload(operation); + requireAbsolute(operation, change.getClassIri(), "classIri"); + listOrEmpty(change.getColumns()) + .forEach(column -> requireAbsolute(operation, propertyIri(column), "propertyIri")); + requireWholeRevision(operation); + requireBindingRules(operation, change); + } + + private static OntologyBindingChange requirePayload(final OntologyChangeOperation operation) { + final OntologyBindingChange change = operation.getBinding(); + if (change == null || OntologyChangeSetValidator.payloadCount(operation) != 1) { + throw invalid(operation, "operation UPSERT_BINDING requires exactly one binding"); + } + if (operation.getTargetId() != null) { + throw invalid( + operation, "a binding operation names its table in its payload, not in targetId"); + } + if (change.getTableId() == null) { + throw invalid(operation, "a binding requires a tableId"); + } + return change; + } + + /** + * The binding the operation writes, with each property IRI turned into the id {@code propertyIds} + * gives it. Every join is {@code inferred}, because only a person confirms one. + */ + static OntologyAssetBinding assetBinding( + final OntologyBindingChange change, final Function propertyIds) { + return new OntologyAssetBinding() + .withAssetType(OntologyBindingAssetType.TABLE) + .withAssetId(change.getTableId()) + .withRole(change.getRole()) + .withSubjectKey(change.getSubjectKey()) + .withRowFilter(change.getRowFilter()) + .withColumns( + listOrEmpty(change.getColumns()).stream() + .map(column -> columnBinding(column, propertyIds)) + .toList()); + } + + /** The binding revision the operation was built against, or null when it carries none. */ + static Long builtAgainst(final OntologyChangeOperation operation) { + final Double version = operation.getBaseVersion(); + return version == null ? null : version.longValue(); + } + + /** Every IRI the columns of a binding name, in the order they appear. */ + static List propertyIris(final OntologyBindingChange change) { + return listOrEmpty(change.getColumns()).stream() + .map(OntologyColumnBindingChange::getPropertyIri) + .distinct() + .toList(); + } + + private static OntologyColumnBinding columnBinding( + final OntologyColumnBindingChange column, final Function propertyIds) { + return new OntologyColumnBinding() + .withPropertyId(propertyIds.apply(column.getPropertyIri())) + .withColumnPath(column.getColumnPath()) + .withJoin(column.getJoin() == null ? null : inferredJoin(column.getJoin())); + } + + private static OntologyColumnJoin inferredJoin(final OntologyJoinChange join) { + return new OntologyColumnJoin() + .withTargetAssetId(join.getTargetAssetId()) + .withStatus(OntologyJoinStatus.INFERRED) + .withOn(join.getOn()); + } + + private static URI propertyIri(final OntologyColumnBindingChange column) { + return column == null ? null : column.getPropertyIri(); + } + + private static void requireAbsolute( + final OntologyChangeOperation operation, final URI iri, final String field) { + final String message = OntologyPropertyRules.relativeIriMessage(iri, field); + if (message != null) { + throw invalid(operation, message); + } + } + + private static void requireWholeRevision(final OntologyChangeOperation operation) { + final Double version = operation.getBaseVersion(); + final boolean whole = + version == null + || (version >= 0 + && version == Math.rint(version) + && version <= OntologyBindingRules.MAX_REVISION); + if (!whole) { + throw invalid( + operation, "baseVersion is the whole binding revision the operation was built against"); + } + } + + /** + * The rules the bindings API applies to the fields of a binding. They compare properties by id, + * so each IRI stands in as an id derived from its text. + */ + private static void requireBindingRules( + final OntologyChangeOperation operation, final OntologyBindingChange change) { + try { + OntologyBindingRules.validate(assetBinding(change, OntologyBindingChanges::standInId)); + } catch (final WebServiceException refused) { + throw invalid(operation, refused.getMessage()); + } + } + + private static UUID standInId(final URI propertyIri) { + return UUID.nameUUIDFromBytes(propertyIri.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static BadRequestException invalid( + final OntologyChangeOperation operation, final String message) { + return OntologyChangeSetValidator.invalid(operation, message); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java index fd74e3513724..872f23f3c517 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java @@ -37,7 +37,7 @@ public final class OntologyBindingRules { public static final int MAX_FILTER_TEXT_LENGTH = TypedValues.MAX_TEXT_LENGTH; private static final int MAX_PATH_DEPTH = 32; private static final int MAX_SEGMENT_LENGTH = 256; - private static final long MAX_REVISION = 9_007_199_254_740_991L; + static final long MAX_REVISION = 9_007_199_254_740_991L; private static final Set BINDABLE_KINDS = Set.of(OntologyPropertyKind.DATA, OntologyPropertyKind.OBJECT); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeApplicationService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeApplicationService.java index 84b4571591fc..995488a950cf 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeApplicationService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeApplicationService.java @@ -26,6 +26,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.function.Function; import java.util.function.Supplier; import org.apache.commons.codec.digest.DigestUtils; import org.openmetadata.schema.entity.data.OntologyChangeSet; @@ -49,7 +50,9 @@ import org.openmetadata.service.jdbi3.OntologyConceptRepository; import org.openmetadata.service.jdbi3.OntologyPropertyRepository; import org.openmetadata.service.jdbi3.OntologyRepository; +import org.openmetadata.service.jdbi3.OntologyShapeRepository; import org.openmetadata.service.ontology.OntologyChangeOperationExecutor.OperationOutcome; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.ontology.OntologyPackInstallations.PreparedPackInstall; import org.openmetadata.service.util.RestUtil.PutResponse; @@ -76,13 +79,33 @@ public final class OntologyChangeApplicationService { private final OntologyWorkingSnapshot workingSnapshot; private final PackInstallWriter installWriter; private final OntologyPackInstallations.PlanLedger planLedger; + private final BindingWriter bindings; private final Clock clock; + /** For a job, which applies with no caller and so writes no binding. */ public OntologyChangeApplicationService( final OntologyChangeSetRepository changeSetRepository, final GlossaryTermRepository termRepository, final Clock clock) { - this(changeSetRepository, productionDependencies(termRepository, clock), clock); + this( + changeSetRepository, + productionDependencies( + termRepository, + clock, + (caller, changeSet) -> OntologyChangeApplicationService::withoutCaller), + clock); + } + + /** For the change set API, where a caller applies and each binding is written as that caller. */ + public OntologyChangeApplicationService( + final OntologyChangeSetRepository changeSetRepository, + final GlossaryTermRepository termRepository, + final Clock clock, + final OntologyBindingChangeExecutor bindings) { + this( + changeSetRepository, + productionDependencies(termRepository, clock, bindings::attempt), + clock); } OntologyChangeApplicationService( @@ -99,22 +122,56 @@ public OntologyChangeApplicationService( this.workingSnapshot = dependencies.workingSnapshot(); this.installWriter = dependencies.installWriter(); this.planLedger = dependencies.planLedger(); + this.bindings = dependencies.bindings(); this.clock = clock; } + /** Applies with no caller at hand, as a job does. A binding operation is refused. */ public PutResponse apply( final UriInfo uriInfo, final UUID changeSetId, final String user) { + return apply( + requireApplicable(changeSetId), + uriInfo, + user, + () -> OntologyChangeApplicationService::withoutCaller); + } + + /** + * Applies as the caller. Each binding operation is written with the rights this caller holds when + * the set is applied, whoever built the set. + */ + public PutResponse apply(final Access caller, final UUID changeSetId) { final OntologyChangeSet changeSet = requireApplicable(changeSetId); + return apply( + changeSet, + caller.uriInfo(), + caller.securityContext().getUserPrincipal().getName(), + () -> bindings.attempt(caller, changeSet)); + } + + private PutResponse apply( + final OntologyChangeSet changeSet, + final UriInfo uriInfo, + final String user, + final Supplier> bindingAttempt) { final List operations = activeOperations(changeSet); preflight.validate(changeSet, operations); final ApplicationExecution execution = - new ApplicationExecution(uriInfo, changeSetId, user, new ArrayList<>()); + new ApplicationExecution( + uriInfo, changeSet.getId(), user, new ArrayList<>(), bindingAttempt); final PutResponse response = applyOperations(execution, changeSet, operations); publishApplied(response.getEntity(), user); return response; } + private static OperationOutcome withoutCaller(final OntologyChangeOperation operation) { + throw new BadRequestException( + "Ontology operation '" + + operation.getId() + + "' writes a binding, which only a caller of the change set API can apply"); + } + private PutResponse applyOperations( final ApplicationExecution execution, final OntologyChangeSet changeSet, @@ -192,14 +249,33 @@ private PutResponse applyAtomically( return transition(execution, OntologyChangeSetState.APPLIED, result); } + /** The transaction can run this more than once, so each run starts its own binding writes. */ private void executeOperations( final ApplicationExecution execution, final List operations) { + final Function bindingWrite = + execution.bindingAttempt().get(); for (final OntologyChangeOperation operation : operations) { - executeOperation(execution, operation); + executeOperation(execution, bindingWrite, operation); } } + /** + * A binding operation is checked as a request to the bindings API is. A refusal leaves the + * transaction and answers the apply with its own status, so nothing is written and the set keeps + * its state. Any other operation that fails records a failed application. + */ private void executeOperation( + final ApplicationExecution execution, + final Function bindingWrite, + final OntologyChangeOperation operation) { + if (OntologyBindingChanges.isBinding(operation)) { + execution.results().add(appliedResult(operation, bindingWrite.apply(operation))); + } else { + executeDefinition(execution, operation); + } + } + + private void executeDefinition( final ApplicationExecution execution, final OntologyChangeOperation operation) { try { final OperationOutcome outcome = @@ -350,7 +426,9 @@ private static OntologyChangeOperationResult result( } private static Dependencies productionDependencies( - final GlossaryTermRepository termRepository, final Clock clock) { + final GlossaryTermRepository termRepository, + final Clock clock, + final BindingWriter bindings) { return new Dependencies( productionPreflight(), new OntologyChangeOperationExecutor( @@ -359,9 +437,12 @@ private static Dependencies productionDependencies( clock, new NativeOntologyChangeExecutor( (OntologyRepository) Entity.getEntityRepository(Entity.ONTOLOGY), - (OntologyConceptRepository) Entity.getEntityRepository(Entity.ONTOLOGY_CONCEPT), - (OntologyPropertyRepository) Entity.getEntityRepository(Entity.ONTOLOGY_PROPERTY), - (OntologyAxiomRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM), + new NativeOntologyChangeExecutor.Definitions( + (OntologyConceptRepository) Entity.getEntityRepository(Entity.ONTOLOGY_CONCEPT), + (OntologyPropertyRepository) + Entity.getEntityRepository(Entity.ONTOLOGY_PROPERTY), + (OntologyAxiomRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM), + (OntologyShapeRepository) Entity.getEntityRepository(Entity.ONTOLOGY_SHAPE)), clock)), new OntologyChangeEventPublisher(), work -> termRepository.executeInTransaction(work), @@ -372,7 +453,8 @@ private static Dependencies productionDependencies( ((OntologyRepository) Entity.getEntityRepository(Entity.ONTOLOGY)) .recordPackInstallation( install.ontologyId(), install.installation(), install.moduleOrder(), user), - OntologyPackInstallJobManager.ledger(Entity.getJobDAO())); + OntologyPackInstallJobManager.ledger(Entity.getJobDAO()), + bindings); } private static void invalidateEntityCache(final EntityReference entity) { @@ -386,7 +468,7 @@ private static OntologyChangePreflight productionPreflight() { OntologyChangeApplicationService::declaredConcepts); } - private static Set declaredConcepts(final UUID ontologyId, final Set iris) { + public static Set declaredConcepts(final UUID ontologyId, final Set iris) { final var concepts = Entity.getCollectionDAO().ontologyConceptDAO(); final Set declared = new HashSet<>(); Lists.partition(new ArrayList<>(iris), DECLARATION_BATCH) @@ -417,7 +499,15 @@ record Dependencies( OntologyPackCatalog packs, OntologyWorkingSnapshot workingSnapshot, PackInstallWriter installWriter, - OntologyPackInstallations.PlanLedger planLedger) {} + OntologyPackInstallations.PlanLedger planLedger, + BindingWriter bindings) {} + + /** Starts the binding writes of one attempt to apply a set, as the caller who applies it. */ + @FunctionalInterface + interface BindingWriter { + Function attempt( + Access caller, OntologyChangeSet changeSet); + } @FunctionalInterface interface PackInstallWriter { @@ -438,7 +528,8 @@ private record ApplicationExecution( UriInfo uriInfo, UUID changeSetId, String user, - List results) {} + List results, + Supplier> bindingAttempt) {} private static final class OperationApplicationException extends RuntimeException { private OperationApplicationException(final RuntimeException cause) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeOperationExecutor.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeOperationExecutor.java index c56a8dfed26d..2ab6c230ab23 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeOperationExecutor.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeOperationExecutor.java @@ -92,7 +92,10 @@ public OperationOutcome execute( UPSERT_PROPERTY, DELETE_PROPERTY, UPSERT_AXIOM, - DELETE_AXIOM -> nativeExecutor().execute(uriInfo, user, operation); + DELETE_AXIOM, + UPSERT_SHAPE -> nativeExecutor().execute(uriInfo, user, operation); + case UPSERT_BINDING -> throw new BadRequestException( + "A binding operation is written through the bindings of its class, as a caller"); }; return outcome; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangePreflight.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangePreflight.java index e3214c96aed3..0223d018ac91 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangePreflight.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangePreflight.java @@ -149,6 +149,12 @@ private static Set classPositions( + "' has a class expression with more than 10000 steps"); }); case UPSERT_PROPERTY -> OntologyClassHierarchy.classPositions(operation.getProperty()); + case UPSERT_BINDING -> List.of( + new OntologyClassHierarchy.ClassPosition( + "/binding/classIri", operation.getBinding().getClassIri())); + case UPSERT_SHAPE -> List.of( + new OntologyClassHierarchy.ClassPosition( + "/shape/targetConcept", operation.getShape().getTargetConcept())); default -> List.of(); }; return positions.stream() @@ -232,6 +238,8 @@ private void validateScope( UPSERT_AXIOM, DELETE_AXIOM -> throw new BadRequestException( "Axioms must be authored in an ontology, not a glossary change set"); + case UPSERT_BINDING, UPSERT_SHAPE -> throw new BadRequestException( + "Bindings and shapes must be authored in an ontology, not a glossary change set"); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetValidator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetValidator.java index 1d8fa2a8cf73..ad837b0cbfa7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetValidator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetValidator.java @@ -42,10 +42,35 @@ public static void normalizeAndValidate(final OntologyChangeSet changeSet) { } else { validateOperations(operations, cursor, plannedTermIds(operations)); } + operations.forEach(OntologyChangeSetValidator::normalizeSupport); changeSet.setOperations(operations); changeSet.setUndoCursor(cursor); } + /** + * What an operation may carry beside its payload. A basis says where a shape comes from, so only + * a shape operation takes one. The count of withheld evidence belongs to a read and is dropped, + * so it is never stored. An empty evidence list is stored as no evidence, so the two never + * differ in a recorded change. + */ + private static void normalizeSupport(final OntologyChangeOperation operation) { + if (operation.getBasis() != null + && operation.getOperationType() != OntologyChangeOperationType.UPSERT_SHAPE) { + throw invalid(operation, "only a shape operation carries a basis"); + } + final boolean incomplete = + listOrEmpty(operation.getEvidence()).stream() + .anyMatch( + entry -> entry == null || entry.getTableId() == null || entry.getKind() == null); + if (incomplete) { + throw invalid(operation, "every evidence entry names a table and a kind"); + } + if (listOrEmpty(operation.getEvidence()).isEmpty()) { + operation.setEvidence(null); + } + operation.setWithheldEvidenceCount(null); + } + private static void validateOperations( final List operations, final int cursor, @@ -162,6 +187,8 @@ static int payloadCount(final OntologyChangeOperation operation) { count += operation.getAxiom() == null ? 0 : 1; count += operation.getConcept() == null ? 0 : 1; count += operation.getProperty() == null ? 0 : 1; + count += operation.getBinding() == null ? 0 : 1; + count += operation.getShape() == null ? 0 : 1; return count; } @@ -299,11 +326,13 @@ private static PayloadKind payloadKind(final OntologyChangeOperationType operati UPSERT_AXIOM, DELETE_AXIOM -> throw new BadRequestException( "Axioms must be authored in an ontology, not a glossary change set"); + case UPSERT_BINDING, UPSERT_SHAPE -> throw new BadRequestException( + "Bindings and shapes must be authored in an ontology, not a glossary change set"); }; return payloadKind; } - private static BadRequestException invalid( + static BadRequestException invalid( final OntologyChangeOperation operation, final String message) { return new BadRequestException( "Ontology operation '" + operation.getId() + "' is invalid: " + message); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java index dd395fdb745a..6d955db9a6af 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java @@ -22,6 +22,7 @@ import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyAssetConceptLink; import org.openmetadata.schema.type.OntologyAssetConceptLinks; import org.openmetadata.schema.type.OntologyBindingAssetType; @@ -57,6 +58,20 @@ public final class OntologyConceptBindingService { public record Access(UriInfo uriInfo, SecurityContext securityContext) {} + /** + * How a changed write proves that it saw the bindings it replaces. It is asked under the ontology + * lock, after the writer's rights on the concept and the asset are checked and before the checks + * of a table binding, with the concept's current revision and the stored binding of the asset, if + * any. It returns the revision the write commits or refuses the write. + */ + @FunctionalInterface + public interface RevisionGuard { + long next(long current, BindingRow existing); + } + + /** One binding to write and the guard that admits it. */ + private record Replacement(OntologyAssetBinding asset, RevisionGuard guard) {} + public OntologyConceptBindingService( final OntologyConceptBindingStore store, final Authorizer authorizer, @@ -141,13 +156,35 @@ public OntologyConceptBindingsResponse put( throw new BadRequestException("A binding update is required"); } OntologyBindingRules.requireRevision(request.getExpectedRevision()); - OntologyBindingRules.validate(request.getAsset()); + final RevisionGuard sawExpectedRevision = + (current, existing) -> + OntologyBindingRules.nextRevision(current, request.getExpectedRevision()); + return firstPage( + access, write(access, conceptId, new Replacement(request.getAsset(), sawExpectedRevision))); + } + + /** + * Adds or replaces the binding of one asset as {@code access} and keeps the concept's other + * bindings. It is {@link #put} without the page it answers with, for a writer that names its own + * guard. Called inside a transaction, it joins that transaction and the ontology lock it holds. + */ + public void replace( + final Access access, + final UUID conceptId, + final OntologyAssetBinding asset, + final RevisionGuard guard) { + write(access, conceptId, new Replacement(asset, guard)); + } + + private OntologyConcept write( + final Access access, final UUID conceptId, final Replacement replacement) { + OntologyBindingRules.validate(replacement.asset()); final var concept = concept(access, conceptId, MetadataOperation.EDIT_ALL); store.update( concept, (lockedConcept, locked, current) -> - replace(access, lockedConcept, locked, current, request)); - return firstPage(access, concept); + replace(access, lockedConcept, locked, current, replacement)); + return concept; } public OntologyConceptBindingsResponse remove( @@ -180,9 +217,9 @@ private long replace( final OntologyConcept concept, final OntologyConceptBindingStore locked, final long current, - final UpdateOntologyConceptBinding request) { + final Replacement replacement) { concept(access, concept.getId(), MetadataOperation.EDIT_ALL); - final var asset = request.getAsset(); + final var asset = replacement.asset(); final var target = targets.authorized( access, asset.getAssetType().value(), asset.getAssetId(), MetadataOperation.VIEW_BASIC); @@ -190,7 +227,7 @@ private long replace( if (existing != null && OntologyBindingRules.sameBinding(existing, asset)) { return current; } - final long next = OntologyBindingRules.nextRevision(current, request.getExpectedRevision()); + final long next = replacement.guard().next(current, existing); final int retained = prune(locked, concept.getId(), asset.getAssetId()); OntologyBindingRules.requireColumnCapacity(retained + listOrEmpty(asset.getColumns()).size()); if (target instanceof Table table) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAndShapeOperationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAndShapeOperationTest.java new file mode 100644 index 000000000000..d1700570d034 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAndShapeOperationTest.java @@ -0,0 +1,378 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationState; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeBasis; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.utils.JsonUtils; + +/** The rules a change set applies to binding and shape operations whenever it is saved. */ +class OntologyBindingAndShapeOperationTest { + private static final UUID ONTOLOGY_ID = UUID.fromString("2ecf752a-956d-4a44-95ec-cce029f5c1d7"); + private static final UUID OPERATION_ID = UUID.fromString("7a1c0f5e-3f0b-4f43-9a5c-6a0d6de0b001"); + private static final UUID TABLE_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0002"); + private static final UUID ORDERS_TABLE_ID = + UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0003"); + private static final URI CUSTOMER = URI.create("https://example.org/sales/Customer"); + private static final URI EMAIL = URI.create("https://example.org/sales/email"); + private static final URI PLACED = URI.create("https://example.org/sales/placed"); + private static final String REFUSED = "Ontology operation '" + OPERATION_ID + "' is invalid: "; + + @Test + void aDraftCarriesAClassAPropertyABindingAndAShape() { + final OntologyChangeSet draft = + draft( + classOperation(), + propertyOperation(), + binding(change -> {}), + shape(shape -> {}).withId(UUID.randomUUID())); + + OntologyChangeSetValidator.normalizeAndValidate(draft); + + assertEquals( + List.of( + OntologyChangeOperationState.ACTIVE, + OntologyChangeOperationState.ACTIVE, + OntologyChangeOperationState.ACTIVE, + OntologyChangeOperationState.ACTIVE), + draft.getOperations().stream().map(OntologyChangeOperation::getState).toList()); + } + + @Test + void aBindingOperationRequiresItsBindingAndNoOtherPayload() { + final OntologyChangeOperation missing = binding(change -> {}).withBinding(null); + final OntologyChangeOperation two = + binding(change -> {}).withConcept(classOperation().getConcept()); + + assertRefused(REFUSED + "operation UPSERT_BINDING requires exactly one binding", missing); + assertRefused(REFUSED + "operation UPSERT_BINDING requires exactly one binding", two); + } + + @Test + void aBindingOperationNamesItsTableInItsPayload() { + assertRefused( + REFUSED + "a binding operation names its table in its payload, not in targetId", + binding(change -> {}).withTargetId(TABLE_ID)); + assertRefused( + REFUSED + "a binding requires a tableId", binding(change -> change.setTableId(null))); + } + + @Test + void aBindingNamesItsClassAndPropertiesByAbsoluteIri() { + assertRefused( + REFUSED + "Ontology classIri must be an absolute IRI", + binding(change -> change.setClassIri(URI.create("Customer")))); + assertRefused( + REFUSED + "Ontology classIri must be an absolute IRI", + binding(change -> change.setClassIri(null))); + assertRefused( + REFUSED + "Ontology propertyIri must be an absolute IRI", + binding(change -> change.getColumns().getFirst().setPropertyIri(URI.create("email")))); + } + + @Test + void aBindingRevisionIsAWholeNumber() { + assertRefused( + REFUSED + "baseVersion is the whole binding revision the operation was built against", + binding(change -> {}).withBaseVersion(1.5)); + assertRefused( + REFUSED + "baseVersion is the whole binding revision the operation was built against", + binding(change -> {}).withBaseVersion(-1.0)); + + final OntologyChangeSet draft = draft(binding(change -> {}).withBaseVersion(3.0)); + OntologyChangeSetValidator.normalizeAndValidate(draft); + assertEquals(3L, OntologyBindingChanges.builtAgainst(draft.getOperations().getFirst())); + } + + @Test + void aBindingPassesTheRulesOfTheBindingsApiOnItsFields() { + assertRefused( + REFUSED + + "A role and a subject key are set together. A binding with a role names its key columns, and a binding without a role names none", + binding(change -> change.setSubjectKey(null))); + assertRefused( + REFUSED + "Duplicate property and column bindings are not allowed", + binding( + change -> + change.setColumns( + List.of(column(EMAIL, "email", null), column(EMAIL, "email", null))))); + assertRefused( + REFUSED + "A join requires a target table, a status and 1 to 16 distinct column pairs", + binding( + change -> + change.setColumns( + List.of( + column( + PLACED, + "customer_id", + new OntologyJoinChange() + .withTargetAssetId(ORDERS_TABLE_ID) + .withOn(List.of())))))); + assertRefused( + REFUSED + + "A row filter compares with a string of at most 1024 characters, a number or a boolean. `in` takes a list of 1 to 100 of them, and `isNull` and `isNotNull` take no value", + binding( + change -> + change.setRowFilter( + new OntologyRowFilter() + .withColumn(List.of("status")) + .withOperator(OntologyRowFilterOperator.IS_NULL) + .withValue("active")))); + assertRefused( + REFUSED + "Column paths require 1 to 32 nonblank name segments of at most 256 characters", + binding(change -> change.setSubjectKey(List.of(List.of(" "))))); + } + + @Test + void aDraftWritesEachBindingOnce() { + final OntologyChangeOperation second = binding(change -> {}).withId(UUID.randomUUID()); + final OntologyChangeOperation otherTable = + binding(change -> change.setTableId(ORDERS_TABLE_ID)).withId(UUID.randomUUID()); + + assertRefused("A native draft may write each binding only once", binding(change -> {}), second); + OntologyChangeSetValidator.normalizeAndValidate(draft(binding(change -> {}), otherTable)); + } + + @Test + void aShapeNamesItsTargetClassByAbsoluteIriAndPassesTheShapeRules() { + assertRefused( + REFUSED + "Ontology targetConcept must be an absolute IRI", + shape(shape -> shape.setTargetConcept(URI.create("Customer")))); + assertRefused( + REFUSED + + "/constraints/0: A constraint states at least one of minCount, maxCount, classIri, datatypeIri, minInclusive, maxInclusive, in or pattern", + shape( + shape -> + shape.setConstraints( + List.of(new OntologyShapeConstraint().withId("email").withPath(EMAIL))))); + } + + @Test + void onlyAShapeOperationCarriesABasis() { + assertRefused( + REFUSED + "only a shape operation carries a basis", + binding(change -> {}).withBasis(OntologyShapeBasis.OBSERVED)); + + final OntologyChangeSet draft = + draft(shape(shape -> {}).withBasis(OntologyShapeBasis.DECLARED)); + OntologyChangeSetValidator.normalizeAndValidate(draft); + assertEquals(OntologyShapeBasis.DECLARED, draft.getOperations().getFirst().getBasis()); + } + + @Test + void anEvidenceEntryNamesATableAndAKind() { + assertRefused( + REFUSED + "every evidence entry names a table and a kind", + binding(change -> {}) + .withEvidence( + List.of(new OntologyChangeEvidence().withKind(OntologyChangeEvidenceKind.NAME)))); + assertRefused( + REFUSED + "every evidence entry names a table and a kind", + binding(change -> {}) + .withEvidence(List.of(new OntologyChangeEvidence().withTableId(TABLE_ID)))); + } + + @Test + void anOperationCarriesEvidenceOfEveryKindInTheClosedList() { + final List kinds = + List.of( + "declaredKey", + "storedJoinCount", + "testCase", + "lineage", + "profile", + "name", + "sampleData", + "measured"); + assertEquals( + kinds, + Arrays.stream(OntologyChangeEvidenceKind.values()) + .map(OntologyChangeEvidenceKind::value) + .toList()); + final OntologyChangeSet draft = + draft( + binding(change -> {}) + .withEvidence( + kinds.stream() + .map( + kind -> + new OntologyChangeEvidence() + .withTableId(TABLE_ID) + .withColumns(List.of(List.of("customer_id"))) + .withKind(OntologyChangeEvidenceKind.fromValue(kind))) + .toList())); + + OntologyChangeSetValidator.normalizeAndValidate(draft); + + assertEquals( + kinds, + JsonUtils.readTree(JsonUtils.pojoToJson(draft.getOperations().getFirst())) + .path("evidence") + .findValuesAsText("kind")); + } + + @Test + void aSaveNeverStoresACountOfWithheldEvidence() { + final OntologyChangeSet draft = draft(binding(change -> {}).withWithheldEvidenceCount(4)); + + OntologyChangeSetValidator.normalizeAndValidate(draft); + + assertNull(draft.getOperations().getFirst().getWithheldEvidenceCount()); + } + + @Test + void anEmptyEvidenceListIsStoredAsNoEvidence() { + final OntologyChangeSet draft = draft(binding(change -> {}).withEvidence(List.of())); + + OntologyChangeSetValidator.normalizeAndValidate(draft); + + assertNull(draft.getOperations().getFirst().getEvidence()); + } + + @Test + void aGlossaryChangeSetTakesNoBindingOrShape() { + final OntologyChangeSet glossaryDraft = + new OntologyChangeSet() + .withGlossaries( + List.of(new EntityReference().withId(UUID.randomUUID()).withType("glossary"))) + .withOperations(List.of(binding(change -> {}))) + .withUndoCursor(1); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> OntologyChangeSetValidator.normalizeAndValidate(glossaryDraft)); + + assertEquals( + "Bindings and shapes must be authored in an ontology, not a glossary change set", + refusal.getMessage()); + } + + private static void assertRefused( + final String expected, final OntologyChangeOperation... operations) { + final OntologyChangeSet draft = draft(operations); + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> OntologyChangeSetValidator.normalizeAndValidate(draft)); + assertEquals(expected, refusal.getMessage()); + } + + private static OntologyChangeSet draft(final OntologyChangeOperation... operations) { + return new OntologyChangeSet() + .withOntology(ontology()) + .withBaseWorkingRevision(0L) + .withOperations(List.of(operations)) + .withUndoCursor(operations.length); + } + + private static EntityReference ontology() { + return new EntityReference().withId(ONTOLOGY_ID).withType("ontology"); + } + + private static OntologyChangeOperation classOperation() { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withConcept( + new OntologyConcept() + .withId(UUID.randomUUID()) + .withName("Customer") + .withIri(CUSTOMER) + .withOntology(ontology())); + } + + private static OntologyChangeOperation propertyOperation() { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_PROPERTY) + .withProperty( + new OntologyProperty() + .withId(UUID.randomUUID()) + .withName("email") + .withIri(EMAIL) + .withKind(OntologyPropertyKind.DATA) + .withOntology(ontology())); + } + + /** An identity binding of the customer table, changed by {@code edit} before it is sent. */ + private static OntologyChangeOperation binding(final Consumer edit) { + final OntologyBindingChange change = + new OntologyBindingChange() + .withClassIri(CUSTOMER) + .withTableId(TABLE_ID) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("customer_id"))) + .withColumns(List.of(column(EMAIL, "email", null))); + edit.accept(change); + return new OntologyChangeOperation() + .withId(OPERATION_ID) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding(change); + } + + private static OntologyColumnBindingChange column( + final URI propertyIri, final String column, final OntologyJoinChange join) { + return new OntologyColumnBindingChange() + .withPropertyIri(propertyIri) + .withColumnPath(List.of(column)) + .withJoin(join); + } + + /** A shape on the customer class, changed by {@code edit} before it is sent. */ + private static OntologyChangeOperation shape(final Consumer edit) { + final OntologyShape shape = + new OntologyShape() + .withId(UUID.randomUUID()) + .withName("CustomerShape") + .withOntology(ontology()) + .withTargetConcept(CUSTOMER) + .withConstraints( + List.of( + new OntologyShapeConstraint().withId("email").withPath(EMAIL).withMinCount(1))); + edit.accept(shape); + return new OntologyChangeOperation() + .withId(OPERATION_ID) + .withOperationType(OntologyChangeOperationType.UPSERT_SHAPE) + .withShape(shape); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutorTest.java new file mode 100644 index 000000000000..4ea26d44b8ac --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutorTest.java @@ -0,0 +1,112 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.service.exception.PreconditionFailedException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; + +/** Which binding revision a binding operation must have been built against to be written. */ +class OntologyBindingChangeExecutorTest { + private static final UUID OPERATION_ID = UUID.fromString("7a1c0f5e-3f0b-4f43-9a5c-6a0d6de0b001"); + private static final UUID TABLE_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0002"); + private static final UUID CLASS_ID = UUID.fromString("5b0e7a52-9d1c-4f0e-b7a1-2c3d4e5f0003"); + private static final BindingRow BOUND = + new BindingRow( + UUID.randomUUID(), TABLE_ID, OntologyBindingAssetType.TABLE, "hash", List.of()); + private static final String STALE = + "The binding of class https://example.org/sales/Customer to table " + + TABLE_ID + + " changed since operation '" + + OPERATION_ID + + "' was built: the operation carries "; + + @Test + void anOperationBuiltAgainstTheCurrentRevisionCommitsTheNextOne() { + assertEquals(4L, guard(3.0).next(3L, BOUND)); + assertEquals(1L, guard(0.0).next(0L, null)); + } + + @Test + void anOperationThatBindsANewTableCarriesNoRevision() { + assertEquals(8L, guard(null).next(7L, null)); + } + + @Test + void aSetThatWritesTwoBindingsOfOneClassIsJudgedAgainstTheRevisionBeforeItsFirstWrite() { + final Map revisionsBefore = new HashMap<>(); + + assertEquals(4L, guard(3.0, revisionsBefore).next(3L, BOUND)); + assertEquals(5L, guard(3.0, revisionsBefore).next(4L, BOUND)); + assertEquals(6L, guard(null, revisionsBefore).next(5L, null)); + final PreconditionFailedException refusal = + assertThrows( + PreconditionFailedException.class, () -> guard(2.0, revisionsBefore).next(6L, BOUND)); + + assertEquals( + STALE + "binding revision 2 and the class is at binding revision 3", refusal.getMessage()); + } + + @Test + void anOperationBuiltAgainstAnEarlierRevisionIsRefusedWithItsBindingNamed() { + final PreconditionFailedException refusal = + assertThrows(PreconditionFailedException.class, () -> guard(3.0).next(4L, BOUND)); + + assertEquals( + STALE + "binding revision 3 and the class is at binding revision 4", refusal.getMessage()); + assertEquals(412, refusal.getResponse().getStatus()); + } + + @Test + void anOperationBuiltBeforeItsTableWasBoundIsRefusedOnceTheTableIsBound() { + final PreconditionFailedException refusal = + assertThrows(PreconditionFailedException.class, () -> guard(null).next(2L, BOUND)); + + assertEquals( + STALE + "no binding revision and the class is at binding revision 2", refusal.getMessage()); + assertEquals(412, refusal.getResponse().getStatus()); + } + + /** The guard of an operation that is the first of its set to write to the class. */ + private static OntologyConceptBindingService.RevisionGuard guard(final Double builtAgainst) { + return guard(builtAgainst, new HashMap<>()); + } + + private static OntologyConceptBindingService.RevisionGuard guard( + final Double builtAgainst, final Map revisionsBefore) { + return OntologyBindingChangeExecutor.revisionGuard( + new OntologyChangeOperation() + .withId(OPERATION_ID) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBaseVersion(builtAgainst) + .withBinding( + new OntologyBindingChange() + .withClassIri(URI.create("https://example.org/sales/Customer")) + .withTableId(TABLE_ID)), + CLASS_ID, + revisionsBefore); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeApplicationServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeApplicationServiceTest.java index abac8f716d9e..dd2979cf8189 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeApplicationServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeApplicationServiceTest.java @@ -30,12 +30,17 @@ import jakarta.ws.rs.BadRequestException; import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; import jakarta.ws.rs.core.UriInfo; +import java.net.URI; +import java.security.Principal; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.function.Function; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,17 +50,21 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EventType; import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.OntologyBindingChange; import org.openmetadata.schema.type.OntologyChangeApplicationResult; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeOperationResult; import org.openmetadata.schema.type.OntologyChangeOperationResultStatus; import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.type.OntologyChangeSetState; +import org.openmetadata.service.exception.PreconditionFailedException; import org.openmetadata.service.jdbi3.OntologyChangeSetRepository; +import org.openmetadata.service.ontology.OntologyChangeApplicationService.BindingWriter; import org.openmetadata.service.ontology.OntologyChangeApplicationService.ChangeTransaction; import org.openmetadata.service.ontology.OntologyChangeApplicationService.Dependencies; import org.openmetadata.service.ontology.OntologyChangeApplicationService.EntityCacheInvalidator; import org.openmetadata.service.ontology.OntologyChangeOperationExecutor.OperationOutcome; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.util.RestUtil.PutResponse; class OntologyChangeApplicationServiceTest { @@ -73,6 +82,9 @@ class OntologyChangeApplicationServiceTest { private final EntityCacheInvalidator cacheInvalidator = mock(EntityCacheInvalidator.class); private final Clock clock = Clock.fixed(Instant.ofEpochMilli(NOW), ZoneOffset.UTC); private final OntologyChangeOperation operation = operation(); + private final List bindingWrites = new ArrayList<>(); + private BindingWriter bindingWriter = this::recordingAttempt; + private int bindingAttempts; private OntologyChangeSet changeSet; private OntologyChangeApplicationService service; @@ -107,7 +119,8 @@ void setUp() { OntologyPackCatalog.bundled(), null, (install, user) -> {}, - (jobId, ontologyId) -> null); + (jobId, ontologyId) -> null, + (caller, applied) -> bindingWriter.attempt(caller, applied)); service = new OntologyChangeApplicationService(repository, dependencies, clock); } @@ -204,6 +217,122 @@ void retriesEveryOperationAfterAnAtomicFailure() { verify(executor).execute(uriInfo, USER, operation); } + @Test + void writesABindingAsTheCallerWhoAppliesInsideTheTransaction() { + final OntologyChangeOperation binding = bindingOperation(); + final UUID ontologyId = nativeDraftOf(binding); + final Access caller = caller(); + + final OntologyChangeSet applied = service.apply(caller, changeSetId).getEntity(); + + assertEquals(OntologyChangeSetState.APPLIED, applied.getState()); + assertEquals(List.of(new BindingWrite(caller, ontologyId, binding, true)), bindingWrites); + assertEquals( + List.of(OntologyChangeOperationResultStatus.APPLIED), + applied.getApplicationResult().getResults().stream() + .map(OntologyChangeOperationResult::getStatus) + .toList()); + assertEquals(USER, applied.getApplicationResult().getAppliedBy()); + verify(executor, never()).execute(any(), any(), any()); + } + + @Test + void aRefusedBindingAnswersTheApplyAndRecordsNoFailedApplication() { + nativeDraftOf(bindingOperation()); + bindingWriter = + (caller, applied) -> + written -> { + throw new PreconditionFailedException("the binding changed"); + }; + + final PreconditionFailedException refused = + assertThrows(PreconditionFailedException.class, () -> service.apply(caller(), changeSetId)); + + assertEquals("the binding changed", refused.getMessage()); + assertEquals(OntologyChangeSetState.DRAFT, changeSet.getState()); + assertFalse(transaction.isActive()); + verify(repository, never()).transition(any(), any(), any(), any(), any()); + verify(eventPublisher, never()).publish(any(), any(), any()); + } + + @Test + void eachRunOfTheTransactionStartsItsOwnBindingWrites() { + final OntologyChangeOperation binding = bindingOperation(); + final UUID ontologyId = nativeDraftOf(binding); + final Access caller = caller(); + transaction.runTwiceAsAfterADeadlock(); + + final OntologyChangeSet applied = service.apply(caller, changeSetId).getEntity(); + + assertEquals(2, bindingAttempts); + assertEquals( + List.of( + new BindingWrite(caller, ontologyId, binding, true), + new BindingWrite(caller, ontologyId, binding, true)), + bindingWrites); + assertEquals(1, applied.getApplicationResult().getResults().size()); + } + + @Test + void anApplyWithNoCallerWritesNoBinding() { + final OntologyChangeOperation binding = bindingOperation(); + nativeDraftOf(binding); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> service.apply(uriInfo, changeSetId, USER)); + + assertEquals( + "Ontology operation '" + + binding.getId() + + "' writes a binding, which only a caller of the change set API can apply", + refused.getMessage()); + assertEquals(List.of(), bindingWrites); + verify(repository, never()).transition(any(), any(), any(), any(), any()); + } + + /** Turns the draft into one of an ontology that holds this one operation, and returns its id. */ + private UUID nativeDraftOf(final OntologyChangeOperation only) { + final UUID ontologyId = UUID.randomUUID(); + changeSet.setGlossaries(List.of()); + changeSet.setOntology(new EntityReference().withId(ontologyId).withType("ontology")); + changeSet.setBaseWorkingRevision(0L); + changeSet.setOperations(List.of(only)); + when(executor.inScope(eq(changeSet), any())) + .thenAnswer(invocation -> invocation.>getArgument(1).get()); + return ontologyId; + } + + private Access caller() { + final SecurityContext securityContext = mock(SecurityContext.class); + final Principal principal = mock(Principal.class); + when(principal.getName()).thenReturn(USER); + when(securityContext.getUserPrincipal()).thenReturn(principal); + return new Access(uriInfo, securityContext); + } + + private Function recordingAttempt( + final Access caller, final OntologyChangeSet applied) { + bindingAttempts++; + return written -> { + bindingWrites.add( + new BindingWrite(caller, applied.getOntology().getId(), written, transaction.isActive())); + return new OperationOutcome(new EntityReference().withId(UUID.randomUUID()), null); + }; + } + + private record BindingWrite( + Access caller, UUID ontologyId, OntologyChangeOperation operation, boolean inTransaction) {} + + private static OntologyChangeOperation bindingOperation() { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding( + new OntologyBindingChange() + .withClassIri(URI.create("https://example.org/sales/Customer")) + .withTableId(UUID.randomUUID())); + } + private OntologyChangeSet changeSet(final OntologyChangeApplicationResult result) { return new OntologyChangeSet() .withId(changeSetId) @@ -233,21 +362,29 @@ private static PutResponse response(final OntologyChangeSet c private static final class RecordingTransaction implements ChangeTransaction { private boolean active; private int executionCount; + private int runs = 1; @Override public PutResponse execute( final Supplier> work) { - PutResponse result; + PutResponse result = null; active = true; executionCount++; try { - result = work.get(); + for (int run = 0; run < runs; run++) { + result = work.get(); + } } finally { active = false; } return result; } + /** A transaction that loses a deadlock rolls back and runs its work again. */ + private void runTwiceAsAfterADeadlock() { + runs = 2; + } + private boolean isActive() { return active; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangePreflightTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangePreflightTest.java index d3e09a0f5ea3..907c84b3a739 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangePreflightTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangePreflightTest.java @@ -32,8 +32,10 @@ import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyBindingChange; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.type.OntologyExpression; @@ -165,6 +167,67 @@ void acceptsAPropertyRangedOverAnXsdDatatypeAndDomainedOnACreatedConcept() { () -> preflightWithoutConcepts().validate(nativeChangeSet(), List.of(concept, property))); } + @Test + void refusesABindingWhoseClassIsNeitherDeclaredNorCreatedByTheSet() { + final URI account = URI.create("https://example.org/Account"); + + assertNeedsConcept(bindingOf(account), account.toString()); + } + + @Test + void refusesAShapeWhoseTargetClassIsNeitherDeclaredNorCreatedByTheSet() { + final URI account = URI.create("https://example.org/Account"); + + assertNeedsConcept(shapeOn(account), account.toString()); + } + + @Test + void acceptsABindingAndAShapeOnAClassTheSetCreates() { + final URI account = URI.create("https://example.org/Account"); + + assertDoesNotThrow( + () -> + preflightWithoutConcepts() + .validate( + nativeChangeSet(), + List.of(upsertConcept(account), bindingOf(account), shapeOn(account)))); + } + + @Test + void refusesABindingInAGlossaryChangeSet() { + final OntologyChangeSet glossaryChangeSet = + new OntologyChangeSet() + .withGlossaries(List.of(new EntityReference().withId(UUID.randomUUID()))); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> + preflightWithoutConcepts() + .validate( + glossaryChangeSet, + List.of(bindingOf(URI.create("https://example.org/Account"))))); + + assertEquals( + "Bindings and shapes must be authored in an ontology, not a glossary change set", + refusal.getMessage()); + } + + private static OntologyChangeOperation bindingOf(final URI classIri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding( + new OntologyBindingChange().withClassIri(classIri).withTableId(UUID.randomUUID())); + } + + private static OntologyChangeOperation shapeOn(final URI classIri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_SHAPE) + .withShape(new OntologyShape().withId(UUID.randomUUID()).withTargetConcept(classIri)); + } + private static OntologyChangePreflight preflightWithoutConcepts() { return new OntologyChangePreflight( (entityType, id) -> { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologySqlValueCasesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologySqlValueCasesTest.java index cb11ee008712..9b66acfa4c62 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologySqlValueCasesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologySqlValueCasesTest.java @@ -199,7 +199,7 @@ void everyServiceTypeACaseNamesBelongsToTheFamilyOfThatCase() throws IOException * Constraint values belong to the tests generated from shapes and stored counts to the job that * stores them. Neither exists in this code. A write the authorizer refuses needs a server and a * caller without the right, so OntologyRowFilterValueIT runs those cases. One of them writes - * through a change set, and no change set operation writes a binding. + * through a change set, and OntologyChangeSetBindingIT applies that change set. */ private static void skipWhatAnotherTestOwns(final Run run) { if (run.kind().startsWith("constraintValue ")) { @@ -212,7 +212,7 @@ private static void skipWhatAnotherTestOwns(final Run run) { abort( run.json().at("/input/via").isMissingNode() ? "OntologyRowFilterValueIT sends this write as a caller without the right" - : "No change set operation writes a binding"); + : "OntologyChangeSetBindingIT applies this change set as a caller without the right"); } } diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyBindingChange.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyBindingChange.json new file mode 100644 index 000000000000..f8c7f11f6d44 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyBindingChange.json @@ -0,0 +1,74 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyBindingChange.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyBindingChange", + "description": "One table binding of one class, as a change set operation carries it. The class and each property are named by IRI, so the operation can refer to definitions that the same change set creates. Applying it adds or replaces the binding of this table and keeps the other bindings of the class.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyBindingChange", + "definitions": { + "join": { + "description": "How a column bound to an OBJECT property reaches the table that holds the related records. It carries no status. A join that a change set writes is stored as `inferred`, and only a write through the bindings API confirms one.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyJoinChange", + "properties": { + "targetAssetId": { + "description": "The table that holds the related records. It sits in the same database as the bound table.", + "$ref": "basic.json#/definitions/uuid" + }, + "on": { + "type": "array", + "items": { "$ref": "ontologyConceptBindings.json#/definitions/joinColumnPair" }, + "minItems": 1, + "maxItems": 16 + } + }, + "required": ["targetAssetId", "on"], + "additionalProperties": false + }, + "columnBinding": { + "description": "One property bound to one column of the table.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyColumnBindingChange", + "properties": { + "propertyIri": { + "description": "Full IRI of a DATA or OBJECT property of the ontology.", + "$ref": "ontologyIri.json" + }, + "columnPath": { "$ref": "ontologyConceptBindings.json#/definitions/columnPath" }, + "join": { + "description": "Required when the property is an OBJECT property, and not allowed otherwise.", + "$ref": "#/definitions/join" + } + }, + "required": ["propertyIri", "columnPath"], + "additionalProperties": false + } + }, + "properties": { + "classIri": { + "description": "Full IRI of the class the table is bound to.", + "$ref": "ontologyIri.json" + }, + "tableId": { + "description": "The table that holds records of the class.", + "$ref": "basic.json#/definitions/uuid" + }, + "role": { "$ref": "ontologyConceptBindings.json#/definitions/role" }, + "subjectKey": { + "description": "Present exactly when the binding has a role.", + "$ref": "ontologyConceptBindings.json#/definitions/subjectKey" + }, + "rowFilter": { + "description": "Applying an operation that sets or changes it also requires ViewSampleData on the table.", + "$ref": "ontologyConceptBindings.json#/definitions/rowFilter" + }, + "columns": { + "type": "array", + "items": { "$ref": "#/definitions/columnBinding" }, + "maxItems": 100, + "default": [] + } + }, + "required": ["classIri", "tableId"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeEvidence.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeEvidence.json new file mode 100644 index 000000000000..2e2416623658 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeEvidence.json @@ -0,0 +1,41 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyChangeEvidence.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyChangeEvidence", + "description": "One piece of catalog metadata that supports a change set operation: a table and, when the support is narrower, some of its columns. A caller of the change set API reads and writes only the entries whose table that caller may view.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyChangeEvidence", + "definitions": { + "kind": { + "description": "The closed set of metadata that can support an operation. `declaredKey` is a key constraint declared on the table. `storedJoinCount` is a join count that the catalog stores for the columns. `testCase` is a data quality test on the table or its columns. `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile of the table or its columns. `name` is the name of the table or of its columns. `sampleData` is values seen in the sample rows that the catalog stores for the table. `measured` is a count or a rate computed by running a query against the source table, such as the distinct and null counts of a key column, or the share of the values of a join column that find a match in the target column.", + "type": "string", + "javaType": "org.openmetadata.schema.type.OntologyChangeEvidenceKind", + "enum": [ + "declaredKey", + "storedJoinCount", + "testCase", + "lineage", + "profile", + "name", + "sampleData", + "measured" + ] + } + }, + "properties": { + "tableId": { + "description": "The table the evidence is about.", + "$ref": "basic.json#/definitions/uuid" + }, + "columns": { + "description": "The columns of that table the evidence is about. Absent when it is about the table as a whole.", + "type": "array", + "items": { "$ref": "ontologyConceptBindings.json#/definitions/columnPath" }, + "maxItems": 32, + "default": null + }, + "kind": { "$ref": "#/definitions/kind" } + }, + "required": ["tableId", "kind"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json index 8f8d586b9652..a7eaa89e7454 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json @@ -24,7 +24,9 @@ "UPSERT_CONCEPT", "DELETE_CONCEPT", "UPSERT_PROPERTY", - "DELETE_PROPERTY" + "DELETE_PROPERTY", + "UPSERT_BINDING", + "UPSERT_SHAPE" ] }, "state": { @@ -35,6 +37,15 @@ "UNDONE" ], "default": "ACTIVE" + }, + "basis": { + "description": "Where a proposed shape comes from. `declared` restates what the catalog already declares, such as a column constraint. `observed` generalizes from what the stored metadata shows, such as a profile.", + "javaType": "org.openmetadata.schema.type.OntologyShapeBasis", + "type": "string", + "enum": [ + "declared", + "observed" + ] } }, "properties": { @@ -48,7 +59,7 @@ "$ref": "basic.json#/definitions/uuid" }, "baseVersion": { - "description": "Version used for optimistic concurrency. Omitted for create operations.", + "description": "Version used for optimistic concurrency. Omitted for create operations. On a binding operation it is the binding revision of the class that the operation was built against, required when the table is already bound to the class.", "type": "number", "minimum": 0.1, "multipleOf": 0.1 @@ -96,7 +107,7 @@ "$ref": "#/definitions/state" }, "requiresConceptIris": { - "description": "IRIs of concepts that an import expects to create in the same change set. Applying the operation without an UPSERT_CONCEPT operation for each of them is refused.", + "description": "IRIs of concepts that the operation needs in the ontology. Applying the operation is refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT operation of the same change set. A binding or a shape operation always needs its own class, listed here or not.", "type": "array", "items": { "$ref": "ontologyIri.json" @@ -108,6 +119,34 @@ }, "property": { "$ref": "../entity/data/ontologyProperty.json" + }, + "binding": { + "description": "The payload of an UPSERT_BINDING operation.", + "$ref": "ontologyBindingChange.json" + }, + "shape": { + "description": "The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI.", + "$ref": "../entity/data/ontologyShape.json" + }, + "basis": { + "description": "Only on an UPSERT_SHAPE operation.", + "$ref": "#/definitions/basis" + }, + "evidence": { + "description": "The tables and columns that support the operation. A save stores the entries about tables its writer may view and keeps the stored entries its writer was not shown. A read returns only the entries whose table the reader may view. A change event has no single reader, so no change event and no recorded change carries an entry.", + "type": "array", + "items": { + "$ref": "ontologyChangeEvidence.json" + }, + "maxItems": 20, + "default": null, + "mask": true + }, + "withheldEvidenceCount": { + "description": "How many evidence entries a read left out of this operation because the reader may not view the table they name, or because that table no longer exists. The server sets it on every operation it returns that stores evidence. It is never stored, and a value that a client sends is ignored.", + "type": "integer", + "minimum": 0, + "mask": true } }, "required": [ From 2f574722ce95d950d8da2bc3d803da65d591a112 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 12:46:08 -0800 Subject: [PATCH 038/203] Check at save that a binding or shape names a class, properties, table and columns that exist --- .../ontology/OntologyDraftPreflight.java | 272 ++++++++++++++ .../ontology/OntologyDraftPreflightTest.java | 336 ++++++++++++++++++ 2 files changed, 608 insertions(+) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftPreflight.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftPreflightTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftPreflight.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftPreflight.java new file mode 100644 index 000000000000..65c2389f8d26 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftPreflight.java @@ -0,0 +1,272 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import com.google.common.collect.Lists; +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.rdf.OwlEntityDeclarations; + +/** + * What the binding and shape operations of a draft must satisfy when the draft is saved: the class + * and properties each one names exist in the ontology or are created by an earlier operation, and + * the table and columns a binding names exist in the catalog. It reads stored state only and asks + * nothing about the caller, whose rights are checked when the draft is applied. + */ +public final class OntologyDraftPreflight { + private static final int DECLARATION_BATCH = 500; + private static final String CLASS = "class"; + private static final String PROPERTY = "property"; + + private final Declarations declarations; + private final TableLoader tables; + + /** The subset of these IRIs that the live classes, or properties, of an ontology declare. */ + public interface Declarations { + Set classes(UUID ontologyId, Set iris); + + Set properties(UUID ontologyId, Set iris); + } + + /** The live table with its columns, or null when the catalog holds none with this id. */ + @FunctionalInterface + public interface TableLoader { + Table load(UUID id); + } + + public OntologyDraftPreflight(final Declarations declarations, final TableLoader tables) { + this.declarations = declarations; + this.tables = tables; + } + + /** Reads the ontology and the catalog as they are stored. */ + public static OntologyDraftPreflight production() { + return new OntologyDraftPreflight( + new StoredDeclarations(), + id -> Entity.getEntityOrNull(Entity.TABLE, id, Entity.FIELD_COLUMNS, Include.NON_DELETED)); + } + + public void validate(final UUID ontologyId, final List operations) { + requireDeclared(ontologyId, listOrEmpty(operations)); + final Map> loaded = new HashMap<>(); + listOrEmpty(operations).stream() + .filter(OntologyBindingChanges::isBinding) + .forEach(operation -> requireResolved(operation, loaded)); + } + + /** One class or property an operation needs before it can be applied. */ + private record Need(OntologyChangeOperation operation, String kind, String iri) {} + + /** + * Walks the draft in order, so a need is met only by an operation that comes before it. What no + * earlier operation creates is then looked up in the ontology, each kind in one read. + */ + private void requireDeclared( + final UUID ontologyId, final List operations) { + final Map> created = + Map.of(CLASS, new HashSet<>(), PROPERTY, new HashSet<>()); + final List pending = new ArrayList<>(); + for (final OntologyChangeOperation operation : operations) { + needs(operation) + .filter(need -> !created.get(need.kind()).contains(need.iri())) + .forEach(pending::add); + rememberCreated(operation, created); + } + final Map> declared = + Map.of( + CLASS, declarations.classes(ontologyId, iris(pending, CLASS)), + PROPERTY, declarations.properties(ontologyId, iris(pending, PROPERTY))); + pending.stream() + .filter(need -> !declared.get(need.kind()).contains(need.iri())) + .findFirst() + .ifPresent(OntologyDraftPreflight::refuse); + } + + private static void refuse(final Need need) { + throw new BadRequestException( + "Ontology operation '" + + need.operation().getId() + + "' needs the " + + need.kind() + + " " + + need.iri() + + ", which the ontology does not declare and no earlier operation creates"); + } + + private static Set iris(final List needs, final String kind) { + return needs.stream() + .filter(need -> kind.equals(need.kind())) + .map(Need::iri) + .collect(Collectors.toSet()); + } + + /** + * A binding is a row of its class, so that class is always needed. A shape may target a + * vocabulary class, which no ontology declares, as any concept an operation lists may be one. + */ + private static Stream needs(final OntologyChangeOperation operation) { + final Stream listed = listOrEmpty(operation.getRequiresConceptIris()).stream(); + return switch (operation.getOperationType()) { + case UPSERT_BINDING -> Stream.of( + Stream.of( + new Need(operation, CLASS, operation.getBinding().getClassIri().toString())), + declarable(operation, listed), + OntologyBindingChanges.propertyIris(operation.getBinding()).stream() + .map(iri -> new Need(operation, PROPERTY, iri.toString()))) + .flatMap(Function.identity()); + case UPSERT_SHAPE -> declarable( + operation, Stream.concat(Stream.of(operation.getShape().getTargetConcept()), listed)); + default -> Stream.empty(); + }; + } + + /** The classes among these that an ontology has to declare, as when a draft is applied. */ + private static Stream declarable( + final OntologyChangeOperation operation, final Stream iris) { + return iris.map(URI::toString) + .filter( + iri -> + !OntologyClassHierarchy.isVocabularyClass(iri) + && !OwlEntityDeclarations.isDatatype(iri)) + .map(iri -> new Need(operation, CLASS, iri)); + } + + private static void rememberCreated( + final OntologyChangeOperation operation, final Map> created) { + if (operation.getOperationType() == OntologyChangeOperationType.UPSERT_CONCEPT + && operation.getConcept() != null + && operation.getConcept().getIri() != null) { + created.get(CLASS).add(operation.getConcept().getIri().toString()); + } + if (operation.getOperationType() == OntologyChangeOperationType.UPSERT_PROPERTY + && operation.getProperty() != null + && operation.getProperty().getIri() != null) { + created.get(PROPERTY).add(operation.getProperty().getIri().toString()); + } + } + + private void requireResolved( + final OntologyChangeOperation operation, final Map> loaded) { + final OntologyBindingChange change = operation.getBinding(); + final Table table = requireTable(operation, change.getTableId(), "table", loaded); + ownColumns(change).forEach(path -> requireColumn(operation, table, path)); + for (final OntologyJoinChange join : joins(change)) { + final Table target = + requireTable(operation, join.getTargetAssetId(), "join target table", loaded); + for (final OntologyJoinColumnPair pair : join.getOn()) { + requireColumn(operation, table, pair.getChild()); + requireColumn(operation, target, pair.getParent()); + } + } + } + + /** The columns of the bound table that the binding names outside its joins. */ + private static List> ownColumns(final OntologyBindingChange change) { + final List> paths = new ArrayList<>(listOrEmpty(change.getSubjectKey())); + if (change.getRowFilter() != null) { + paths.add(change.getRowFilter().getColumn()); + } + listOrEmpty(change.getColumns()).stream() + .map(OntologyColumnBindingChange::getColumnPath) + .forEach(paths::add); + return paths; + } + + private static List joins(final OntologyBindingChange change) { + return listOrEmpty(change.getColumns()).stream() + .map(OntologyColumnBindingChange::getJoin) + .filter(Objects::nonNull) + .toList(); + } + + private Table requireTable( + final OntologyChangeOperation operation, + final UUID id, + final String role, + final Map> loaded) { + return loaded + .computeIfAbsent(id, missing -> Optional.ofNullable(tables.load(missing))) + .orElseThrow( + () -> + new BadRequestException( + "Ontology operation '" + + operation.getId() + + "' names the " + + role + + " " + + id + + ", which does not exist")); + } + + private static void requireColumn( + final OntologyChangeOperation operation, final Table table, final List path) { + if (OntologyBindingRules.resolveColumn(table, path) == null) { + throw new BadRequestException( + "Ontology operation '" + + operation.getId() + + "' names the column " + + String.join(".", path) + + ", which table " + + table.getId() + + " does not have"); + } + } + + /** The declarations as the ontology stores them, read in batches the database accepts. */ + private static final class StoredDeclarations implements Declarations { + @Override + public Set classes(final UUID ontologyId, final Set iris) { + return OntologyChangeApplicationService.declaredConcepts(ontologyId, iris); + } + + @Override + public Set properties(final UUID ontologyId, final Set iris) { + final OntologyConceptBindingStore store = + new OntologyConceptBindingStore( + Entity.getCollectionDAO(), OntologyConceptBindingStore.registeredAssetTables()); + final Set declared = new HashSet<>(); + Lists.partition(iris.stream().map(URI::create).toList(), DECLARATION_BATCH) + .forEach( + batch -> + store + .liveProperties(ontologyId, batch) + .forEach(property -> declared.add(property.getIri().toString()))); + return declared; + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftPreflightTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftPreflightTest.java new file mode 100644 index 000000000000..5dca94eef0b3 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftPreflightTest.java @@ -0,0 +1,336 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; + +/** What a draft with binding and shape operations must name before it is saved. */ +class OntologyDraftPreflightTest { + private static final UUID ONTOLOGY_ID = UUID.fromString("2ecf752a-956d-4a44-95ec-cce029f5c1d7"); + private static final UUID OPERATION_ID = UUID.fromString("7a1c0f5e-3f0b-4f43-9a5c-6a0d6de0b001"); + private static final UUID ORDERS_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0002"); + private static final UUID CUSTOMERS_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0003"); + private static final UUID MISSING_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0004"); + private static final String ORDER = "https://example.org/sales/Order"; + private static final String CUSTOMER = "https://example.org/sales/Customer"; + private static final String TOTAL = "https://example.org/sales/total"; + private static final String PLACED_BY = "https://example.org/sales/placedBy"; + private static final String NEEDS = "Ontology operation '" + OPERATION_ID + "' needs the "; + private static final String NAMES = "Ontology operation '" + OPERATION_ID + "' names the "; + + private final Set declaredClasses = new HashSet<>(Set.of(ORDER, CUSTOMER)); + private final Set declaredProperties = new HashSet<>(Set.of(TOTAL, PLACED_BY)); + private final Map tables = new HashMap<>(); + private final OntologyDraftPreflight preflight = + new OntologyDraftPreflight(new Declared(), tables::get); + + OntologyDraftPreflightTest() { + tables.put( + ORDERS_ID, + table( + ORDERS_ID, + column("order_id"), + column("customer_id"), + column("total"), + column("status"), + column("shipping").withChildren(List.of(column("zip"))))); + tables.put(CUSTOMERS_ID, table(CUSTOMERS_ID, column("id"))); + } + + @Test + void acceptsABindingAndAShapeWhoseNamesAllExist() { + assertDoesNotThrow(() -> validate(binding(change -> {}), shape(CUSTOMER))); + } + + @Test + void acceptsAClassAndAPropertyThatAnEarlierOperationCreates() { + declaredClasses.remove(ORDER); + declaredProperties.remove(TOTAL); + + assertDoesNotThrow( + () -> validate(classOperation(ORDER), propertyOperation(TOTAL), binding(change -> {}))); + } + + @Test + void refusesABindingWhoseClassNothingDeclaresOrCreatesEarlier() { + declaredClasses.remove(ORDER); + + assertRefused( + NEEDS + + "class " + + ORDER + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> {})); + assertRefused( + NEEDS + + "class " + + ORDER + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> {}), + classOperation(ORDER)); + } + + @Test + void refusesAShapeWhoseTargetClassNothingDeclaresOrCreatesEarlier() { + declaredClasses.remove(CUSTOMER); + + assertRefused( + NEEDS + + "class " + + CUSTOMER + + ", which the ontology does not declare and no earlier operation creates", + shape(CUSTOMER).withId(OPERATION_ID)); + } + + @Test + void aShapeMayTargetAVocabularyClassButABindingNeedsADeclaredOne() { + final String thing = "http://www.w3.org/2002/07/owl#Thing"; + + assertDoesNotThrow(() -> validate(shape(thing))); + assertRefused( + NEEDS + + "class " + + thing + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> change.setClassIri(URI.create(thing)))); + } + + @Test + void refusesAConceptAnOperationListsAsRequiredButNothingDeclares() { + final String region = "https://example.org/sales/Region"; + + assertRefused( + NEEDS + + "class " + + region + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> {}).withRequiresConceptIris(List.of(URI.create(region)))); + assertDoesNotThrow( + () -> + validate( + binding(change -> {}) + .withRequiresConceptIris( + List.of( + URI.create("http://www.w3.org/2002/07/owl#Thing"), + URI.create("http://www.w3.org/2001/XMLSchema#string"))))); + } + + @Test + void refusesABindingWhosePropertyNothingDeclaresOrCreatesEarlier() { + declaredProperties.remove(TOTAL); + + assertRefused( + NEEDS + + "property " + + TOTAL + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> {})); + } + + @Test + void refusesATableTheCatalogDoesNotHold() { + assertRefused( + NAMES + "table " + MISSING_ID + ", which does not exist", + binding(change -> change.setTableId(MISSING_ID))); + } + + @Test + void refusesEachColumnTheBoundTableDoesNotHave() { + final String missing = ", which table " + ORDERS_ID + " does not have"; + + assertRefused( + NAMES + "column order_number" + missing, + binding(change -> change.setSubjectKey(List.of(List.of("order_number"))))); + assertRefused( + NAMES + "column state" + missing, + binding( + change -> + change.setRowFilter( + new OntologyRowFilter() + .withColumn(List.of("state")) + .withOperator(OntologyRowFilterOperator.IS_NOT_NULL)))); + assertRefused( + NAMES + "column amount" + missing, + binding(change -> change.setColumns(List.of(column(TOTAL, List.of("amount"), null))))); + assertRefused( + NAMES + "column shipping.city" + missing, + binding( + change -> + change.setColumns(List.of(column(TOTAL, List.of("shipping", "city"), null))))); + } + + @Test + void acceptsANestedColumnByItsPath() { + assertDoesNotThrow( + () -> + validate( + binding( + change -> + change.setColumns( + List.of(column(TOTAL, List.of("shipping", "zip"), null)))))); + } + + @Test + void refusesAJoinWhoseTargetTableOrColumnsDoNotExist() { + assertRefused( + NAMES + "join target table " + MISSING_ID + ", which does not exist", + binding(change -> change.setColumns(List.of(joined(MISSING_ID, "customer_id", "id"))))); + assertRefused( + NAMES + "column buyer_id, which table " + ORDERS_ID + " does not have", + binding(change -> change.setColumns(List.of(joined(CUSTOMERS_ID, "buyer_id", "id"))))); + assertRefused( + NAMES + "column customer_key, which table " + CUSTOMERS_ID + " does not have", + binding( + change -> + change.setColumns(List.of(joined(CUSTOMERS_ID, "customer_id", "customer_key"))))); + assertDoesNotThrow( + () -> + validate( + binding( + change -> + change.setColumns(List.of(joined(CUSTOMERS_ID, "customer_id", "id")))))); + } + + private void validate(final OntologyChangeOperation... operations) { + preflight.validate(ONTOLOGY_ID, List.of(operations)); + } + + private void assertRefused(final String expected, final OntologyChangeOperation... operations) { + final BadRequestException refusal = + assertThrows(BadRequestException.class, () -> validate(operations)); + assertEquals(expected, refusal.getMessage()); + } + + /** Answers for one ontology only, so a lookup in another ontology finds nothing. */ + private final class Declared implements OntologyDraftPreflight.Declarations { + @Override + public Set classes(final UUID ontologyId, final Set iris) { + return known(ontologyId, iris, declaredClasses); + } + + @Override + public Set properties(final UUID ontologyId, final Set iris) { + return known(ontologyId, iris, declaredProperties); + } + + private Set known( + final UUID ontologyId, final Set iris, final Set declared) { + final Set known = new HashSet<>(iris); + known.retainAll(ONTOLOGY_ID.equals(ontologyId) ? declared : Set.of()); + return known; + } + } + + /** An identity binding of the orders table, changed by {@code edit} before it is sent. */ + private static OntologyChangeOperation binding(final Consumer edit) { + final OntologyBindingChange change = + new OntologyBindingChange() + .withClassIri(URI.create(ORDER)) + .withTableId(ORDERS_ID) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("order_id"))) + .withRowFilter( + new OntologyRowFilter() + .withColumn(List.of("status")) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue("placed")) + .withColumns(List.of(column(TOTAL, List.of("total"), null))); + edit.accept(change); + return new OntologyChangeOperation() + .withId(OPERATION_ID) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding(change); + } + + private static OntologyColumnBindingChange column( + final String propertyIri, final List path, final OntologyJoinChange join) { + return new OntologyColumnBindingChange() + .withPropertyIri(URI.create(propertyIri)) + .withColumnPath(path) + .withJoin(join); + } + + private static OntologyColumnBindingChange joined( + final UUID target, final String child, final String parent) { + return column( + PLACED_BY, + List.of(child), + new OntologyJoinChange() + .withTargetAssetId(target) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(child)) + .withParent(List.of(parent))))); + } + + private static OntologyChangeOperation shape(final String targetClass) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_SHAPE) + .withShape( + new OntologyShape() + .withId(UUID.randomUUID()) + .withTargetConcept(URI.create(targetClass))); + } + + private static OntologyChangeOperation classOperation(final String iri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withConcept(new OntologyConcept().withId(UUID.randomUUID()).withIri(URI.create(iri))); + } + + private static OntologyChangeOperation propertyOperation(final String iri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_PROPERTY) + .withProperty(new OntologyProperty().withId(UUID.randomUUID()).withIri(URI.create(iri))); + } + + private static Table table(final UUID id, final Column... columns) { + return new Table().withId(id).withColumns(List.of(columns)); + } + + private static Column column(final String name) { + return new Column().withName(name); + } +} From 8701988c4211b6054e85754d63dbf9630721a395 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 12:46:11 -0800 Subject: [PATCH 039/203] Show change set evidence only for tables the reader may view Every change set endpoint, stored version and entity read leaves out evidence entries about tables the reader lacks ViewBasic on and reports how many it left out. Recorded changes and change events hold operations without evidence. A save checks drafts and applies as the caller. The patch tool refuses a change set, whose resource has no patch. --- .../openmetadata/mcp/tools/CommonUtils.java | 11 +- .../mcp/tools/PatchEntityTool.java | 3 + .../mcp/tools/PatchEntityToolTest.java | 1 + .../jdbi3/OntologyChangeSetRepository.java | 25 +- .../ontology/OntologyChangeEvidenceView.java | 190 ++++++++++++++ .../ontology/OntologyChangeSetResource.java | 182 ++++++++++--- .../OntologyChangeEvidenceViewTest.java | 240 ++++++++++++++++++ 7 files changed, 608 insertions(+), 44 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CommonUtils.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CommonUtils.java index 5ef98a1ffa72..60da15322540 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CommonUtils.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CommonUtils.java @@ -11,6 +11,7 @@ import org.openmetadata.schema.CreateEntity; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.entity.context.ContextMemory; +import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.teams.Team; import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.type.EntityReference; @@ -22,6 +23,8 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.TeamRepository; import org.openmetadata.service.jdbi3.UserRepository; +import org.openmetadata.service.ontology.OntologyChangeEvidenceView; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.resources.context.ContextMemoryDocumentAccess; import org.openmetadata.service.resources.context.ContextMemoryEvidenceAccess; import org.openmetadata.service.resources.context.ContextMemoryVisibility; @@ -68,7 +71,9 @@ public static EntityInterface readEntityForCaller( /** * Returns {@code entity} as the caller may read it: a context memory's references to Queries the * caller cannot view keep only their id and type, as in every REST memory response ({@link - * ContextMemoryEvidenceAccess}); a metric's or metric group's relations keep only the entities + * ContextMemoryEvidenceAccess}); the operations of an ontology change set keep only the evidence + * about tables the caller may view, as in every REST change set response ({@link + * OntologyChangeEvidenceView}); a metric's or metric group's relations keep only the entities * the caller may view ({@link MetricRelationVisibility}); every other entity type is returned as * is. Applied where a tool answers with the entity, not on reads it only checks. */ @@ -80,6 +85,10 @@ public static EntityInterface withVisibleEvidence( ContextMemoryDocumentAccess.redactDocuments(List.of(copy), securityContext); return copy; } + if (entity instanceof OntologyChangeSet changeSet) { + return OntologyChangeEvidenceView.of(authorizer, new Access(null, securityContext)) + .apply(JsonUtils.deepCopy(changeSet, OntologyChangeSet.class)); + } return MetricRelationVisibility.visibleTo(entity, authorizer, securityContext); } diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java index f8693a340cc5..cda3a2b86faf 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java @@ -62,6 +62,8 @@ public class PatchEntityTool implements McpTool { // ingestionPipeline secret decryptOrNullify on the response // intakeForm authorizeAdmin // notificationTemplate provider-aware EDIT_ALL authorization + // ontologyChangeSet edit lease and scope authorization, and evidence shown per reader, + // which a copy, move or test would read; its resource has no PATCH // persona authorizeAdmin // testCase table-or-testCase authorization, sample cleanup // testSuite getAuthRequestsForUpdate authorization @@ -80,6 +82,7 @@ public class PatchEntityTool implements McpTool { Entity.INGESTION_PIPELINE, Entity.INTAKE_FORM, Entity.NOTIFICATION_TEMPLATE, + Entity.ONTOLOGY_CHANGE_SET, Entity.PERSONA, Entity.TEST_CASE, Entity.TEST_SUITE, diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java index 9c573045ce70..c53753ac0f88 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java @@ -380,6 +380,7 @@ void execute_letsMetricDescriptionEditsThrough() { "ingestionPipeline", "intakeForm", "notificationTemplate", + "ontologyChangeSet", "persona", "testCase", "testSuite", diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java index 32fbeb095a95..6032659a5256 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java @@ -14,6 +14,7 @@ package org.openmetadata.service.jdbi3; import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.util.EntityUtil.objectMatch; import jakarta.ws.rs.BadRequestException; import jakarta.ws.rs.core.UriInfo; @@ -36,6 +37,7 @@ import org.openmetadata.schema.type.change.ChangeSource; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyChangeEvidenceView; import org.openmetadata.service.ontology.OntologyChangeSetValidator; import org.openmetadata.service.ontology.OntologyPackCatalog; import org.openmetadata.service.ontology.OntologyPackInstallations; @@ -46,6 +48,7 @@ @Repository public class OntologyChangeSetRepository extends EntityRepository { + private static final String OPERATIONS_FIELD = "operations"; private static final String UPDATE_FIELDS = "operations,undoCursor,state,reviewTask,applicationResult"; @@ -384,12 +387,32 @@ public void entitySpecificUpdate(final boolean consolidatingChanges) { Entity.CONTEXT_MEMORY); storeSourceMemoryRelationships(updated); } - recordChange("operations", original.getOperations(), updated.getOperations(), true); + recordOperations(); recordChange("undoCursor", original.getUndoCursor(), updated.getUndoCursor()); recordChange("state", original.getState(), updated.getState()); recordChange("reviewTask", original.getReviewTask(), updated.getReviewTask()); recordChange( "applicationResult", original.getApplicationResult(), updated.getApplicationResult()); } + + /** + * A recorded change is read with every version and travels in change events, and neither has a + * single reader to decide the tables of the evidence for. So it holds the operations without + * their evidence, and an edit that changes evidence alone is stored without a new version. + */ + private void recordOperations() { + recordChange( + OPERATIONS_FIELD, + OntologyChangeEvidenceView.withoutEvidence(original.getOperations()), + OntologyChangeEvidenceView.withoutEvidence(updated.getOperations()), + true); + recordChange( + OPERATIONS_FIELD, + original.getOperations(), + updated.getOperations(), + false, + objectMatch, + false); + } } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java new file mode 100644 index 000000000000..80ce74e860ef --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java @@ -0,0 +1,190 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.security.Authorizer; + +/** + * The evidence of change set operations as one reader may see it and may write it. A read keeps + * the entries whose table the reader may view and sets, on each operation that stores evidence, how + * many it left out. A save stores the entries the reader sends about tables it may view, beside the + * stored entries it was not shown. One view serves one request, so a table is decided once however + * many operations, rows and versions name it. + * + *

A recorded change and a change event have no single reader. They hold the operations {@link + * #withoutEvidence}, so this view has only the operations of a change set to mask. + */ +public final class OntologyChangeEvidenceView implements UnaryOperator { + /** The most entries an operation stores, as the operation schema bounds its evidence. */ + static final int MAX_ENTRIES = 20; + + private static final int TABLE_BATCH = 500; + + private final ViewableTables tables; + private final Map decided = new HashMap<>(); + + /** The subset of these tables that the reader may view. A table that is gone is not in it. */ + @FunctionalInterface + public interface ViewableTables { + Set among(List tableIds); + } + + public OntologyChangeEvidenceView(final ViewableTables tables) { + this.tables = tables; + } + + /** The view of one caller, who may view a table when the caller's policies allow ViewBasic. */ + public static OntologyChangeEvidenceView of(final Authorizer authorizer, final Access reader) { + final OntologyBindingAccess catalog = + new OntologyBindingAccess(authorizer, Entity::getEntityRepository); + return new OntologyChangeEvidenceView( + ids -> catalog.viewable(reader, Entity.TABLE, ids).keySet()); + } + + /** The operations with no evidence, as a recorded change holds them for every reader alike. */ + public static List withoutEvidence( + final List operations) { + return listOrEmpty(operations).stream() + .map( + operation -> + listOrEmpty(operation.getEvidence()).isEmpty() + ? operation + : JsonUtils.deepCopy(operation, OntologyChangeOperation.class) + .withEvidence(null)) + .toList(); + } + + /** Masks the operations of one change set in place. */ + @Override + public OntologyChangeSet apply(final OntologyChangeSet changeSet) { + applyAll(List.of(changeSet)); + return changeSet; + } + + /** Masks every change set in place, deciding the tables of all of them in one read. */ + public void applyAll(final Collection changeSets) { + final List operations = + changeSets.stream() + .flatMap(changeSet -> listOrEmpty(changeSet.getOperations()).stream()) + .toList(); + decide(operations.stream()); + operations.forEach(this::mask); + } + + /** + * The operations to store when the reader saves {@code incoming} over the {@code stored} + * operations of a draft, or over none when the reader creates the draft. Evidence passes through + * the reader's view in this direction too. An entry the reader sends about a table it may not + * view is not stored. Storing it would repeat a withheld entry, and merging the repeat would tell + * the reader what is withheld. Each stored entry the reader was not shown stays where the draft + * stores it. + */ + public List savedByReader( + final List stored, final List incoming) { + final Map> storedEvidence = + stored.stream() + .filter(operation -> !listOrEmpty(operation.getEvidence()).isEmpty()) + .collect( + Collectors.toMap( + OntologyChangeOperation::getId, + OntologyChangeOperation::getEvidence, + (first, second) -> first)); + decide(Stream.concat(stored.stream(), incoming.stream())); + for (final OntologyChangeOperation operation : incoming) { + final List kept = storedEvidence.get(operation.getId()); + if (kept != null || !listOrEmpty(operation.getEvidence()).isEmpty()) { + save(operation, listOrEmpty(kept)); + } + } + return incoming; + } + + /** + * Walks the stored entries in order. A withheld one keeps its place, and the place of a shown one + * goes to the next entry the reader sent about a table it may view. + */ + private void save( + final OntologyChangeOperation operation, final List stored) { + final Iterator sent = + listOrEmpty(operation.getEvidence()).stream().filter(this::mayView).iterator(); + final List kept = new ArrayList<>(); + int withheld = 0; + for (final OntologyChangeEvidence entry : stored) { + if (!mayView(entry)) { + kept.add(entry); + withheld++; + } else if (sent.hasNext()) { + kept.add(sent.next()); + } + } + sent.forEachRemaining(kept::add); + if (kept.size() > MAX_ENTRIES) { + throw OntologyChangeSetValidator.invalid( + operation, + "evidence holds at most " + + MAX_ENTRIES + + " entries, counting the " + + withheld + + " that a read withheld"); + } + operation.setEvidence(kept); + } + + private void decide(final Stream operations) { + final List undecided = + operations + .flatMap(operation -> listOrEmpty(operation.getEvidence()).stream()) + .map(OntologyChangeEvidence::getTableId) + .filter(tableId -> !decided.containsKey(tableId)) + .distinct() + .toList(); + for (final List batch : Lists.partition(undecided, TABLE_BATCH)) { + final Set viewable = tables.among(batch); + batch.forEach(tableId -> decided.put(tableId, viewable.contains(tableId))); + } + } + + private void mask(final OntologyChangeOperation operation) { + final List stored = listOrEmpty(operation.getEvidence()); + if (!stored.isEmpty()) { + final List shown = stored.stream().filter(this::mayView).toList(); + operation.setEvidence(shown); + operation.setWithheldEvidenceCount(stored.size() - shown.size()); + } + } + + private boolean mayView(final OntologyChangeEvidence entry) { + return Boolean.TRUE.equals(decided.get(entry.getTableId())); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java index db0ff1671005..f79d6878d50a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java @@ -42,7 +42,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.UUID; +import java.util.function.UnaryOperator; import java.util.stream.Collectors; import org.openmetadata.schema.api.data.ApplyOntologyChangeSet; import org.openmetadata.schema.api.data.CreateOntologyChangeSet; @@ -58,6 +61,7 @@ import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeSetState; import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.GlossaryTermRepository; @@ -65,8 +69,13 @@ import org.openmetadata.service.jdbi3.OntologyChangeSetRepository; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.ontology.NativeOntologyChanges; +import org.openmetadata.service.ontology.OntologyBindingChangeExecutor; +import org.openmetadata.service.ontology.OntologyBindingChanges; import org.openmetadata.service.ontology.OntologyChangeApplicationService; +import org.openmetadata.service.ontology.OntologyChangeEvidenceView; import org.openmetadata.service.ontology.OntologyChangeSetValidator; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyDraftPreflight; import org.openmetadata.service.ontology.OntologyEditLeasePolicy; import org.openmetadata.service.ontology.OntologyEditLockService; import org.openmetadata.service.resources.Collection; @@ -90,6 +99,7 @@ public class OntologyChangeSetResource private static final String FIELDS = "operations,applicationResult"; private final OntologyChangeSetMapper mapper = new OntologyChangeSetMapper(); private final OntologyChangeApplicationService applicationService; + private final OntologyDraftPreflight draftPreflight; private final OntologyEditLockService lockService; public OntologyChangeSetResource(final Authorizer authorizer, final Limits limits) { @@ -99,7 +109,9 @@ public OntologyChangeSetResource(final Authorizer authorizer, final Limits limit new OntologyChangeApplicationService( repository, (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM), - clock); + clock, + OntologyBindingChangeExecutor.production(authorizer)); + draftPreflight = OntologyDraftPreflight.production(); lockService = new OntologyEditLockService(Entity.getJdbi(), clock, new OntologyEditLeasePolicy()); } @@ -145,6 +157,7 @@ public ResultList list( if (scopeId == null) { authorizeListedScopes(securityContext, page.getData()); } + evidence(uriInfo, securityContext).applyAll(page.getData()); return page; } @@ -202,7 +215,8 @@ public OntologyChangeSet get( @QueryParam("fields") final String fields, @QueryParam("include") @DefaultValue("non-deleted") final Include include) { authorizeScopeRead(securityContext, readableChangeSet(id)); - return getInternal(uriInfo, securityContext, id, fields, include, null); + return evidence(uriInfo, securityContext) + .apply(getInternal(uriInfo, securityContext, id, fields, include, null)); } @POST @@ -213,7 +227,10 @@ public Response create( @Valid final CreateOntologyChangeSet request) { final OntologyChangeSet entity = mapper.createToEntity(request, user(securityContext)); authorizeScope(securityContext, entity, MetadataOperation.EDIT_ALL); - return create(uriInfo, securityContext, entity); + requireResolved(entity); + final OntologyChangeEvidenceView evidence = evidence(uriInfo, securityContext); + evidence.savedByReader(List.of(), entity.getOperations()); + return masked(evidence, create(uriInfo, securityContext, entity)); } @PUT @@ -226,10 +243,62 @@ public Response replaceOperations( @Valid final UpdateOntologyChangeSet request) { authorizeChangeSet(securityContext, id); requireLease(id, request.getLease(), securityContext); - return repository - .replaceOperations( - uriInfo, user(securityContext), id, request.getOperations(), request.getUndoCursor()) - .toResponse(); + final OntologyChangeEvidenceView evidence = evidence(uriInfo, securityContext); + return masked( + evidence, + repository + .replaceOperations( + uriInfo, + user(securityContext), + id, + savable(evidence, id, request), + request.getUndoCursor()) + .toResponse()); + } + + /** + * The operations a save stores. They pass the rules the repository applies, then name classes, + * properties, tables and columns that exist, and they carry the evidence the writer may write + * beside the evidence the writer was not shown. + */ + private List savable( + final OntologyChangeEvidenceView evidence, + final UUID id, + final UpdateOntologyChangeSet request) { + final OntologyChangeSet draft = scopedChangeSet(id); + final List stored = listOrEmpty(draft.getOperations()); + draft.setOperations(request.getOperations()); + draft.setUndoCursor(request.getUndoCursor()); + OntologyChangeSetValidator.normalizeAndValidate(draft); + requireResolved(draft); + return evidence.savedByReader(stored, draft.getOperations()); + } + + private void requireResolved(final OntologyChangeSet draft) { + if (draft.getOntology() != null) { + draftPreflight.validate(draft.getOntology().getId(), draft.getOperations()); + } + } + + private OntologyChangeEvidenceView evidence( + final UriInfo uriInfo, final SecurityContext securityContext) { + return OntologyChangeEvidenceView.of(authorizer, new Access(uriInfo, securityContext)); + } + + /** + * A write answers with the instance the repository stored and passed to its listeners, so the + * reader's view is taken from a copy of it. + */ + private Response masked(final OntologyChangeEvidenceView evidence, final Response response) { + return withRedactedEntity( + response, stored -> evidence.apply(JsonUtils.deepCopy(stored, OntologyChangeSet.class))); + } + + /** A stored version carries every evidence entry, so it is read through the reader's view. */ + @Override + protected Optional> snapshotRedaction( + final SecurityContext securityContext) { + return Optional.of(evidence(null, securityContext)); } @POST @@ -242,7 +311,9 @@ public Response undo( @Valid final OntologyChangeSetCommand request) { authorizeChangeSet(securityContext, id); requireLease(id, request.getLease(), securityContext); - return repository.moveCursor(uriInfo, user(securityContext), id, -1).toResponse(); + return masked( + evidence(uriInfo, securityContext), + repository.moveCursor(uriInfo, user(securityContext), id, -1).toResponse()); } @POST @@ -255,7 +326,9 @@ public Response redo( @Valid final OntologyChangeSetCommand request) { authorizeChangeSet(securityContext, id); requireLease(id, request.getLease(), securityContext); - return repository.moveCursor(uriInfo, user(securityContext), id, 1).toResponse(); + return masked( + evidence(uriInfo, securityContext), + repository.moveCursor(uriInfo, user(securityContext), id, 1).toResponse()); } @POST @@ -269,9 +342,11 @@ public Response submit( final OntologyChangeSet changeSet = scopedChangeSet(id); authorizeScope(securityContext, changeSet, MetadataOperation.EDIT_ALL); requireLease(id, request.getLease(), securityContext); - return repository - .transition(uriInfo, user(securityContext), id, OntologyChangeSetState.SUBMITTED, null) - .toResponse(); + return masked( + evidence(uriInfo, securityContext), + repository + .transition(uriInfo, user(securityContext), id, OntologyChangeSetState.SUBMITTED, null) + .toResponse()); } @POST @@ -286,9 +361,9 @@ public Response apply( authorizeScope(securityContext, changeSet, MetadataOperation.EDIT_ALL); requireLease(id, request.getLease(), securityContext); final PutResponse response = - applicationService.apply(uriInfo, id, user(securityContext)); + applicationService.apply(new Access(uriInfo, securityContext), id); releaseAppliedLease(response.getEntity(), request.getLease(), securityContext); - return response.toResponse(); + return masked(evidence(uriInfo, securityContext), response.toResponse()); } @POST @@ -301,9 +376,11 @@ public Response discard( @Valid final OntologyChangeSetCommand request) { authorizeChangeSet(securityContext, id); requireLease(id, request.getLease(), securityContext); - return repository - .transition(uriInfo, user(securityContext), id, OntologyChangeSetState.DISCARDED, null) - .toResponse(); + return masked( + evidence(uriInfo, securityContext), + repository + .transition(uriInfo, user(securityContext), id, OntologyChangeSetState.DISCARDED, null) + .toResponse()); } @GET @@ -334,7 +411,9 @@ public Response delete( @Context final SecurityContext securityContext, @PathParam("id") final UUID id, @QueryParam("hardDelete") @DefaultValue("false") final boolean hardDelete) { - return delete(uriInfo, securityContext, id, false, hardDelete); + return masked( + evidence(uriInfo, securityContext), + delete(uriInfo, securityContext, id, false, hardDelete)); } @PUT @@ -344,7 +423,9 @@ public Response restore( @Context final UriInfo uriInfo, @Context final SecurityContext securityContext, @Valid final RestoreEntity restore) { - return restoreEntity(uriInfo, securityContext, restore.getId()); + return masked( + evidence(uriInfo, securityContext), + restoreEntity(uriInfo, securityContext, restore.getId())); } private OntologyChangeSet scopedChangeSet(final UUID id) { @@ -452,6 +533,11 @@ private void authorizeGlossary( new ResourceContext<>(Entity.GLOSSARY, glossary.getId(), null)); } + /** + * A definition operation is authorized here, when the draft is saved, submitted or applied. A + * binding operation is authorized where it is written, with the rights of the caller who applies + * the draft, whoever saved it. + */ private void authorizeNativeScope( final SecurityContext context, final OntologyChangeSet changeSet) { authorizer.authorize( @@ -460,30 +546,42 @@ private void authorizeNativeScope( new ResourceContext<>(Entity.ONTOLOGY, changeSet.getOntology().getId(), null)); for (final OntologyChangeOperation change : changeSet.getOperations().subList(0, changeSet.getUndoCursor())) { - final String type = NativeOntologyChanges.entityType(change); - if (change.getTargetId() == null) { - authorizer.authorize( - context, - new OperationContext(type, MetadataOperation.CREATE), - new CreateResourceContext<>(type, NativeOntologyChanges.definition(change))); - } else { - final MetadataOperation operation = - NativeOntologyChanges.isDelete(change) - ? MetadataOperation.DELETE - : MetadataOperation.EDIT_ALL; - authorizer.authorize( - context, - new OperationContext(type, operation), - new ResourceContext<>(type, change.getTargetId(), null)); - } - if (change.getSourceMemoryIds() != null) { - for (final UUID memoryId : change.getSourceMemoryIds()) { - authorizer.authorize( - context, - new OperationContext(Entity.CONTEXT_MEMORY, MetadataOperation.VIEW_ALL), - new ResourceContext<>(Entity.CONTEXT_MEMORY, memoryId, null)); - } + if (!OntologyBindingChanges.isBinding(change)) { + authorizeDefinition(context, change); } + authorizeSourceMemories(context, change); + } + } + + private void authorizeDefinition( + final SecurityContext context, final OntologyChangeOperation change) { + final String type = NativeOntologyChanges.entityType(change); + if (change.getTargetId() == null) { + authorizer.authorize( + context, + new OperationContext(type, MetadataOperation.CREATE), + new CreateResourceContext<>(type, NativeOntologyChanges.definition(change))); + return; + } + final MetadataOperation operation = + NativeOntologyChanges.isDelete(change) + ? MetadataOperation.DELETE + : MetadataOperation.EDIT_ALL; + authorizer.authorize( + context, + new OperationContext(type, operation), + new ResourceContext<>(type, change.getTargetId(), null)); + } + + private void authorizeSourceMemories( + final SecurityContext context, final OntologyChangeOperation change) { + final Set memoryIds = + change.getSourceMemoryIds() == null ? Set.of() : change.getSourceMemoryIds(); + for (final UUID memoryId : memoryIds) { + authorizer.authorize( + context, + new OperationContext(Entity.CONTEXT_MEMORY, MetadataOperation.VIEW_ALL), + new ResourceContext<>(Entity.CONTEXT_MEMORY, memoryId, null)); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java new file mode 100644 index 000000000000..a162ecdf92b4 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java @@ -0,0 +1,240 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.ws.rs.BadRequestException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.secrets.masker.MaskedFields; + +/** Evidence as a reader sees it, what a save by that reader stores, and what no reader is sent. */ +class OntologyChangeEvidenceViewTest { + private static final UUID OPERATION_ID = UUID.fromString("7a1c0f5e-3f0b-4f43-9a5c-6a0d6de0b001"); + private static final UUID SHOWN = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0002"); + private static final UUID HIDDEN = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0003"); + + private final List> lookups = new ArrayList<>(); + private final OntologyChangeEvidenceView view = + new OntologyChangeEvidenceView( + tableIds -> { + lookups.add(tableIds); + final Set viewable = new HashSet<>(tableIds); + viewable.retainAll(Set.of(SHOWN)); + return viewable; + }); + + @Test + void aReaderSeesOnlyTheEvidenceOfTablesTheReaderMayView() { + final OntologyChangeSet changeSet = + changeSet( + operation(OPERATION_ID, name(SHOWN), profile(HIDDEN), lineage(SHOWN)), + operation(UUID.randomUUID())); + + view.apply(changeSet); + + final OntologyChangeOperation supported = changeSet.getOperations().getFirst(); + final OntologyChangeOperation unsupported = changeSet.getOperations().getLast(); + assertEquals(List.of(name(SHOWN), lineage(SHOWN)), supported.getEvidence()); + assertEquals(1, supported.getWithheldEvidenceCount()); + assertNull(unsupported.getEvidence()); + assertNull(unsupported.getWithheldEvidenceCount()); + } + + @Test + void aReaderWhoMayViewEveryTableSeesEveryEntryAndACountOfZero() { + final OntologyChangeSet changeSet = + changeSet(operation(OPERATION_ID, name(SHOWN), lineage(SHOWN))); + + view.apply(changeSet); + + final OntologyChangeOperation operation = changeSet.getOperations().getFirst(); + assertEquals(List.of(name(SHOWN), lineage(SHOWN)), operation.getEvidence()); + assertEquals(0, operation.getWithheldEvidenceCount()); + } + + @ParameterizedTest + @EnumSource(OntologyChangeEvidenceKind.class) + void evidenceOfEachKindIsWithheldWhenItsTableIsHidden(final OntologyChangeEvidenceKind kind) { + final OntologyChangeSet changeSet = + changeSet(operation(OPERATION_ID, entry(HIDDEN, kind), entry(SHOWN, kind))); + + view.apply(changeSet); + + final OntologyChangeOperation operation = changeSet.getOperations().getFirst(); + assertEquals(List.of(entry(SHOWN, kind)), operation.getEvidence()); + assertEquals(1, operation.getWithheldEvidenceCount()); + } + + @Test + void aRecordedChangeHoldsTheOperationsWithNoEvidence() { + final OntologyChangeOperation supported = operation(OPERATION_ID, name(SHOWN), profile(HIDDEN)); + final OntologyChangeOperation unsupported = operation(UUID.randomUUID()); + + final List recorded = + OntologyChangeEvidenceView.withoutEvidence(List.of(supported, unsupported)); + + assertEquals(List.of(operation(OPERATION_ID), unsupported), recorded); + assertEquals(List.of(name(SHOWN), profile(HIDDEN)), supported.getEvidence()); + } + + @Test + void aStoredChangeEventLeavesOutTheEvidenceOfEveryOperation() { + final OntologyChangeSet changeSet = + changeSet( + operation(OPERATION_ID, name(SHOWN), profile(HIDDEN)).withWithheldEvidenceCount(1)); + + final JsonNode stored = JsonUtils.readTree(JsonUtils.pojoToMaskedJson(changeSet)); + + assertTrue(MaskedFields.anyIn(OntologyChangeSet.class)); + assertEquals(OPERATION_ID.toString(), stored.at("/operations/0/id").asText()); + assertTrue(stored.at("/operations/0/evidence").isMissingNode()); + assertTrue(stored.at("/operations/0/withheldEvidenceCount").isMissingNode()); + } + + @Test + void onePageOfChangeSetsDecidesEachTableOnce() { + final OntologyChangeSet first = changeSet(operation(OPERATION_ID, name(SHOWN), name(HIDDEN))); + final OntologyChangeSet second = + changeSet(operation(UUID.randomUUID(), profile(HIDDEN), profile(SHOWN))); + + view.applyAll(List.of(first, second)); + view.apply(changeSet(operation(UUID.randomUUID(), lineage(HIDDEN)))); + + assertEquals(List.of(List.of(SHOWN, HIDDEN)), lookups); + assertEquals(List.of(profile(SHOWN)), second.getOperations().getFirst().getEvidence()); + } + + @Test + void aSaveKeepsTheEvidenceItsWriterWasNotShown() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN), lineage(SHOWN))); + + assertEquals( + List.of(name(SHOWN), profile(HIDDEN), lineage(SHOWN)), + saved(stored, operation(OPERATION_ID, name(SHOWN), lineage(SHOWN)))); + assertEquals( + List.of(lineage(SHOWN), profile(HIDDEN)), + saved(stored, operation(OPERATION_ID, lineage(SHOWN)))); + assertEquals( + List.of(name(SHOWN), profile(HIDDEN), lineage(SHOWN), testCase(SHOWN)), + saved(stored, operation(OPERATION_ID, name(SHOWN), lineage(SHOWN), testCase(SHOWN)))); + assertEquals(List.of(profile(HIDDEN)), saved(stored, operation(OPERATION_ID))); + } + + @Test + void anEntrySentAboutAHiddenTableIsNotStoredWhetherOrNotItRepeatsAWithheldOne() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN))); + + assertEquals( + List.of(name(SHOWN), profile(HIDDEN)), + saved(stored, operation(OPERATION_ID, name(SHOWN), profile(HIDDEN)))); + assertEquals( + List.of(name(SHOWN), profile(HIDDEN)), + saved(stored, operation(OPERATION_ID, name(SHOWN), lineage(HIDDEN)))); + } + + @Test + void anOperationTheDraftDoesNotStoreKeepsTheEntriesItsWriterMayView() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN))); + + assertEquals( + List.of(name(SHOWN)), + saved(stored, operation(UUID.randomUUID(), lineage(HIDDEN), name(SHOWN)))); + assertEquals( + List.of(testCase(SHOWN)), + saved(List.of(), operation(OPERATION_ID, profile(HIDDEN), testCase(SHOWN)))); + assertEquals(List.of(), saved(List.of(), operation(OPERATION_ID, lineage(HIDDEN)))); + assertNull(saved(stored, operation(UUID.randomUUID()))); + } + + @Test + void aSaveRefusesMoreEvidenceThanAnOperationHolds() { + final List stored = + List.of(operation(OPERATION_ID, profile(HIDDEN), lineage(HIDDEN))); + final OntologyChangeEvidence[] sent = + IntStream.range(0, 19) + .mapToObj(index -> name(SHOWN).withColumns(List.of(List.of("column_" + index)))) + .toArray(OntologyChangeEvidence[]::new); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> view.savedByReader(stored, List.of(operation(OPERATION_ID, sent)))); + + assertEquals( + "Ontology operation '" + + OPERATION_ID + + "' is invalid: evidence holds at most 20 entries, counting the 2 that a read withheld", + refusal.getMessage()); + } + + private List saved( + final List stored, final OntologyChangeOperation sent) { + return view.savedByReader(stored, List.of(sent)).getFirst().getEvidence(); + } + + private static OntologyChangeSet changeSet(final OntologyChangeOperation... operations) { + return new OntologyChangeSet().withOperations(List.of(operations)); + } + + private static OntologyChangeOperation operation( + final UUID id, final OntologyChangeEvidence... evidence) { + return new OntologyChangeOperation() + .withId(id) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withEvidence(evidence.length == 0 ? null : List.of(evidence)); + } + + private static OntologyChangeEvidence name(final UUID tableId) { + return entry(tableId, OntologyChangeEvidenceKind.NAME); + } + + private static OntologyChangeEvidence profile(final UUID tableId) { + return entry(tableId, OntologyChangeEvidenceKind.PROFILE); + } + + private static OntologyChangeEvidence lineage(final UUID tableId) { + return entry(tableId, OntologyChangeEvidenceKind.LINEAGE); + } + + private static OntologyChangeEvidence testCase(final UUID tableId) { + return entry(tableId, OntologyChangeEvidenceKind.TEST_CASE); + } + + private static OntologyChangeEvidence entry( + final UUID tableId, final OntologyChangeEvidenceKind kind) { + return new OntologyChangeEvidence().withTableId(tableId).withKind(kind); + } +} From cec2180cc2b07cc68bafc544fb411fb7bd1336d9 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 12:56:20 -0800 Subject: [PATCH 040/203] Add integration tests for change set bindings, shapes and evidence OntologyChangeSetBindingIT applies a draft that creates a class, a property, a binding and a shape, and covers each refusal at save and at apply. OntologyChangeSetEvidenceIT reads and writes evidence as a caller who may not view one of the tables, on every endpoint that returns operations. OntologyChangeSetEvidenceMcpIT does the same through get_entity_details and patch_entity. OntologyRowFilterValueIT leaves the one row filter case that is written through a change set to OntologyChangeSetBindingIT. --- .../it/tests/OntologyChangeSetBindingIT.java | 515 ++++++++++++++++++ .../it/tests/OntologyChangeSetEvidenceIT.java | 367 +++++++++++++ .../tests/OntologyChangeSetEvidenceMcpIT.java | 158 ++++++ .../it/tests/OntologyDraftFixtures.java | 293 ++++++++++ .../it/tests/OntologyRowFilterValueIT.java | 4 +- 5 files changed, 1335 insertions(+), 2 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceMcpIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftFixtures.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java new file mode 100644 index 000000000000..bc2e9fa5fad9 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java @@ -0,0 +1,515 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.apply; +import static org.openmetadata.it.tests.OntologyDraftFixtures.assertNotFound; +import static org.openmetadata.it.tests.OntologyDraftFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.boundColumn; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.discard; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.joinTo; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedDataProperty; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedShape; +import static org.openmetadata.it.tests.OntologyDraftFixtures.read; +import static org.openmetadata.it.tests.OntologyDraftFixtures.replaceOperations; +import static org.openmetadata.it.tests.OntologyDraftFixtures.workingRevision; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.conceptsBoundTo; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeSetState; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyHydratedAssetBinding; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeBasis; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.service.Entity; + +/** + * A draft that carries table bindings and shapes beside the definitions they belong to: what a + * save checks, what an apply writes and with whose rights, and when an apply is refused. One + * refusal is a case of {@code ontology/sql-value-cases.json}, the one that writes its row filter + * through a change set. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetBindingIT extends BaseOntologyApprovalIT { + private static final URI INVOICE = URI.create("urn:Invoice"); + private static final URI CUSTOMER_NAME = URI.create("urn:customerName"); + private static final int BAD_REQUEST = 400; + private static final int FORBIDDEN = 403; + private static final int PRECONDITION_FAILED = 412; + private static final String NOT_A_WHOLE_NUMBER = + "The value for column qty does not parse as INT: a whole number is written in ASCII digits," + + " with a leading minus sign when negative and no leading zeros"; + + @Test + void aDraftThatProposesAClassItsPropertyItsTableAndAShapeAppliesAsOne(final TestNamespace ns) { + final Proposal proposal = propose(ns, createOntology(ns)); + + final OntologyChangeSet applied = apply(admin(), proposal.draft()); + + assertEquals(OntologyChangeSetState.APPLIED, applied.getState()); + assertEquals(4, applied.getApplicationResult().getOperationsApplied()); + assertEquals(CUSTOMER, admin().ontologyConcepts().get(proposal.customer().getId()).getIri()); + assertEquals( + List.of(CUSTOMER), admin().ontologyProperties().get(proposal.name().getId()).getDomain()); + final var bound = bindings(admin(), proposal.customer()); + assertEquals(1L, bound.getRevision()); + final OntologyHydratedAssetBinding held = bound.getAssets().getFirst(); + assertEquals(proposal.customers().getId(), held.getAssetId()); + assertEquals(OntologyBindingRole.IDENTITY, held.getRole()); + assertEquals(List.of(List.of("id")), held.getSubjectKey()); + assertEquals(proposal.name().getId(), held.getColumns().getFirst().getPropertyId()); + assertEquals(List.of("name"), held.getColumns().getFirst().getColumnPath()); + final OntologyShape shape = admin().ontologyShapes().get(proposal.named().getId()); + assertEquals(CUSTOMER, shape.getTargetConcept()); + assertEquals(CUSTOMER_NAME, shape.getConstraints().getFirst().getPath()); + assertEquals(1, shape.getConstraints().getFirst().getMinCount()); + assertEquals(OntologyShapeBasis.OBSERVED, applied.getOperations().getLast().getBasis()); + } + + @Test + void discardingTheDraftCreatesNothing(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Proposal proposal = propose(ns, ontology); + final long revision = workingRevision(ontology); + + final OntologyChangeSet discarded = discard(admin(), proposal.draft()); + + assertEquals(OntologyChangeSetState.DISCARDED, discarded.getState()); + assertNothingWasWritten(proposal); + assertEquals(revision, workingRevision(ontology)); + } + + @Test + void aDraftBuiltBeforeAnUnrelatedEditIsStillReadAndNarrowedAndIsRefusedAtApply( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Proposal proposal = propose(ns, ontology); + declareClass(ontology, "Invoice", INVOICE); + + final List read = read(admin(), proposal.draft()).getOperations(); + final OntologyEditLeaseToken lease = lease(admin(), proposal.draft()); + final OntologyChangeSet narrowed = + replaceOperations(admin(), proposal.draft(), lease, read.subList(0, 3)); + + assertEquals(4, read.size()); + assertEquals(ids(read.subList(0, 3)), ids(narrowed.getOperations())); + assertRefused( + PRECONDITION_FAILED, + "Ontology changed since this draft was created", + () -> apply(admin(), proposal.draft(), lease)); + assertNothingWasWritten(proposal); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), proposal.draft()).getState()); + } + + @Test + void aBindingIsWrittenWithTheRightsOfTheCallerWhoAppliesAndNotOfTheAuthor( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table invoices = table(schema(ns), "invoices", column("id", ColumnDataType.BIGINT)); + try (var fixtures = new RdfAccessFixtures("applyRights" + ns.shortPrefix())) { + final OpenMetadataClient seesNoTable = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OntologyConcept refused = proposedClass(ontology, "Invoice", INVOICE); + final OntologyChangeSet byAdmin = + draft(admin(), ns, ontology, creates(refused), binds(bindingOf(INVOICE, invoices))); + + assertRefused(FORBIDDEN, "ViewBasic", () -> apply(seesNoTable, byAdmin)); + assertNotFound(() -> admin().ontologyConcepts().get(refused.getId())); + assertEquals(List.of(), conceptsBoundTo(admin(), invoices).getLinks()); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), byAdmin).getState()); + + final OntologyConcept written = proposedClass(ontology, "Invoice", INVOICE); + final OntologyChangeSet byCaller = + draft(seesNoTable, ns, ontology, creates(written), binds(bindingOf(INVOICE, invoices))); + + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), byCaller).getState()); + assertEquals(List.of(invoices.getId()), boundTables(written)); + } + } + + @Test + void aRowFilterAppliedByACallerWithoutViewSampleDataIsRefusedAsItsCaseExpects( + final TestNamespace ns) { + final JsonNode json = caseWrittenThroughAChangeSet(); + final OntologyRowFilter rowFilter = rowFilterOf(json); + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table people = + table( + schema(ns), + "people", + column( + rowFilter.getColumn().getFirst(), + ColumnDataType.fromValue(json.get("columnType").asText()))); + try (var fixtures = new RdfAccessFixtures("applyFilter" + ns.shortPrefix())) { + final OpenMetadataClient seesNoSample = + callerWithout(fixtures, MetadataOperation.VIEW_SAMPLE_DATA, Entity.TABLE, null); + final OntologyChangeSet draft = + draft(admin(), ns, ontology, binds(bindingOf(ORDER, people).withRowFilter(rowFilter))); + + final OpenMetadataException refusal = + assertThrows(OpenMetadataException.class, () -> apply(seesNoSample, draft)); + + assertEquals( + json.at("/expectedOutcome/status").asInt(), refusal.getStatusCode(), refusal::getMessage); + json.at("/expectedOutcome/messageContains") + .forEach( + part -> + assertTrue(refusal.getMessage().contains(part.asText()), refusal::getMessage)); + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), draft).getState()); + assertEquals(rowFilter, bindings(admin(), order).getAssets().getFirst().getRowFilter()); + } + } + + @Test + void aRowFilterValueThatDoesNotParseAsTheTypeOfItsColumnIsRefusedAtApply(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table orders = table(schema(ns), "orders", column("qty", ColumnDataType.INT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, orders) + .withRowFilter(filter("qty", OntologyRowFilterOperator.EQUALS, "abc")))); + + assertRefused(BAD_REQUEST, NOT_A_WHOLE_NUMBER, () -> apply(admin(), draft)); + + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), draft).getState()); + } + + @Test + void aJoinThatAnOperationWritesIsStoredAsInferredEvenAfterAPersonConfirmedIt( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept customer = declareClass(ontology, "Customer", CUSTOMER); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final DatabaseSchema schema = schema(ns); + final Table customers = table(schema, "customers", column("id", ColumnDataType.BIGINT)); + final Table orders = orders(schema); + final OntologyProperty placedBy = objectProperty(ontology, "placedBy", order, customer); + final OntologyBindingChange joined = + bindingOf(ORDER, orders) + .withColumns( + List.of( + boundColumn(placedBy.getIri(), "customer_id") + .withJoin(joinTo(customers, "customer_id", "id")))); + + apply(admin(), draft(admin(), ns, ontology, binds(joined))); + + assertEquals(customers.getId(), storedJoin(order).getTargetAssetId()); + assertEquals(OntologyJoinStatus.INFERRED, storedJoin(order).getStatus()); + final OntologyColumnBinding confirmed = + column(placedBy, "customer_id") + .withJoin(join(customers, OntologyJoinStatus.CONFIRMED, "customer_id", "id")); + put(admin(), order, binding(orders).withColumns(List.of(confirmed)), 1L); + assertEquals(OntologyJoinStatus.CONFIRMED, storedJoin(order).getStatus()); + + apply(admin(), draft(admin(), ns, ontology, binds(joined).withBaseVersion(2.0))); + + assertEquals(OntologyJoinStatus.INFERRED, storedJoin(order).getStatus()); + assertEquals(3L, bindings(admin(), order).getRevision()); + } + + @Test + void aBindingOperationBuiltAgainstAnEarlierBindingRevisionIsRefusedAndAppliesOnceRebuilt( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + put(admin(), order, binding(orders), 0L); + final OntologyChangeOperation keyed = + binds(keyed(orders, OntologyBindingRole.IDENTITY)).withBaseVersion(1.0); + final OntologyChangeSet draft = draft(admin(), ns, ontology, keyed); + put(admin(), order, binding(orders, OntologyBindingRole.CONTRIBUTING, "order_id"), 1L); + + assertRefused( + PRECONDITION_FAILED, + "The binding of class urn:Order to table " + + orders.getId() + + " changed since operation '" + + keyed.getId() + + "' was built: the operation carries binding revision 1 and the class is at binding" + + " revision 2", + () -> apply(admin(), draft)); + assertEquals( + OntologyBindingRole.CONTRIBUTING, + bindings(admin(), order).getAssets().getFirst().getRole()); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), draft).getState()); + + final OntologyEditLeaseToken lease = lease(admin(), draft); + replaceOperations(admin(), draft, lease, List.of(keyed.withBaseVersion(2.0))); + + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), draft, lease).getState()); + assertEquals(3L, bindings(admin(), order).getRevision()); + assertEquals( + OntologyBindingRole.IDENTITY, bindings(admin(), order).getAssets().getFirst().getRole()); + } + + @Test + void aBindingOperationBuiltWhenItsTableWasNotBoundIsRefusedOnceTheTableIsBound( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + final OntologyChangeOperation keyed = binds(keyed(orders, OntologyBindingRole.IDENTITY)); + final OntologyChangeSet draft = draft(admin(), ns, ontology, keyed); + put(admin(), order, binding(orders), 0L); + + assertRefused( + PRECONDITION_FAILED, + "The binding of class urn:Order to table " + + orders.getId() + + " changed since operation '" + + keyed.getId() + + "' was built: the operation carries no binding revision and the class is at binding" + + " revision 1", + () -> apply(admin(), draft)); + assertEquals(1L, bindings(admin(), order).getRevision()); + } + + @Test + void aDraftChangesTwoBindingsOfOneClassThatItReadAtOneRevision(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final DatabaseSchema schema = schema(ns); + final Table orders = orders(schema); + final Table archive = + table(schema, "orders_archive", column("order_id", ColumnDataType.BIGINT)); + put(admin(), order, binding(orders), 0L); + put(admin(), order, binding(archive), 1L); + + final OntologyChangeSet applied = + apply( + admin(), + draft( + admin(), + ns, + ontology, + binds(keyed(orders, OntologyBindingRole.IDENTITY)).withBaseVersion(2.0), + binds(keyed(archive, OntologyBindingRole.CONTRIBUTING)).withBaseVersion(2.0))); + + assertEquals(OntologyChangeSetState.APPLIED, applied.getState()); + final var bound = bindings(admin(), order); + assertEquals(4L, bound.getRevision()); + assertEquals(OntologyBindingRole.IDENTITY, roleOf(bound.getAssets(), orders)); + assertEquals(OntologyBindingRole.CONTRIBUTING, roleOf(bound.getAssets(), archive)); + } + + @Test + void aSaveRefusesABindingOrAShapeThatNamesWhatDoesNotExist(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + final UUID noTable = UUID.randomUUID(); + + assertRefused( + BAD_REQUEST, + "names the table " + noTable + ", which does not exist", + () -> + draft( + admin(), + ns, + ontology, + binds(new OntologyBindingChange().withClassIri(ORDER).withTableId(noTable)))); + assertRefused( + BAD_REQUEST, + "names the column missing, which table " + orders.getId() + " does not have", + () -> + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, orders) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("missing")))))); + assertRefused( + BAD_REQUEST, + "needs the class urn:Invoice, which the ontology does not declare and no earlier" + + " operation creates", + () -> + draft( + admin(), + ns, + ontology, + binds(bindingOf(INVOICE, orders)), + creates(proposedClass(ontology, "Invoice", INVOICE)))); + + final OntologyChangeSet draft = draft(admin(), ns, ontology, binds(bindingOf(ORDER, orders))); + final OntologyShape paid = proposedShape(ontology, "PaidInvoice", INVOICE, CUSTOMER_NAME); + assertRefused( + BAD_REQUEST, + "needs the class urn:Invoice, which the ontology does not declare and no earlier" + + " operation creates", + () -> replaceOperations(admin(), draft, lease(admin(), draft), List.of(creates(paid)))); + assertEquals(1, read(admin(), draft).getOperations().size()); + } + + /** A draft that proposes a class with the property, the table and the shape that belong to it. */ + private record Proposal( + Table customers, + OntologyConcept customer, + OntologyProperty name, + OntologyShape named, + OntologyChangeSet draft) {} + + private static Proposal propose(final TestNamespace ns, final Ontology ontology) { + final Table customers = + table( + schema(ns), + "customers", + column("id", ColumnDataType.BIGINT), + column("name", ColumnDataType.VARCHAR)); + final OntologyConcept customer = proposedClass(ontology, "Customer", CUSTOMER); + final OntologyProperty name = + proposedDataProperty(ontology, "customerName", CUSTOMER_NAME, CUSTOMER); + final OntologyShape named = proposedShape(ontology, "NamedCustomer", CUSTOMER, CUSTOMER_NAME); + final OntologyBindingChange held = + bindingOf(CUSTOMER, customers) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("id"))) + .withColumns(List.of(boundColumn(CUSTOMER_NAME, "name"))); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(customer), + creates(name), + binds(held).withRequiresConceptIris(List.of(CUSTOMER)), + creates(named) + .withBasis(OntologyShapeBasis.OBSERVED) + .withRequiresConceptIris(List.of(CUSTOMER))); + return new Proposal(customers, customer, name, named, draft); + } + + private static void assertNothingWasWritten(final Proposal proposal) { + assertNotFound(() -> admin().ontologyConcepts().get(proposal.customer().getId())); + assertNotFound(() -> admin().ontologyProperties().get(proposal.name().getId())); + assertNotFound(() -> admin().ontologyShapes().get(proposal.named().getId())); + assertEquals(List.of(), conceptsBoundTo(admin(), proposal.customers()).getLinks()); + } + + private static Table orders(final DatabaseSchema schema) { + return table( + schema, + "orders", + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + } + + /** A binding of {@code table} to the order class, keyed by the order id. */ + private static OntologyBindingChange keyed(final Table table, final OntologyBindingRole role) { + return bindingOf(ORDER, table).withRole(role).withSubjectKey(List.of(List.of("order_id"))); + } + + private static List ids(final List operations) { + return operations.stream().map(OntologyChangeOperation::getId).toList(); + } + + private static OntologyBindingRole roleOf( + final List assets, final Table table) { + return assets.stream() + .filter(asset -> table.getId().equals(asset.getAssetId())) + .findFirst() + .orElseThrow() + .getRole(); + } + + private static List boundTables(final OntologyConcept concept) { + return bindings(admin(), concept).getAssets().stream() + .map(OntologyHydratedAssetBinding::getAssetId) + .toList(); + } + + /** The join of the one column the order class binds. */ + private static OntologyColumnJoin storedJoin(final OntologyConcept order) { + return bindings(admin(), order).getAssets().getFirst().getColumns().getFirst().getJoin(); + } + + /** The one case of the file whose row filter is written by applying a change set. */ + private static JsonNode caseWrittenThroughAChangeSet() { + final List cases = + OntologySqlValueCases.withOutcome("refusedAtSave").stream() + .filter(json -> "changeSet".equals(json.at("/input/via").asText())) + .toList(); + assertEquals(List.of("PRB-005"), cases.stream().map(json -> json.get("id").asText()).toList()); + assertEquals(FORBIDDEN, cases.getFirst().at("/expectedOutcome/status").asInt()); + assertEquals( + "ViewSampleData", cases.getFirst().at("/expectedOutcome/messageContains/0").asText()); + return cases.getFirst(); + } + + /** The row filter a case carries beside the path that writes it. */ + private static OntologyRowFilter rowFilterOf(final JsonNode json) { + final ObjectNode input = json.get("input").deepCopy(); + input.remove("via"); + return JsonUtils.getObjectMapper().convertValue(input, OntologyRowFilter.class); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java new file mode 100644 index 000000000000..2cc0890906ea --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java @@ -0,0 +1,367 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.apply; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.discard; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.evidence; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyDraftFixtures.path; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.read; +import static org.openmetadata.it.tests.OntologyDraftFixtures.release; +import static org.openmetadata.it.tests.OntologyDraftFixtures.replaceOperations; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import java.time.Duration; +import java.util.List; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.ApplyOntologyChangeSet; +import org.openmetadata.schema.api.data.OntologyChangeSetCommand; +import org.openmetadata.schema.api.data.RestoreEntity; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.locator.ConnectionType; + +/** + * The evidence of a draft's operations as each caller reads and writes it. Each endpoint that + * answers with operations leaves out the entries whose table its caller may not view and counts + * them. A save stores no entry about such a table and keeps the entries its writer was not shown. No + * stored change event and no recorded change carries an entry, because neither has a single reader. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetEvidenceIT extends BaseOntologyApprovalIT { + private static final List> ID_COLUMN = List.of(List.of("id")); + private static final String CREATED = "entityCreated"; + private static final String UPDATED = "entityUpdated"; + private static final String APPLIED = "ontologyChangeSetApplied"; + + @Test + void aReadLeavesOutTheEvidenceOfTablesTheReaderMayNotViewAndCountsIt(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("readEvidence" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OntologyConcept customer = proposedClass(ontology, "Customer", CUSTOMER); + final OntologyChangeOperation supported = + creates(customer).withEvidence(scene.evidenceOfBothTables()); + final OntologyChangeSet draft = draft(admin(), ns, ontology, supported); + final OntologyEditLeaseToken lease = lease(admin(), draft); + customer.setDescription("A party that buys"); + replaceOperations(admin(), draft, lease, List.of(supported)); + release(admin(), draft, lease); + + final OntologyChangeOperation seen = read(scene.reader(), draft).getOperations().getFirst(); + final OntologyChangeOperation stored = read(admin(), draft).getOperations().getFirst(); + + assertEquals(List.of(scene.aboutTheShownTable()), seen.getEvidence()); + assertEquals(1, seen.getWithheldEvidenceCount()); + assertEquals(scene.evidenceOfBothTables(), stored.getEvidence()); + assertEquals(0, stored.getWithheldEvidenceCount()); + final String versions = path(draft) + "/versions"; + scene.assertReaderView("get", get(scene.reader(), path(draft))); + scene.assertReaderView( + "list", get(scene.reader(), CHANGE_SETS + "?ontologyId=" + ontology.getId())); + scene.assertReaderView("versions", get(scene.reader(), versions)); + scene.assertReaderView("version", get(scene.reader(), versions + "/0.1")); + assertTrue(get(admin(), versions).contains(scene.hidden().getId().toString())); + assertEquals( + 2, admin().ontologyChangeSets().getVersionList(draft.getId()).getVersions().size()); + } + } + + @Test + void aWriteAnswersItsCallerWithTheSameViewAndKeepsTheEntriesTheCallerWasNotShown( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("writeEvidence" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OpenMetadataClient reader = scene.reader(); + final OntologyChangeEvidence added = + evidence(scene.shown(), OntologyChangeEvidenceKind.LINEAGE); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(scene.evidenceOfBothTables())); + final OntologyChangeOperation seen = read(reader, draft).getOperations().getFirst(); + final OntologyEditLeaseToken lease = lease(reader, draft); + final OntologyChangeSetCommand command = new OntologyChangeSetCommand().withLease(lease); + + final OntologyChangeOperation saved = + replaceOperations( + reader, + draft, + lease, + List.of(seen.withEvidence(List.of(scene.aboutTheShownTable(), added)))) + .getOperations() + .getFirst(); + + assertEquals(List.of(scene.aboutTheShownTable(), added), saved.getEvidence()); + assertEquals(1, saved.getWithheldEvidenceCount()); + assertEquals( + List.of(scene.aboutTheShownTable(), scene.aboutTheHiddenTable(), added), + read(admin(), draft).getOperations().getFirst().getEvidence()); + scene.assertReaderView("undo", post(reader, path(draft) + "/undo", command)); + scene.assertReaderView("redo", post(reader, path(draft) + "/redo", command)); + scene.assertReaderView("submit", post(reader, path(draft) + "/submit", command)); + scene.assertReaderView( + "apply", + post(reader, path(draft) + "/apply", new ApplyOntologyChangeSet().withLease(lease))); + scene.assertReaderView( + "delete", reader.getHttpClient().executeForString(HttpMethod.DELETE, path(draft), null)); + scene.assertReaderView( + "restore", + reader + .getHttpClient() + .executeForString( + HttpMethod.PUT, + CHANGE_SETS + "/restore", + new RestoreEntity().withId(draft.getId()))); + + final OntologyChangeSet discarded = + discard( + reader, + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Order", ORDER)) + .withEvidence(scene.evidenceOfBothTables()))); + assertEquals( + List.of(scene.aboutTheShownTable()), discarded.getOperations().getFirst().getEvidence()); + assertEquals(1, discarded.getOperations().getFirst().getWithheldEvidenceCount()); + } + } + + @Test + void aSaveStoresNoEvidenceAboutATableItsWriterMayNotView(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("saveEvidence" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OpenMetadataClient writer = scene.reader(); + final OntologyChangeOperation supported = + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(scene.evidenceOfBothTables()); + + final OntologyChangeSet created = draft(writer, ns, ontology, supported); + + final OntologyChangeOperation answered = created.getOperations().getFirst(); + assertEquals(List.of(scene.aboutTheShownTable()), answered.getEvidence()); + assertEquals(0, answered.getWithheldEvidenceCount()); + assertEquals( + List.of(scene.aboutTheShownTable()), + read(admin(), created).getOperations().getFirst().getEvidence()); + + final OntologyEditLeaseToken byAdmin = lease(admin(), created); + replaceOperations(admin(), created, byAdmin, List.of(supported)); + release(admin(), created, byAdmin); + final OntologyChangeOperation guessed = + replaceOperations( + writer, + created, + lease(writer, created), + List.of( + answered.withEvidence( + List.of( + scene.aboutTheShownTable(), + scene.aboutTheHiddenTable(), + evidence(scene.hidden(), OntologyChangeEvidenceKind.LINEAGE))))) + .getOperations() + .getFirst(); + + assertEquals(List.of(scene.aboutTheShownTable()), guessed.getEvidence()); + assertEquals(1, guessed.getWithheldEvidenceCount()); + assertEquals( + scene.evidenceOfBothTables(), + read(admin(), created).getOperations().getFirst().getEvidence()); + } + } + + @Test + void anEditOfEvidenceAloneIsStoredWithoutANewVersion(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table customers = table(schema(ns), "customers", column("id", ColumnDataType.BIGINT)); + final OntologyChangeOperation supported = + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(List.of(evidence(customers, OntologyChangeEvidenceKind.NAME))); + final OntologyChangeSet draft = draft(admin(), ns, ontology, supported); + final List profiled = + List.of(evidence(customers, OntologyChangeEvidenceKind.PROFILE).withColumns(ID_COLUMN)); + + final OntologyChangeSet edited = + replaceOperations( + admin(), draft, lease(admin(), draft), List.of(supported.withEvidence(profiled))); + + final OntologyChangeSet stored = read(admin(), draft); + assertEquals(profiled, edited.getOperations().getFirst().getEvidence()); + assertEquals(profiled, stored.getOperations().getFirst().getEvidence()); + assertEquals(draft.getVersion(), stored.getVersion()); + assertEquals( + 1, admin().ontologyChangeSets().getVersionList(draft.getId()).getVersions().size()); + } + + @Test + void noRecordedChangeAndNoStoredChangeEventCarriesTheEvidenceOfADraft(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table customers = table(schema(ns), "customers", column("id", ColumnDataType.BIGINT)); + final OntologyConcept customer = proposedClass(ontology, "Customer", CUSTOMER); + final List named = + List.of(evidence(customers, OntologyChangeEvidenceKind.NAME)); + final OntologyChangeOperation supported = creates(customer).withEvidence(named); + final OntologyChangeSet draft = draft(admin(), ns, ontology, supported); + final OntologyEditLeaseToken lease = lease(admin(), draft); + customer.setDescription("A party that buys"); + + final OntologyChangeSet changed = replaceOperations(admin(), draft, lease, List.of(supported)); + final OntologyChangeSet applied = apply(admin(), draft, lease); + + final String recorded = JsonUtils.pojoToJson(changed.getChangeDescription()); + assertTrue(changed.getVersion() > draft.getVersion()); + assertTrue(recorded.contains(supported.getId().toString()), recorded); + assertFalse(recorded.contains(customers.getId().toString()), recorded); + final List events = storedEvents(draft, CREATED, UPDATED, APPLIED); + for (final String event : events) { + assertFalse(event.contains(customers.getId().toString()), event); + for (final JsonNode operation : storedOperations(event)) { + assertFalse(operation.has("evidence"), event); + assertFalse(operation.has("withheldEvidenceCount"), event); + } + } + for (final String type : List.of(CREATED, APPLIED)) { + final JsonNode operations = storedOperations(ofType(events, type).getFirst()); + assertEquals(supported.getId().toString(), operations.path(0).path("id").asText(), type); + } + assertEquals(named, applied.getOperations().getFirst().getEvidence()); + assertEquals(named, read(admin(), draft).getOperations().getFirst().getEvidence()); + } + + /** A reader who may view the tables they own and no other, with one table of each kind. */ + private record Scene(OpenMetadataClient reader, Table shown, Table hidden) { + private OntologyChangeEvidence aboutTheShownTable() { + return evidence(shown, OntologyChangeEvidenceKind.NAME); + } + + private OntologyChangeEvidence aboutTheHiddenTable() { + return evidence(hidden, OntologyChangeEvidenceKind.PROFILE).withColumns(ID_COLUMN); + } + + private List evidenceOfBothTables() { + return List.of(aboutTheShownTable(), aboutTheHiddenTable()); + } + + /** What the reader is sent: the evidence about the table it may view, and no other table. */ + private void assertReaderView(final String endpoint, final String body) { + assertTrue(body.contains(shown.getId().toString()), endpoint); + assertFalse(body.contains(hidden.getId().toString()), endpoint); + } + } + + private static Scene scene(final TestNamespace ns, final RdfAccessFixtures fixtures) { + final DatabaseSchema schema = schema(ns); + final OpenMetadataClient reader = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final Table shown = + ownedTable( + schema, + "customers", + OntologyBindingFixtures.readerReference(reader), + column("id", ColumnDataType.BIGINT)); + final Table hidden = table(schema, "payments", column("id", ColumnDataType.BIGINT)); + return new Scene(reader, shown, hidden); + } + + private static String get(final OpenMetadataClient caller, final String path) { + return caller.getHttpClient().executeForString(HttpMethod.GET, path, null); + } + + private static String post( + final OpenMetadataClient caller, final String path, final Object body) { + return caller.getHttpClient().executeForString(HttpMethod.POST, path, body); + } + + /** + * The change events stored for a draft, once one of each of these types is stored. The event of a + * request is written after its response is sent. + */ + private static List storedEvents(final OntologyChangeSet draft, final String... types) { + return Awaitility.await("the change events of the draft") + .atMost(Duration.ofSeconds(30)) + .pollInterval(Duration.ofMillis(250)) + .until( + () -> eventsOf(draft), + events -> List.of(types).stream().noneMatch(type -> ofType(events, type).isEmpty())); + } + + private static List eventsOf(final OntologyChangeSet draft) { + final String sql = + TestSuiteBootstrap.getConnectionType() == ConnectionType.MYSQL + ? "SELECT CAST(json AS CHAR) FROM change_event WHERE json ->> '$.entityId' = :id" + : "SELECT json::text FROM change_event WHERE json ->> 'entityId' = :id"; + return Entity.getJdbi() + .withHandle( + handle -> + handle + .createQuery(sql) + .bind("id", draft.getId().toString()) + .mapTo(String.class) + .list()); + } + + private static List ofType(final List events, final String type) { + return events.stream() + .filter(event -> type.equals(JsonUtils.readTree(event).path("eventType").asText())) + .toList(); + } + + /** The operations of the change set an event stores. An event holds its entity as JSON text. */ + private static JsonNode storedOperations(final String event) { + final JsonNode entity = JsonUtils.readTree(event).path("entity"); + return (entity.isTextual() ? JsonUtils.readTree(entity.asText()) : entity).path("operations"); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceMcpIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceMcpIT.java new file mode 100644 index 000000000000..f31a968a5409 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceMcpIT.java @@ -0,0 +1,158 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.evidence; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.read; +import static org.openmetadata.it.tests.OntologyDraftFixtures.tokenWithout; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; +import java.util.stream.StreamSupport; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.tests.mcp.McpTestBase; +import org.openmetadata.it.tests.mcp.McpTestUtils; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.service.Entity; + +/** + * A stored change set as the entity tools hand it to a caller. get_entity_details leaves out the + * evidence about tables its caller may not view and counts it, as every REST read of a change set + * does. patch_entity refuses a change set, because a JSON Patch can copy a stored evidence entry to + * a member that every reader is shown. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetEvidenceMcpIT extends McpTestBase { + private static final String BEARER = "Bearer "; + + /** A draft whose one operation rests on a table the caller owns and on one it may not view. */ + private record Scene(String token, Table shown, Table hidden, OntologyChangeSet draft) {} + + @Test + void theEntityToolLeavesOutTheEvidenceOfTablesItsCallerMayNotView(final TestNamespace ns) + throws Exception { + initAuth(); + final Ontology ontology = BaseOntologyApprovalIT.createOntology(ns); + try (var fixtures = new RdfAccessFixtures("toolEvidence" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, ontology); + final String shown = scene.shown().getId().toString(); + final String hidden = scene.hidden().getId().toString(); + + final JsonNode stored = operationReadBy(authToken, scene.draft()); + final JsonNode seen = operationReadBy(BEARER + scene.token(), scene.draft()); + + assertEquals(List.of(shown, hidden), evidenceTables(stored)); + assertEquals(0, stored.path("withheldEvidenceCount").asInt(-1)); + assertEquals(List.of(shown), evidenceTables(seen)); + assertEquals(1, seen.path("withheldEvidenceCount").asInt(-1)); + assertFalse(seen.toString().contains(hidden), seen::toString); + } + } + + @Test + void thePatchToolRefusesAChangeSetSoNoPatchCopiesEvidenceToAMemberEveryReaderSees( + final TestNamespace ns) throws Exception { + initAuth(); + final Ontology ontology = BaseOntologyApprovalIT.createOntology(ns); + try (var fixtures = new RdfAccessFixtures("toolPatch" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, ontology); + + final JsonNode answer = + executeMcpRequest( + McpTestUtils.createPatchEntityToolCall( + Entity.ONTOLOGY_CHANGE_SET, + scene.draft().getFullyQualifiedName(), + "[{\"op\":\"copy\",\"from\":\"/operations/0/evidence/1/tableId\"," + + "\"path\":\"/description\"}]"), + BEARER + scene.token()); + + assertTrue(answer.at("/result/isError").asBoolean(false), answer::toString); + assertTrue( + answer + .at("/result/content/0/text") + .asText() + .contains("cannot be patched through patch_entity"), + answer::toString); + assertFalse(answer.toString().contains(scene.hidden().getId().toString()), answer::toString); + assertEquals(scene.draft().getDescription(), read(admin(), scene.draft()).getDescription()); + } + } + + private static Scene scene( + final TestNamespace ns, final RdfAccessFixtures fixtures, final Ontology ontology) { + final String token = + tokenWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final DatabaseSchema schema = schema(ns); + final Table shown = + ownedTable( + schema, + "customers", + OntologyBindingFixtures.readerReference(OntologyBindingFixtures.client(token)), + column("id", ColumnDataType.BIGINT)); + final Table hidden = table(schema, "payments", column("id", ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence( + List.of( + evidence(shown, OntologyChangeEvidenceKind.NAME), + evidence(hidden, OntologyChangeEvidenceKind.PROFILE)))); + return new Scene(token, shown, hidden, draft); + } + + /** The one operation of the draft as get_entity_details answers its caller. */ + private JsonNode operationReadBy(final String bearer, final OntologyChangeSet draft) + throws Exception { + final JsonNode response = + executeMcpRequest( + McpTestUtils.createGetEntityToolCall( + Entity.ONTOLOGY_CHANGE_SET, draft.getFullyQualifiedName()), + bearer); + assertFalse(response.at("/result/isError").asBoolean(false), response::toString); + return OBJECT_MAPPER + .readTree(response.at("/result/content/0/text").asText()) + .at("/operations/0"); + } + + private static List evidenceTables(final JsonNode operation) { + return StreamSupport.stream(operation.path("evidence").spliterator(), false) + .map(entry -> entry.path("tableId").asText()) + .toList(); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftFixtures.java new file mode 100644 index 000000000000..6b2d1be70d9a --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftFixtures.java @@ -0,0 +1,293 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.api.data.AcquireOntologyEditLock; +import org.openmetadata.schema.api.data.ApplyOntologyChangeSet; +import org.openmetadata.schema.api.data.CreateOntologyChangeSet; +import org.openmetadata.schema.api.data.OntologyChangeSetCommand; +import org.openmetadata.schema.api.data.UpdateOntologyChangeSet; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationState; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyConceptType; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyEditLock; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; + +/** REST helpers shared by the tests of change sets that carry table bindings, shapes and evidence. */ +final class OntologyDraftFixtures { + static final String CHANGE_SETS = "/v1/ontologyChangeSets"; + private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + private static final String CHANGE_SET = "ontologyChangeSet"; + private static final String EVERY_RESOURCE = "All"; + private static final int LEASE_SECONDS = 60; + + private OntologyDraftFixtures() {} + + /** + * A caller who holds every right on every resource but one. The tests give a role that denies + * the right under test, so a refusal can come from that right alone. + */ + static OpenMetadataClient callerWithout( + final RdfAccessFixtures fixtures, + final MetadataOperation denied, + final String resource, + final String condition) { + return OntologyBindingFixtures.client(tokenWithout(fixtures, denied, resource, condition)); + } + + /** The token of such a caller, for a request that no SDK client sends. */ + static String tokenWithout( + final RdfAccessFixtures fixtures, + final MetadataOperation denied, + final String resource, + final String condition) { + final var everything = fixtures.allowRole(MetadataOperation.ALL, EVERY_RESOURCE); + final var without = fixtures.denyRole(denied, resource, condition); + return fixtures.userToken("caller", List.of(everything.getId(), without.getId())); + } + + static OntologyChangeSet draft( + final OpenMetadataClient author, + final TestNamespace ns, + final Ontology ontology, + final OntologyChangeOperation... operations) { + return ns.trackRoot( + CHANGE_SET, + author + .ontologyChangeSets() + .create( + new CreateOntologyChangeSet() + .withName(ns.prefix("draft") + UUID.randomUUID()) + .withDisplayName("Proposed mapping") + .withDescription("Definitions with the tables that hold them") + .withOntology(ontology.getFullyQualifiedName()) + .withBaseWorkingRevision(workingRevision(ontology)) + .withOperations(List.of(operations)))); + } + + static long workingRevision(final Ontology ontology) { + return admin().ontologies().state(ontology.getId()).getWorkingRevision(); + } + + /** The lease that every command on a draft carries. One caller holds one lease on a draft. */ + static OntologyEditLeaseToken lease( + final OpenMetadataClient caller, final OntologyChangeSet draft) { + final OntologyEditLock lock = + caller + .ontologyEditLocks() + .acquire( + new AcquireOntologyEditLock() + .withResourceType(CHANGE_SET) + .withResourceId(draft.getId()) + .withSessionId(UUID.randomUUID().toString()) + .withLeaseSeconds(LEASE_SECONDS)); + return new OntologyEditLeaseToken() + .withSessionId(lock.getSessionId()) + .withVersion(lock.getVersion()); + } + + /** + * Applies under a lease of the caller's own. A refused apply keeps its lease, so this gives the + * lease up before it reports the refusal and another caller can apply the same draft. + */ + static OntologyChangeSet apply(final OpenMetadataClient caller, final OntologyChangeSet draft) { + final OntologyEditLeaseToken lease = lease(caller, draft); + try { + return apply(caller, draft, lease); + } catch (final OpenMetadataException refused) { + release(caller, draft, lease); + throw refused; + } + } + + static OntologyChangeSet apply( + final OpenMetadataClient caller, + final OntologyChangeSet draft, + final OntologyEditLeaseToken lease) { + return caller + .ontologyChangeSets() + .apply(draft.getId(), new ApplyOntologyChangeSet().withLease(lease)); + } + + static void release( + final OpenMetadataClient caller, + final OntologyChangeSet draft, + final OntologyEditLeaseToken lease) { + caller.ontologyEditLocks().release(CHANGE_SET, draft.getId(), lease.getSessionId()); + } + + /** Replaces the operations of a draft and leaves every one of them active. */ + static OntologyChangeSet replaceOperations( + final OpenMetadataClient caller, + final OntologyChangeSet draft, + final OntologyEditLeaseToken lease, + final List operations) { + return caller + .ontologyChangeSets() + .replaceOperations( + draft.getId(), + new UpdateOntologyChangeSet() + .withLease(lease) + .withOperations(operations) + .withUndoCursor(operations.size())); + } + + static OntologyChangeSet discard(final OpenMetadataClient caller, final OntologyChangeSet draft) { + return caller + .ontologyChangeSets() + .discard(draft.getId(), new OntologyChangeSetCommand().withLease(lease(caller, draft))); + } + + static String path(final OntologyChangeSet draft) { + return CHANGE_SETS + "/" + draft.getId(); + } + + static OntologyChangeSet read(final OpenMetadataClient reader, final OntologyChangeSet draft) { + return reader.ontologyChangeSets().get(draft.getId().toString()); + } + + static OntologyChangeOperation creates(final OntologyConcept concept) { + return operation(OntologyChangeOperationType.UPSERT_CONCEPT).withConcept(concept); + } + + static OntologyChangeOperation creates(final OntologyProperty property) { + return operation(OntologyChangeOperationType.UPSERT_PROPERTY).withProperty(property); + } + + static OntologyChangeOperation creates(final OntologyShape shape) { + return operation(OntologyChangeOperationType.UPSERT_SHAPE).withShape(shape); + } + + static OntologyChangeOperation binds(final OntologyBindingChange binding) { + return operation(OntologyChangeOperationType.UPSERT_BINDING).withBinding(binding); + } + + private static OntologyChangeOperation operation(final OntologyChangeOperationType type) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(type) + .withState(OntologyChangeOperationState.ACTIVE); + } + + /** A class that a draft proposes and that the ontology does not declare yet. */ + static OntologyConcept proposedClass(final Ontology ontology, final String name, final URI iri) { + return new OntologyConcept() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName(ontology.getFullyQualifiedName() + "." + name) + .withOntology(ontology.getEntityReference()) + .withIri(iri) + .withConceptType(OntologyConceptType.OWL_CLASS) + .withVersion(0.1); + } + + static OntologyProperty proposedDataProperty( + final Ontology ontology, final String name, final URI iri, final URI domain) { + return new OntologyProperty() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName(ontology.getFullyQualifiedName() + "." + name) + .withOntology(ontology.getEntityReference()) + .withIri(iri) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(domain)) + .withRange(List.of(XSD_STRING)) + .withVersion(0.1); + } + + /** A shape that requires at least one value of {@code path} on every record of the class. */ + static OntologyShape proposedShape( + final Ontology ontology, final String name, final URI targetClass, final URI path) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withName(name) + .withDisplayName(name) + .withDescription("Every record states the value") + .withFullyQualifiedName(ontology.getFullyQualifiedName() + "." + name) + .withOntology(ontology.getEntityReference()) + .withTargetConcept(targetClass) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + List.of(new OntologyShapeConstraint().withId("stated").withPath(path).withMinCount(1))) + .withVersion(0.1); + } + + static OntologyBindingChange bindingOf(final URI classIri, final Table table) { + return new OntologyBindingChange().withClassIri(classIri).withTableId(table.getId()); + } + + static OntologyColumnBindingChange boundColumn(final URI propertyIri, final String column) { + return new OntologyColumnBindingChange() + .withPropertyIri(propertyIri) + .withColumnPath(List.of(column)); + } + + static OntologyJoinChange joinTo(final Table target, final String child, final String parent) { + return new OntologyJoinChange() + .withTargetAssetId(target.getId()) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(child)) + .withParent(List.of(parent)))); + } + + static OntologyChangeEvidence evidence(final Table table, final OntologyChangeEvidenceKind kind) { + return new OntologyChangeEvidence().withTableId(table.getId()).withKind(kind); + } + + /** The refusal of a request, which must answer {@code status} with {@code message} in its text. */ + static OpenMetadataException assertRefused( + final int status, final String message, final Runnable request) { + final var refused = assertThrows(OpenMetadataException.class, request::run); + assertEquals(status, refused.getStatusCode(), refused::getMessage); + assertTrue( + refused.getMessage().contains(message), + () -> "expects '" + message + "' in " + refused.getMessage()); + return refused; + } + + static void assertNotFound(final Runnable read) { + assertEquals(404, assertThrows(OpenMetadataException.class, read::run).getStatusCode()); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRowFilterValueIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRowFilterValueIT.java index 0feee25a1b6c..e4cd19bccc0e 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRowFilterValueIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRowFilterValueIT.java @@ -148,8 +148,8 @@ void aValueOfTheDataTypeOfItsColumnIsStoredAsItWasWrittenAndReadBack(final TestN } /** - * One case of the file writes through a change set. No change set operation writes a binding, so - * that case has no request to send. + * One case of the file writes through a change set. OntologyChangeSetBindingIT applies that + * change set, so this test leaves the case out. */ @Test void aCallerWithoutViewSampleDataSetsAndChangesNoRowFilterOfTheCases(final TestNamespace ns) { From 28ce6a64cee3005b00b82fd666398f5a67b9874a Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 12:56:31 -0800 Subject: [PATCH 041/203] Record that a change set carries table bindings and shapes The new record states the two operation types, what a save and an apply check, how a binding operation shows which binding revision it was built against, and how evidence passes through the view of each caller. The bindings record gains an amendment, because a change set operation now writes a binding beside the bindings API. --- ...pt-bindings-remain-operational-metadata.md | 11 ++ ...set-can-carry-table-bindings-and-shapes.md | 127 ++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md diff --git a/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md b/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md index 68329d134fec..93149780cc07 100644 --- a/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md +++ b/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md @@ -3,6 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-10-19 (initial) · v2 2026-10-23 (binding rows, bounded paging, the ontology data graph) · v3 2026-10-24 (write confirmation and complete read recovery) · v4 2026-10-26 (paged cleanup under the lock, lineage between returned assets) · v5 2026-10-26 (stateless combined graph pages) · v6 2026-10-30 (Data mode bindings page size and stale reload budget) · v7 2026-11-15 (UI guards moved to Collate) · v8 2026-11-21 (a table binding carries a role, a subject key, a row filter and joins) + · v9 2026-11-22 (a change set operation also writes a binding) - **Deciders:** Ontology Studio implementation review - **Guard:** OntologyConceptBindingsIT, OntologyConceptBindingCleanupIT, NativeOntologyDataGraphIT, NativeOntologyDataGraphEdgeScanIT, NativeOntologyDataGraphBindingScanIT, NativeOntologyDataGraphPageIT, NativeOntologyDataGraphContextIT, NativeOntologyDataGraphPagerTest, NativeOntologyDataGraphPagerRequestTest (including #aTokenTheServerKeySealedGetsTheRandomBytesRefusalBeforeAnyRead and #withoutAServerKeyAContinuedTopologyIssuesACursorTheNextRequestAccepts), NativeOntologyTopologyCursorCodecTest (including #aCursorKeyIsTheHmacOfItsServerKeyAndTheCursorLabel, #aCursorSealedUnderTheDerivedSecondKeyOfARotatedListStillOpens, #withoutAServerKeyOneKeyHeldForTheProcessSealsAndOpensCursors and #withoutAServerKeyACursorSealedWithAnotherKeyGetsTheSameRefusal), OntologyPrefixLineageDaoTest, OntologyBindingRulesTest, OntologyConceptBindingMigrationTest, ontologyAPI.test.ts, useOntologyConceptBindings.test.tsx *(openmetadata-collate)*, OntologyConceptAssets.test.tsx *(openmetadata-collate)*, OntologyColumnBindingEditor.test.tsx *(openmetadata-collate)*, OntologyPropertyBindings.test.tsx *(openmetadata-collate)*, OntologyConceptDataGraph.test.tsx, OntologyConceptInspector.test.tsx *(openmetadata-collate)* - **Related:** ADR:2026-10-17-glossaries-do-not-own-ontology-models, @@ -81,3 +82,13 @@ Writes still require concept `EditAll` and target `ViewBasic`. A write that sets The decision above describes a column assignment as a data-property UUID. The API also accepts an OBJECT property, and a column assignment to one that a write adds or changes must now carry a join. Once the ontology names a mapping source, a table binding that a write adds or changes must sit in that database. The identical-retry rule is unchanged. A write that repeats the stored row is a no-op and is checked against none of these rules, so a row written before them stays as it is until someone changes it. The tests that the new record names guard this amendment. + +## Amendment 2026-11-22. A change set operation also writes a binding + +The Decision gives the concept bindings API as the writer of bindings. An `UPSERT_BINDING` operation of a change set now writes one too (ADR:2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes). + +The operation writes through the step that checks and saves a binding row for the API, under the same ontology lock, and as the caller who applies the change set. Every rule of this record and of ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records therefore holds for it: the rights on the concept and the target, the single revision increment for each write that changes something, the cleanup of links to deleted assets, and the identical retry that is a no-op. + +Two things differ from the API. An operation proves what it read with the binding revision it carries, where the API takes `expectedRevision`. A stale operation is a 412 that names the binding, where the API answers 409. And the join that an operation writes is always stored as `inferred`. Only the API stores `confirmed`. + +Bindings stay operational metadata. A binding operation changes no definition, so applying it does not move the semantic working revision, and bindings stay out of concept JSON, release digests and RDF import and export. The tests that the new record names guard this amendment. diff --git a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md new file mode 100644 index 000000000000..5a43f2115ad6 --- /dev/null +++ b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md @@ -0,0 +1,127 @@ +# An ontology change set can carry table bindings and shapes + +- **Status:** Accepted +- **Revisions:** v1 2026-11-22 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyBindingAndShapeOperationTest`, `OntologyDraftPreflightTest`, `OntologyBindingChangeExecutorTest`, `OntologyChangeApplicationServiceTest`, `OntologyChangeEvidenceViewTest`, `OntologyChangeSetBindingIT`, `OntologyChangeSetEvidenceIT`, `OntologyChangeSetEvidenceMcpIT`, `PatchEntityToolTest` +- **Related:** ADR:2026-10-19-native-concept-bindings-remain-operational-metadata (amended by this + record), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records, + ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints, + ADR:2026-10-26-masked-fields-stay-out-of-change-events-and-version-history, + ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights + +## Context + +A change set carries classes, properties and axioms, and a person reviews and applies it as one +draft. A table binding and a shape were each written through their own API, one request at a time +and outside any draft. A draft that proposed a class could therefore not show, beside it, the table +that holds its records or the constraints those records should meet. Whoever applied the draft +wrote those afterwards, and a refusal then left the class in place without them. + +A reviewer also could not see what a proposed operation rests on. Whatever names the tables behind +a proposal must not name a table to a reader who may not view it. + +## Decision + +**Two operation types, `UPSERT_BINDING` and `UPSERT_SHAPE`.** Neither has a delete type. + +- `UPSERT_BINDING` carries `binding`, which is + `{classIri, tableId, role, subjectKey, rowFilter, columns: [{propertyIri, columnPath, join}]}`. + It names its class and each property by IRI, so it can name a definition that the same change + set creates, and it names its table by id. `role`, `subjectKey`, `rowFilter` and the columns mean + what they mean on a stored binding + (ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records). Applying it adds or replaces + that one table's binding of the class and keeps the other bindings of the class. A change set + writes each pair of class and table once. +- A `join` in a binding operation is `{targetAssetId, on}` and has no status. The server stores it + as `inferred`, also when it replaces a join that a person had confirmed. Only the bindings API + stores `confirmed`. +- `UPSERT_SHAPE` carries `shape`, a shape as the shape API stores it, and may carry `basis`, which + is `declared` or `observed`. +- A binding operation needs its class and a shape operation needs its target class. + `requiresConceptIris` orders both after the class operations they need, as it orders a property. + +**Any operation may carry evidence.** `evidence` is a list of at most 20 entries. Each entry is +`{tableId, columns, kind}`: one table, optionally up to 32 column paths of it, and a `kind` out of +`declaredKey`, `storedJoinCount`, `testCase`, `lineage`, `profile`, `name`, `sampleData` and +`measured`. Evidence is what the author says the operation rests on. The server never acts on it +and checks only that its author may view the table. + +**Evidence passes through the view of the caller in both directions.** Every response that carries +operations leaves out each entry whose table its caller lacks `ViewBasic` on, and sets +`withheldEvidenceCount` on every operation that stores evidence. A deleted table is withheld from +every caller. The stored operation keeps every entry. "Every response" means every endpoint of the +change set resource, the versions it serves and the MCP tool that reads an entity. + +The MCP tool that patches an entity refuses a change set. A JSON Patch can copy a stored entry into +a member that every reader is shown, and the change set resource itself offers no patch. + +A save through the change set resource stores the entries its writer sends about tables the writer +may view, and keeps the stored entries the writer was not shown, each in its place. It stores no +entry about a table the writer may not view. Storing one would repeat a withheld entry, and merging +the repeat would tell the writer what is withheld. + +`evidence` and `withheldEvidenceCount` are masked fields +(ADR:2026-10-26-masked-fields-stay-out-of-change-events-and-version-history), so no stored change +event holds them, and the recorded change of `operations` holds the operations without their +evidence. A save that changes evidence alone is stored without a new version. + +**A save checks what an operation names, and an apply checks what its caller may do.** + +- Creating a change set and replacing its operations check, with nobody's rights, that every IRI + is absolute, that the class of a binding and each property it names is declared in the ontology + or created by an earlier operation, that the target class of a shape is declared, created by an + earlier operation or a class of a standard vocabulary, that the table, each join target and every + column a binding names exist, and that the binding passes the binding rules that read only its + own fields. A failure is a 400 that names the operation. +- Applying runs every check of a binding write again as the caller who applies: `EditAll` on the + class, `ViewBasic` on the table, `ViewSampleData` for a row filter the write sets or changes, the + right to view a join target, the mapping source of the ontology, and the data type of a row + filter value. The rights of whoever built the change set play no part. A refusal answers with the + status of the check that failed, rolls back every write of the change set and leaves the change + set in the state it was in. +- A background job that applies a change set has no caller, so it refuses a binding operation. + +**A binding operation says which binding revision it was built against.** `baseVersion` holds the +binding revision of the class that the author read. It is absent when the table was not bound to +the class. Under the ontology lock, an apply refuses with a 412 an operation that carries no +revision while the table is bound, and an operation whose revision is not the one the class had +before this apply wrote its first binding. The message names the class, the table and the +operation, so a client can rebuild that one operation. Every operation of a change set is judged +against the revision before the apply, so two of them can change two tables of one class that the +author read together. An operation that repeats the stored binding writes nothing and is not +judged. + +A binding operation writes through the step that checks and saves every binding row, inside the +transaction of the apply, which already holds the ontology lock. It takes no other lock. + +## Consequences + +A draft can propose a class, its properties, the table that holds it and the shapes it should meet, +and a reviewer applies or discards all of it at once. Discarding writes nothing. + +A binding write changes no definition, so it does not move the working revision of the ontology, +and a change set stays applicable while others edit bindings. `baseVersion` alone guards its +binding operations. That revision counts every binding of the class, so a change to another table +of the same class also makes an operation stale. The cost is a rebuild that the author did not +need. A revision for each table would remove that cost and needs a migration. + +The save checks read the catalog with nobody's rights. An author who knows the id of a table can +therefore learn from a refusal whether the table and a named column exist. The alternative is a +draft that only someone who may view every table it names can save. That rule would tie a review +to the rights of the author. + +The fields of a binding operation are part of the operation, and every reader of the change set +sees them. Only evidence is masked for each reader. Reading the operations of a change set already +requires the right to edit its scope +(ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights). + +An author cites only tables it may view. A service that drafts with wider rights than the person it +drafts for therefore saves the draft itself, and that person then reads it through their own view. + +A person's confirmation of a join is lost when a later operation writes that join again. Revisit +the rule when operations rewrite bindings that people maintain by hand. An operation could then +keep the status of a join it does not change. + +A binding or a shape is still removed through its own API. Add delete operation types when a draft +has to retire one. From 9ad3c7c1c4a6ef2144e519a8b81eadecef27f597 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 13:45:58 -0800 Subject: [PATCH 042/203] Keep the search-around statement of a concept with one table POST /v1/ontologyConcepts/{id}/query refused every concept without an identity table. A binding made before a binding had a role has none, so a concept with such bindings lost the statement it had. The table bindings of the concept now pick where the statement starts: - A concept with one table binding starts from that table, whatever the role of the binding. A reader who may not view the table gets the 400 of a concept with no viewable table, as before. - A concept with several table bindings starts from its identity table. A reader who may not view that table gets a 403 that names the concept and never the table. - A concept with several table bindings and no identity table is a 409 that names the concept and asks for its identity table. A concept that binds no table gets its 400 again. A binding whose table no longer exists does not count for this rule, whatever its role. The four statements about records still take the identity table and its subject key, because they name records. Ten of the twelve tests that OntologyConceptQueryIT held before this branch have their earlier text again. The test of a start concept with twelve tables stays as a test of a hop target, and the row filter test keeps both forms of the statement. --- ...tatements-start-from-the-identity-table.md | 50 +++-- .../it/tests/OntologyConceptQueryIT.java | 171 +++++++++++++++--- .../ontology/OntologyConceptQueryService.java | 52 ++++-- .../ontology/OntologyConceptSqlGenerator.java | 4 +- .../ontology/OntologyMappingReader.java | 54 +++++- .../ontology/OntologyMappingReaderTest.java | 94 ++++++++++ .../schema/api/data/ontologyConceptQuery.json | 2 +- 7 files changed, 365 insertions(+), 62 deletions(-) diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md index 5c555ee396be..06a49f48e12b 100644 --- a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -37,11 +37,11 @@ the binding keeps it. Its id is the class IRI with the key values in key order. record by a `key`, a list with one JSON value for each key column. Two rows with one key are one record, so the class count counts distinct keys. -**Every statement starts from the identity table of its class.** A class without one is a 409 that -names the class. A reader who may not view the identity table gets a 403 that names the class and -never the table. A statement never starts from another table because of who asks, so the id of a -record does not depend on the reader. Every table a statement reads is in the database of that -identity table, and a table in another database is a 409. +**Each of the four statements starts from the identity table of its class.** A class without one is +a 409 that names the class. A reader who may not view the identity table gets a 403 that names the +class and never the table. A statement never starts from another table because of who asks, so the +id of a record does not depend on the reader. Every table a statement reads is in the database of +that identity table, and a table in another database is a 409. **`open` joins each contributing table on the subject key.** The keys pair by position. The join is a `LEFT JOIN` that also carries the row filter of the contributing table, so a record with no @@ -96,32 +96,50 @@ again. A binding write commits its rows and its revision in one transaction, so that the rows belong to those revisions. After three unequal reads the request is a 409 that asks the client to send it again. -**`POST /v1/ontologyConcepts/{id}/query` starts from the identity table too.** One generator writes -its statement and the four above. Its `sql` writes every colon as a colon again, and it gains -`escapedSql`. +**The table bindings of a concept pick where `POST /v1/ontologyConcepts/{id}/query` starts.** That +endpoint is older than the roles, and a binding made before them has no role. The server guesses no +role for such a binding, and a concept with one table binding keeps the answer it had. + +- A concept with one table binding starts from that table, whatever the role of the binding. A + reader who may not view the table gets the 400 of a concept with no viewable table, as before. +- A concept with several table bindings starts from its identity table. A reader who may not view + that table gets a 403 that names the concept and never the table. +- A concept with several table bindings and no identity table is a 409 that names the concept and + asks for its identity table. The server never picks one of several tables for a reader. + +A binding whose table no longer exists does not count for this rule, whatever its role, as the +list of the bindings of a concept leaves it out. + +One generator writes the statement of this endpoint and the four above. Its `sql` writes every +colon as a colon again, and it gains `escapedSql`. **This record replaces three rules of -ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension, for the concept that a -statement starts from.** +ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension, for a start concept that binds +several tables.** - That record reads the first 100 table bindings of the concept and keeps the first ten tables that the reader may view. The statement started from one of those ten. It now starts from the identity table, which the server reads by its role. - That record treats a bound table that the caller may not view as unbound. A reader who may not view the identity table now gets a 403. -- That record answers a concept without a viewable bound table with a 400. A concept without an - identity table is now a 409. +- That record answers a concept without a viewable bound table with a 400. A concept that binds + several tables never gets that 400. Without an identity table it is a 409 for every reader. -Its rules for the concepts that a hop reaches, for joins, labels, directions, batched reads, and -the hop limit are unchanged. +Its rules for a start concept that binds one table or none, for the concepts that a hop reaches, +for joins, labels, directions, batched reads, and the hop limit are unchanged. ## Consequences A client builds a record id from the plan, and the id is the same in every statement and for every reader. A client reads a result by column index, because two result columns can have one name. -A concept whose bindings carry no role has no identity table. Every statement about it is a 409, -the search-around statement included, until one of its table bindings takes the `identity` role. +A concept whose bindings carry no role has no identity table. Each of the four statements about +its records is a 409 until one of its table bindings takes the `identity` role. The search-around +statement still starts from its table when it binds one. + +A concept that binds several tables and has no identity table got a search-around statement +before, and now gets a 409. That request works again once someone picks its identity table. A hop +still reaches such a concept, because the rules for a hop are unchanged. Only the relation count orders its rows. A page of `find` or `expand` is any 25 records, and no statement reads a second page. Paging needs an order over the key and is a later decision. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java index 26e8e31bc1ab..5e8dc53d7a94 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java @@ -1,6 +1,7 @@ package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.openmetadata.it.tests.OntologyBindingFixtures.admin; @@ -69,8 +70,11 @@ class OntologyConceptQueryIT extends BaseOntologyApprovalIT { private static final URI ACCOUNT = URI.create("urn:payments:Account"); private static final URI EMPLOYEE = URI.create("urn:payments:Employee"); private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); - private static final String NO_IDENTITY_TABLE = - "Class urn:payments:FundsTransfer has no identity table"; + private static final String NO_VIEWABLE_TABLE = + " has no bound table you can view among its first 100 table bindings"; + private static final String PICK_IDENTITY_TABLE = + "Class urn:payments:FundsTransfer binds several tables and none is its identity table." + + " Pick its identity table"; private static final String HIDDEN_IDENTITY_TABLE = "The identity table of class urn:payments:FundsTransfer is not visible to you"; @@ -101,7 +105,7 @@ void theSqlSelectsTheBoundColumnsAndJoinsEachHopOnForeignKeys(final TestNamespac "accounts", List.of("account_id", "owner_id"), foreignKey("owner_id", customers, "customer_id")); - bindIdentity(payments.transfer(), transfers, payments.ontology(), "transfer_id", "amount_usd"); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id", "amount_usd"); bindData(payments.customer(), customers, payments.ontology(), "name"); bindData(payments.account(), accounts, payments.ontology(), "account_id"); @@ -145,11 +149,10 @@ void aHopWithoutAConstraintJoinsAnObjectPropertyBindingToTheTargetIdentifier( dataProperty(payments.ontology(), "customerId", payments.customer(), true); bind( payments.transfer(), - binding(transfers, OntologyBindingRole.IDENTITY, "transfer_id") - .withColumns( - List.of( - column(transferId, "transfer_id"), - relation(payments.partOf(), "payer_id", customers, "customer_id"))), + transfers, + List.of( + column(transferId, "transfer_id"), + relation(payments.partOf(), "payer_id", customers, "customer_id")), 0L); bind(payments.customer(), customers, List.of(column(customerId, "customer_id")), 0L); @@ -170,7 +173,7 @@ void snowflakeQuotesEveryIdentifierAsStored(final TestNamespace ns) { final Payments payments = payments(ns, "snowflakePayments", DatabaseServiceTestFactory.createSnowflake(ns)); final Table transfers = table(payments, "transfers", List.of("transfer_id", "Amount USD")); - bindIdentity(payments.transfer(), transfers, payments.ontology(), "transfer_id", "Amount USD"); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id", "Amount USD"); final OntologyConceptQuery snowflake = query(admin(), payments.transfer()); @@ -183,17 +186,16 @@ void snowflakeQuotesEveryIdentifierAsStored(final TestNamespace ns) { } @Test - void missingBindingsAndJoinsAreNamedRefusals(final TestNamespace ns) { + void missingBindingsAndJoinsAreNamedBadRequests(final TestNamespace ns) { final Payments payments = payments(ns, "unboundPayments", DatabaseServiceTestFactory.createPostgres(ns)); final Table transfers = table(payments, "transfers", List.of("transfer_id")); final Table customers = table(payments, "customers", List.of("customer_id")); - final Table ledger = table(payments, "ledger", List.of("entry_id")); - assertRefused(409, NO_IDENTITY_TABLE, () -> query(admin(), payments.transfer())); - bindData(payments.transfer(), ledger, payments.ontology(), "entry_id"); - assertRefused(409, NO_IDENTITY_TABLE, () -> query(admin(), payments.transfer())); - bindIdentity(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + assertBadRequest( + "Concept FundsTransfer has no bound table you can view among its first 100 table bindings", + () -> query(admin(), payments.transfer())); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); assertBadRequest( "Hop 1 (part of) reaches concept Customer, which has no bound table you can view" + " among its first 100 table bindings", @@ -230,19 +232,124 @@ void missingBindingsAndJoinsAreNamedRefusals(final TestNamespace ns) { } @Test - void anIdentityTableTheReaderMayNotViewIsRefusedAndNeverNamed(final TestNamespace ns) { + void aTableTheReaderMayNotViewIsUnboundAndItsColumnsStayHidden(final TestNamespace ns) { final Payments payments = payments(ns, "hiddenPayments", DatabaseServiceTestFactory.createPostgres(ns)); final Table transfers = table(payments, "transfers", List.of("secret_amount")); - bindIdentity(payments.transfer(), transfers, payments.ontology(), "secret_amount"); + bindData(payments.transfer(), transfers, payments.ontology(), "secret_amount"); try (var fixtures = new RdfAccessFixtures("conceptQuery" + ns.shortPrefix())) { final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); - assertRefused(403, HIDDEN_IDENTITY_TABLE, () -> query(reader, payments.transfer())); + final OpenMetadataException hidden = + assertThrows(OpenMetadataException.class, () -> query(reader, payments.transfer())); + + assertEquals(400, hidden.getStatusCode()); + assertTrue(hidden.getMessage().contains("has no bound table you can view")); + assertFalse(hidden.getMessage().contains("secret_amount")); + assertFalse(hidden.getMessage().contains("transfers")); assertTrue(query(admin(), payments.transfer()).getSql().contains("secret_amount")); } } + @Test + void aClassWithOneTableBindingStartsFromThatTableWhateverItsRole(final TestNamespace ns) { + final Payments payments = + payments(ns, "oneTablePayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table transfers = table(payments, "transfers", List.of("transfer_id")); + final Table customers = table(payments, "customers", List.of("customer_id")); + final Table accounts = table(payments, "accounts", List.of("account_id")); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + bindAs( + OntologyBindingRole.CONTRIBUTING, + payments.customer(), + customers, + payments.ontology(), + "customer_id"); + bindIdentity(payments.account(), accounts, payments.ontology(), "account_id"); + try (var fixtures = new RdfAccessFixtures("conceptQueryOne" + ns.shortPrefix())) { + final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); + final String schema = payments.schema().getName(); + + assertEquals( + "SELECT transfer_id\nFROM " + schema + ".transfers\nLIMIT 50", + query(admin(), payments.transfer()).getSql()); + assertEquals( + "SELECT customer_id\nFROM " + schema + ".customers\nLIMIT 50", + query(admin(), payments.customer()).getSql()); + assertEquals( + "SELECT account_id\nFROM " + schema + ".accounts\nLIMIT 50", + query(admin(), payments.account()).getSql()); + assertRefused( + 400, + "Concept FundsTransfer" + NO_VIEWABLE_TABLE, + () -> query(reader, payments.transfer())); + assertRefused( + 400, "Concept Customer" + NO_VIEWABLE_TABLE, () -> query(reader, payments.customer())); + assertRefused( + 400, "Concept Account" + NO_VIEWABLE_TABLE, () -> query(reader, payments.account())); + } + } + + @Test + void aClassWithSeveralTableBindingsIsRefusedUntilItsIdentityTableIsPicked( + final TestNamespace ns) { + final Payments payments = + payments(ns, "severalPayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table customers = table(payments, "customers", List.of("customer_id")); + final Table transfers = + table( + payments, + "transfers", + List.of("transfer_id", "customer_id"), + foreignKey("customer_id", customers, "customer_id")); + final Table ledger = table(payments, "ledger", List.of("entry_id")); + bindData(payments.customer(), customers, payments.ontology(), "customer_id"); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + bindAs( + OntologyBindingRole.CONTRIBUTING, + payments.transfer(), + ledger, + payments.ontology(), + "entry_id"); + try (var fixtures = new RdfAccessFixtures("conceptQuerySeveral" + ns.shortPrefix())) { + final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); + own(ledger, reader); + + assertRefused(409, PICK_IDENTITY_TABLE, () -> query(admin(), payments.transfer())); + assertRefused(409, PICK_IDENTITY_TABLE, () -> query(reader, payments.transfer())); + bindIdentity(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + assertRefused(403, HIDDEN_IDENTITY_TABLE, () -> query(reader, payments.transfer())); + assertEquals( + String.join( + "\n", + "SELECT t1.customer_id", + "FROM " + payments.schema().getName() + ".transfers t0", + "JOIN " + + payments.schema().getName() + + ".customers t1 ON t0.customer_id = t1.customer_id", + "LIMIT 50"), + query(admin(), payments.transfer(), hop(payments.partOf(), OUTGOING, payments.customer())) + .getSql()); + } + } + + @Test + void aBindingWhoseTableWasDeletedIsNoTableBindingOfItsClass(final TestNamespace ns) { + final Payments payments = + payments(ns, "deletedPayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table transfers = table(payments, "transfers", List.of("transfer_id")); + final Table ledger = table(payments, "ledger", List.of("entry_id")); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + bindData(payments.transfer(), ledger, payments.ontology(), "entry_id"); + + assertRefused(409, PICK_IDENTITY_TABLE, () -> query(admin(), payments.transfer())); + admin().tables().delete(ledger.getId()); + + assertEquals( + "SELECT transfer_id\nFROM " + payments.schema().getName() + ".transfers\nLIMIT 50", + query(admin(), payments.transfer()).getSql()); + } + @Test void theSqlStartsFromTheIdentityTableWhoeverAsks(final TestNamespace ns) { final Payments payments = @@ -346,7 +453,7 @@ void anInverseTheReaderMayViewAsItsOwnerLabelsAnIncomingHop(final TestNamespace "accounts", List.of("account_id", "customer_id"), foreignKey("customer_id", customers, "customer_id")); - bindIdentity(payments.account(), accounts, payments.ontology(), "account_id"); + bindData(payments.account(), accounts, payments.ontology(), "account_id"); bindData(payments.customer(), customers, payments.ontology(), "name"); try (var fixtures = new RdfAccessFixtures("conceptQueryInverse" + ns.shortPrefix())) { final OpenMetadataClient reader = ownerOnlyPropertyReader(fixtures); @@ -446,11 +553,10 @@ private SelfKey selfKeyEmployees(final TestNamespace ns, final String name) { dataProperty(payments.ontology(), "employeeId", employee, true); bind( employee, - binding(employees, OntologyBindingRole.IDENTITY, "employee_id") - .withColumns( - List.of( - column(employeeId, "employee_id"), - relation(managedBy, "manager_id", employees, "employee_id"))), + employees, + List.of( + column(employeeId, "employee_id"), + relation(managedBy, "manager_id", employees, "employee_id")), 0L); return new SelfKey(employee, managedBy, manages, payments.schema().getName()); } @@ -522,7 +628,7 @@ private static void bindFiltered( put( admin(), payments.transfer(), - binding(transfers, OntologyBindingRole.IDENTITY, "transfer_id") + binding(transfers) .withColumns(List.of(column(transferId, "transfer_id"))) .withRowFilter(filter(column, operator, value)), 0L); @@ -539,7 +645,7 @@ void generatingSqlWritesNothing(final TestNamespace ns) { "transfers", List.of("transfer_id", "customer_id"), foreignKey("customer_id", customers, "customer_id")); - bindIdentity(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); bindData(payments.customer(), customers, payments.ontology(), "customer_id"); final List before = observedState(payments, transfers); @@ -642,10 +748,19 @@ private static void bindIdentity( final Table table, final Ontology ontology, final String... columns) { + bindAs(OntologyBindingRole.IDENTITY, concept, table, ontology, columns); + } + + /** Binds the table to the concept in a role, keyed by the first of the columns. */ + private static void bindAs( + final OntologyBindingRole role, + final OntologyConcept concept, + final Table table, + final Ontology ontology, + final String... columns) { bind( concept, - binding(table, OntologyBindingRole.IDENTITY, columns[0]) - .withColumns(dataColumns(concept, ontology, columns)), + binding(table, role, columns[0]).withColumns(dataColumns(concept, ontology, columns)), bindings(concept, "").getRevision()); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java index 85a38d18461e..e2c0c08e82dd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java @@ -55,6 +55,8 @@ import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundTable; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.Generated; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.Hop; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.IdentityTable; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.OnlyTable; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.policyevaluator.BulkFieldHydrator; @@ -65,15 +67,16 @@ /** * Reads what SQL generation needs in a fixed number of batched statements, whatever the hop count: - * the concepts, the hop properties and their inverses, the identity table of the concept the - * statement starts from, the first bound tables of each concept a hop reaches, those tables twice - * (for the view check, then columns of the kept ones), and the properties their columns bind. The - * call writes nothing. + * the concepts, the hop properties and their inverses, the table of the concept the statement + * starts from, the first bound tables of each concept a hop reaches, those tables twice (for the + * view check, then columns of the kept ones), and the properties their columns bind. The call + * writes nothing. * - *

The statement starts from the identity table of its concept, as every statement about the - * records of that concept does (ADR:2026-11-22-record-statements-start-from-the-identity-table). - * A table that a hop reaches and the reader may not view is treated as unbound, so its columns - * never appear in the SQL. + *

The table bindings of a concept pick the table its statement starts from, and who asks never + * does (ADR:2026-11-22-record-statements-start-from-the-identity-table). A concept with one table + * binding starts from that table, and a concept with several starts from its identity table. A + * table the reader may not view is treated as unbound, so its columns never appear in the SQL. + * The one exception is the identity table of a concept that binds several tables, which is a 403. */ @Slf4j public final class OntologyConceptQueryService { @@ -277,12 +280,24 @@ private Map relations( } /** - * The concept a statement starts from, with the one table it starts from: its identity table. A - * concept without one is a 409, and one whose identity table the reader may not view is a 403. + * The concept a statement starts from, with the one table it starts from. The only table of a + * concept follows the rule of every bound table. A reader who may not view it gets the 400 of a + * concept with no table. */ private BoundConcept start(final Access access, final OntologyConcept root) { - final BindingRow identity = mapping.identityRows(List.of(root.getId())).get(root.getId()); - final List rows = identity == null ? List.of() : List.of(identity); + return switch (mapping.searchStart(root.getId(), root.getIri())) { + case OnlyTable only -> bound(access, List.of(root), only.rows()).get(root.getId()); + case IdentityTable several -> identityBound(access, root, several.row()); + }; + } + + /** + * A concept with its identity table. A reader who may not view that table gets a 403 that names + * the concept and never the table. + */ + private BoundConcept identityBound( + final Access access, final OntologyConcept root, final BindingRow identity) { + final List rows = List.of(identity); OntologyMappingReader.identity(root.getIri(), identity, mapping.tables(access, rows)); final Table table = tablesWithColumns(access, rows).get(identity.assetId()); return new BoundConcept( @@ -293,9 +308,18 @@ private BoundConcept start(final Access access, final OntologyConcept root) { /** The tables that each concept a hop reaches binds and the reader may view. */ private Map bind( final Access access, final Collection concepts) { - final List rows = + return bound( + access, + concepts, store.firstTables( - concepts.stream().map(OntologyConcept::getId).toList(), TABLE_BINDINGS_READ); + concepts.stream().map(OntologyConcept::getId).toList(), TABLE_BINDINGS_READ)); + } + + /** Each concept with the tables among {@code rows} that it binds and the reader may view. */ + private Map bound( + final Access access, + final Collection concepts, + final List rows) { final Map> visible = firstVisibleTables(rows, viewableTableIds(access, rows)::contains); final List kept = visible.values().stream().flatMap(List::stream).toList(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index 53dbee3f9a6f..1865ad8e54f3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -111,7 +111,7 @@ public BoundTable( /** * A concept and the tables it binds that the reader may view, in asset id order. The concept a - * statement starts from holds one table, its identity table. + * statement starts from holds the one table that its bindings pick, or no table. */ public record BoundConcept(String label, List tables) {} @@ -413,7 +413,7 @@ private static void requireSameDatabase(final MappedClass type, final MappedTabl } } - /** The one table a statement starts from, which its caller found as the identity table. */ + /** The one table a statement starts from, which its caller found from the table bindings. */ private static BoundTable rootTable(final BoundConcept root) { final List tables = listOrEmpty(root.tables()); if (tables.isEmpty()) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java index 0f3e985695a3..70d78d904497 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java @@ -31,6 +31,8 @@ import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.IdentityTable; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.OnlyTable; import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; import org.openmetadata.service.ontology.OntologyRelationPath.End; import org.openmetadata.service.ontology.OntologyRelationPath.Ends; @@ -49,6 +51,7 @@ final class OntologyMappingReader { static final int MAX_CONTRIBUTING_TABLES = 32; private static final int BINDING_READ_ATTEMPTS = 3; + private static final int SEVERAL_TABLES = 2; private final OntologyConceptBindingStore store; private final OntologyBindingAccess catalog; @@ -95,6 +98,20 @@ MappedTable mapped(final BindingRow row) { } } + /** The table that the search-around statement of a class starts from. */ + sealed interface SearchStart { + /** + * The class binds at most one table, and the statement starts from that table whatever the + * role of its binding. + * + * @param rows the one table row of the class whose table exists, or no row + */ + record OnlyTable(List rows) implements SearchStart {} + + /** The class binds several tables, and the statement starts from its identity table. */ + record IdentityTable(BindingRow row) implements SearchStart {} + } + /** * Reads the binding rows between two reads of the binding revisions. A binding write commits its * rows and its revision in one transaction, so two equal revision reads mean that no write @@ -114,7 +131,42 @@ Bindings bindings(final Collection classes, final Collection withCon throw conflict("The table bindings changed while the statement was built. Ask again"); } - Map identityRows(final Collection classes) { + /** + * Finds the table that the search-around statement of a class starts from. A class with one + * table binding starts from that table, as it did before a binding had a role. A class with + * several table bindings starts from its identity table. Without one it gets no statement, + * because the server never picks one of several tables for a reader. + * + *

A binding whose table no longer exists is no table binding here, as the list of the + * bindings of a class leaves it out. That holds for the identity binding too. The rule reads + * the first table bindings of the class, up to + * {@link OntologyConceptQueryService#TABLE_BINDINGS_READ}. + */ + SearchStart searchStart(final UUID type, final URI iri) { + final List classes = List.of(type); + final List tables = + held(store.firstTables(classes, OntologyConceptQueryService.TABLE_BINDINGS_READ)); + return tables.size() < SEVERAL_TABLES + ? new OnlyTable(tables) + : new IdentityTable(identityAmongSeveral(iri, held(store.identityRows(classes)))); + } + + /** The rows whose table exists. */ + private List held(final List rows) { + final Set live = store.liveAssets(rows).keySet(); + return rows.stream().filter(row -> live.contains(row.assetId())).toList(); + } + + private static BindingRow identityAmongSeveral(final URI type, final List identity) { + if (identity.isEmpty()) { + throw conflict( + "Class %s binds several tables and none is its identity table. Pick its identity table", + type); + } + return identity.getFirst(); + } + + private Map identityRows(final Collection classes) { return store.identityRows(classes).stream() .collect(Collectors.toMap(BindingRow::conceptId, Function.identity())); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingReaderTest.java index f693f8962d3e..8ea43b10f01d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingReaderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingReaderTest.java @@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -25,13 +26,18 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; import java.util.stream.IntStream; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.openmetadata.schema.type.OntologyBindingAssetType; import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.LiveAsset; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; import org.openmetadata.service.ontology.OntologyMappingReader.Bindings; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.IdentityTable; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.OnlyTable; import org.openmetadata.service.ontology.OntologyMappingReader.Tables; /** @@ -130,6 +136,94 @@ void aContributingTableThatNoLongerExistsIsLeftOut() { CUSTOMER_IRI, List.of(kept, gone), new Tables(Set.of(kept.assetId()), Map.of()))); } + @Test + void aClassThatBindsNoTableHasNoTableToStartItsSearchFrom() { + bound(); + + assertEquals(new OnlyTable(List.of()), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + } + + @Test + void aClassWithOneTableBindingStartsItsSearchFromThatTableWhateverItsRole() { + final BindingRow withoutRole = row(1, null); + final BindingRow contributing = row(2, OntologyBindingRole.CONTRIBUTING); + final BindingRow identity = row(3, OntologyBindingRole.IDENTITY); + + bound(withoutRole); + assertEquals(new OnlyTable(List.of(withoutRole)), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + bound(contributing); + assertEquals(new OnlyTable(List.of(contributing)), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + bound(identity); + assertEquals(new OnlyTable(List.of(identity)), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + } + + @Test + void aBindingWhoseTableNoLongerExistsIsNoTableBindingOfItsClass() { + final BindingRow gone = row(1, null); + final BindingRow kept = row(2, null); + bound(gone, kept); + deleted(gone); + + assertEquals(new OnlyTable(List.of(kept)), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + } + + @Test + void aClassWithSeveralTableBindingsStartsItsSearchFromItsIdentityTable() { + final BindingRow identity = row(3, OntologyBindingRole.IDENTITY); + bound(row(1, null), row(2, OntologyBindingRole.CONTRIBUTING), identity); + + assertEquals(new IdentityTable(identity), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + } + + @Test + void aClassWithSeveralTableBindingsAndNoIdentityTableGivesNoSearchStatement() { + bound(row(1, null), row(2, OntologyBindingRole.CONTRIBUTING)); + + assertAsksForTheIdentityTable(); + } + + @Test + void anIdentityBindingWhoseTableNoLongerExistsIsNoIdentityTableOfItsClass() { + final BindingRow identity = row(3, OntologyBindingRole.IDENTITY); + bound(row(1, null), row(2, OntologyBindingRole.CONTRIBUTING), identity); + deleted(identity); + + assertAsksForTheIdentityTable(); + } + + private void assertAsksForTheIdentityTable() { + final ClientErrorException refused = + assertThrows(ClientErrorException.class, () -> reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Class https://example.org/shop#Customer binds several tables and none is its identity" + + " table. Pick its identity table", + refused.getMessage()); + } + + /** Makes these rows the table bindings of the class, each over a table that exists. */ + private void bound(final BindingRow... rows) { + when(store.firstTables(List.of(CUSTOMER), 100)).thenReturn(List.of(rows)); + when(store.identityRows(anyCollection())) + .thenReturn( + Stream.of(rows).filter(row -> row.role() == OntologyBindingRole.IDENTITY).toList()); + deleted(); + } + + /** Makes the store answer that every table exists except the tables of these rows. */ + private void deleted(final BindingRow... gone) { + final Set missing = Stream.of(gone).map(BindingRow::assetId).collect(Collectors.toSet()); + when(store.liveAssets(anyList())) + .thenAnswer( + call -> + call.>getArgument(0).stream() + .filter(row -> !missing.contains(row.assetId())) + .collect( + Collectors.toMap( + BindingRow::assetId, row -> new LiveAsset(row.assetId(), "Postgres")))); + } + private static BindingRow row(final int table, final OntologyBindingRole role) { return new BindingRow( CUSTOMER, diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json index b19d9626955f..45a25bf5090d 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json @@ -50,7 +50,7 @@ "default": [] }, "sql": { - "description": "Generated SELECT limited to 50 rows, for a person to read. It starts from the identity table of the concept and applies the row filter of each table it reads. Every colon is written as a colon. Do not pass it to a library that reads `:name` as a bind parameter. Set by the server.", + "description": "Generated SELECT limited to 50 rows, for a person to read. It starts from the only bound table of the concept, or from its identity table when the concept binds several tables, and applies the row filter of each table it reads. Every colon is written as a colon. Do not pass it to a library that reads `:name` as a bind parameter. Set by the server.", "type": "string" }, "escapedSql": { From 053f165f7307cd2639ea8d4f3eb2261ef309bf72 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 14:00:16 -0800 Subject: [PATCH 043/203] Test the display name flag of a version and an inverse request A request names the version to read, and the display name flag of a property comes from that version. OntologyRecordStatementIT now clears the flag in the working draft after a release. The release plan still lists the column as the display name, and the draft plan lists it as a property. An inverse request takes its related class from the domain of the relation. OntologyStatementRefusalIT now gives the relation two classes in its domain. A request that names no related class is a 400 that says so, and a request that names one gets its statement. --- .../it/tests/OntologyRecordStatementIT.java | 28 +++++++++++ .../it/tests/OntologyStatementRefusalIT.java | 47 +++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java index 828d6c3c8a74..e6aa691427fe 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java @@ -220,6 +220,34 @@ void aStatementReadsTheVersionThatItsRequestNames(final TestNamespace ns) { } } + @Test + void theDisplayNameFlagComesFromTheVersionThatARequestNames(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "displayNameVersions"); + final Ask find = UNFILTERED_IDENTITY.ask("find"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, UNFILTERED_IDENTITY)) { + fixture.bindAll(); + activate(ns, ontology); + final String name = fixture.property("customerName").getId().toString(); + admin() + .ontologyProperties() + .update(name, admin().ontologyProperties().get(name).withIsDisplayName(false)); + + assertEquals( + List.of( + "0 key Customer part 0", + "1 displayName Customer customerName", + "2 property Customer customerEmail"), + columnPlan(fixture.ask(admin(), find, OntologyStatementVersion.RELEASE).getColumns())); + assertEquals( + List.of( + "0 key Customer part 0", + "1 property Customer customerEmail", + "2 property Customer customerName"), + columnPlan(fixture.ask(admin(), find, OntologyStatementVersion.DRAFT).getColumns())); + } + } + @Test void aBindingWriteMovesTheBindingRevisionOfTheNextPlan(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "revisions"); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java index 48d40b3e4183..03af7dcf8ad5 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java @@ -388,6 +388,39 @@ void aRequestNamesTheRelatedClassWhenTheRelationDoesNotNameOne(final TestNamespa } } + @Test + void anInverseRequestNamesTheRelatedClassWhenTheDomainNamesSeveral(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "relatedDomain"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + final UUID order = fixture.type("Order").getId(); + final UUID customer = fixture.type("Customer").getId(); + final OntologyProperty placedBy = fixture.property("placedBy"); + final String toTheOrders = fixture.golden(COLUMN_RELATION.ask("expand-inverse")); + + assertEquals(toTheOrders, expandBack(customer, placedBy, null).getSql() + "\n"); + final String id = placedBy.getId().toString(); + admin() + .ontologyProperties() + .update( + id, + admin() + .ontologyProperties() + .get(id) + .withDomain(List.of(URI.create(ORDER), URI.create(CUSTOMER)))); + + assertRefused( + 400, + "Relation " + + PLACED_BY + + " names 2 classes in its domain, so the request must name the related class", + () -> expandBack(customer, placedBy, null)); + final OntologyStatementPlan named = expandBack(customer, placedBy, order); + assertEquals(toTheOrders, named.getSql() + "\n"); + assertEquals(URI.create(ORDER), named.getRelation().getRelatedClassIri()); + } + } + /** Asks the expand statement of order 31 with a request that can name the related class. */ private static OntologyStatementPlan expand( final UUID type, final OntologyProperty relation, final UUID relatedClass) { @@ -402,6 +435,20 @@ private static OntologyStatementPlan expand( .withRelatedClass(relatedClass)); } + /** Asks for the orders of customer 2, against the relation that the orders hold. */ + private static OntologyStatementPlan expandBack( + final UUID type, final OntologyProperty relation, final UUID relatedClass) { + return post( + type, + "expand", + new OntologyExpandStatementRequest() + .withVersion(DRAFT) + .withKey(List.of(2)) + .withRelation(relation.getId()) + .withDirection(OntologyStatementDirection.INVERSE) + .withRelatedClass(relatedClass)); + } + private static OntologyStatementPlan post( final UUID type, final String statement, final Object request) { return admin() From 1f446cf9d0439bfb5bc9c9753ab24b91dfb38bc6 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 17:55:16 -0800 Subject: [PATCH 044/203] Test a join onto another table and a stale filter on a table that adds no column --- .../ontology/OntologyExpandStatementTest.java | 36 +++++++++++++++++++ .../ontology/OntologyRecordStatementTest.java | 21 +++++++++++ 2 files changed, 57 insertions(+) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java index 6619aa3ad37e..2c96b1f6d475 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java @@ -169,6 +169,42 @@ void aJoinThatIsOnlyInferredIsNotFollowed() { refused.getMessage()); } + @Test + void aConfirmedJoinOntoAnotherTableThanTheIdentityTableOfTheRelatedClassIsNeverFollowed() { + final ColumnBindingSpec ontoOrders = + new ColumnBindingSpec( + "placedBy", + "customer_id", + new JoinSpec( + "orders", OntologyJoinStatus.CONFIRMED, List.of("customer_id"), List.of("id"))); + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COLUMN_RELATION, + POSTGRES, + List.of(COLUMN_RELATION.bindings().getFirst(), orders(ontoOrders))); + final String message = + "Relation " + + PLACED_BY + + " has no join from class " + + ORDER + + " to the identity table of class " + + CUSTOMER; + + final ClientErrorException forward = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Order", "placedBy", FORWARD, List.of(31))); + final ClientErrorException inverse = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Customer", "placedBy", INVERSE, List.of(2))); + + assertEquals(409, forward.getResponse().getStatus()); + assertEquals(message, forward.getMessage()); + assertEquals(409, inverse.getResponse().getStatus()); + assertEquals(message, inverse.getMessage()); + } + @Test void aRelationWithNoJoinGivesNoStatementInEitherDirection() { final OntologyMappingShapeModel model = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java index 382889da8dd9..6071a8ccae86 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java @@ -324,6 +324,27 @@ void aRowFilterThatNoLongerAppliesIsRefusedOnlyByAStatementThatReadsItsTable() { .getMessage()); } + @Test + void aStaleRowFilterOfAContributingTableThatAddsNoColumnChangesNothing() { + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COMPOSITE_KEY, + POSTGRES, + List.of( + COMPOSITE_KEY.bindings().getFirst(), + profile( + List.of("tenant", "customer"), + new FilterSpec("segment", OntologyRowFilterOperator.EQUALS, "retail")))); + + final RecordStatement open = open(model.omit("accountTier"), "Account", List.of("eu", 42)); + + assertEquals( + "SELECT t0.tenant_id, t0.customer_id, t0.name\nFROM shop.crm_customers t0\n" + + "WHERE t0.tenant_id = 'eu'\n AND t0.customer_id = 42\nLIMIT 101", + sql(open)); + assertEquals(List.of("crm_customers"), read(open)); + } + @Test void aContributingTableWhoseKeyHasAnotherLengthGivesNoStatement() { final OntologyMappingShapeModel model = From c04740d1f0e559d822189ac042a35a446bed136a Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 18:05:48 -0800 Subject: [PATCH 045/203] Read a release statement from the release members, whatever the draft deleted --- ...tatements-start-from-the-identity-table.md | 27 ++- .../jdbi3/OntologyConceptBindingStore.java | 21 +++ .../service/jdbi3/RdfInfraDAOs.java | 10 ++ .../ontology/OntologyBindingAccess.java | 77 ++++++++- .../ontology/OntologyStatementService.java | 112 ++++++++---- .../service/ontology/OntologyVersion.java | 159 +++++++++++++----- 6 files changed, 325 insertions(+), 81 deletions(-) diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md index 06a49f48e12b..ff930150e8f5 100644 --- a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-11-22 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyRecordStatementIT`, `OntologyStatementRefusalIT`, `OntologyStatementValueIT`, `OntologyConceptQueryIT` +- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyRecordStatementIT`, `OntologyStatementRefusalIT`, `OntologyStatementReleaseDeleteIT`, `OntologyStatementValueIT`, `OntologyConceptQueryIT` - **Related:** ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles and the subject key that a statement reads), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (amended by this record), ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension (three of its rules are replaced here), ADR:2026-11-21-a-class-has-at-most-one-display-name-property ## Context @@ -83,8 +83,8 @@ one row more than `rowCap`, and that row says only that more rows exist. `draft` reads the working draft and takes `EditAll` on the ontology. The class, its properties, the display name flag, and the relations come from that version. A class or a relation that the active release lacks is a 404 that names its IRI, and an ontology with no active release is a 404 that -says so. Bindings sit outside versions and are always current. The server checks `ViewBasic` on the -working class, relation, and properties. +says so. Bindings sit outside versions and are always current. The server checks `ViewBasic` on +each definition the statement reads, as that version holds it. **The plan says what the statement is and what it was built from.** `sql` is the statement for a person to read and `escapedSql` is the form to run through a reader of `:name` parameters. `columns` @@ -154,5 +154,22 @@ are a 400 for that class. `find` and the class count still work. The relation count groups over the whole join. On a large table that is expensive, and a narrower statement is a later change that must keep the row filters and the null rule of both classes. -Authorization reads the working definitions. A class or a relation that someone deleted from the -draft cannot be read by id, although the active release still holds it. +A read of the active release does not depend on later deletions in the working draft. The class, +the relation, the related class and the properties come from the members of the release, read by +id, so a plain delete in the draft changes no answer of the release. Only the ontology of a class is +found from its working row, deleted or not, and that ontology must still be live. A request for a +class or relation that the release lacks is a 404, or a 400 when the working row belongs to another +ontology. The caller needs `ViewBasic` on each released definition, checked on the definition with +the owners, tags and domains the catalog holds now for its id, the way a read of a release +authorizes its members. A property the caller may not view leaves the plan. The right is never +`ViewAll`. A read of the draft keeps reading live working rows, so a deleted class or relation is a +404 there and a deleted property leaves the plan. + +The one class that a relation names in its range or its domain is found by IRI among the working +rows, deleted ones too, and kept when the release holds a member with that id and that IRI. A class +deleted for good and made again with the same IRI has a new id that the release lacks, and the +request is a 404 that names the IRI. A hard delete of a class also removes its bindings. A statement +on it is a 404 when no working row is left, and a 409 that the class has no identity table when the +request still names a class that the release holds. Both are right, because bindings sit outside +versions. A request for a deleted class that names an ontology which is itself deleted is a 404, +checked before the right to the class, since the ontology comes from the working row. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index ec12231a43b0..989c8262f454 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -53,6 +53,8 @@ public final class OntologyConceptBindingStore { private static final String SCHEMA = "ontologyConceptBindings"; private static final String FIRST_PAGE = ""; + // A deleted row and a live one can hold the same IRI, so more than one row per IRI is read. + private static final int WORKING_ROWS_PER_IRI = 8; private static final int MAX_ANCESTORS = OntologyWriteClosureLimits.BINDING_ANCESTORS; private final CollectionDAO dao; private final Function assetTables; @@ -161,6 +163,25 @@ public List contributingRows(final UUID conceptId, final int limit) return dao.ontologyConceptBindingDAO().listContributingRows(conceptId, limit); } + /** + * The working rows of one ontology declared with these IRIs, soft-deleted ones included, in one + * statement. A release answers for a class that was deleted from the draft after it was sealed. + */ + public List workingConcepts(final UUID ontologyId, final Collection iris) { + final var concepts = dao.ontologyConceptDAO(); + return iris.isEmpty() + ? List.of() + : concepts + .findDeclarationsIncludingDeleted( + concepts.getTableName(), + ontologyId, + iris.stream().map(iri -> DigestUtils.md5Hex(iri.toString())).toList(), + WORKING_ROWS_PER_IRI * iris.size()) + .stream() + .map(json -> JsonUtils.readValue(json, OntologyConcept.class)) + .toList(); + } + /** The live concepts of one ontology declared with these IRIs, in one statement. */ public List liveConcepts(final UUID ontologyId, final Collection iris) { final var concepts = dao.ontologyConceptDAO(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java index 10aa7649a09c..c98c4612bb76 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java @@ -158,6 +158,16 @@ List findDeclarations( @BindList("iriHashes") List iriHashes, @Bind("limit") int limit, @Define("locking") String locking); + + /** The rows that declare these IRIs, soft-deleted ones included. */ + @SqlQuery( + "SELECT json FROM

WHERE ontologyId = :ontologyId " + + "AND iriHash IN () ORDER BY name, id LIMIT :limit") + List findDeclarationsIncludingDeleted( + @Define("table") String table, + @BindUUID("ontologyId") UUID ontologyId, + @BindList("iriHashes") List iriHashes, + @Bind("limit") int limit); } interface OntologyConceptDAO extends OntologyMemberDAO { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java index 0a14f6fc10ca..5392e2c8d6e2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java @@ -10,6 +10,7 @@ import java.util.function.Function; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.service.Entity; @@ -41,7 +42,32 @@ final class OntologyBindingAccess { /** The live entity, or an authorization or not-found failure for the caller. */ EntityInterface authorized( final Access access, final String type, final UUID id, final MetadataOperation operation) { - return authorized(access, repositories.apply(type), id, operation); + return authorized(access, repositories.apply(type), id, operation, Include.NON_DELETED); + } + + /** The working row of {@code id}, deleted or not, after the caller's right to it is checked. */ + EntityInterface authorizedWorking( + final Access access, final String type, final UUID id, final MetadataOperation operation) { + return authorized(access, repositories.apply(type), id, operation, Include.ALL); + } + + /** The working row of {@code id}, deleted or not, with no check of the caller's rights. */ + EntityInterface working(final Access access, final String type, final UUID id) { + final EntityRepository repository = repositories.apply(type); + return repository.get(access.uriInfo(), id, fields(repository), Include.ALL, false); + } + + /** + * A released definition, after the caller's right to it is checked with the policy inputs the + * catalog holds now for its id (owners, tags and domains), hydrated as a read of a release + * does. Nothing here reads the working row, which a later delete may have removed. + */ + EntityInterface authorized( + final Access access, + final String type, + final OntologyDefinition released, + final MetadataOperation operation) { + return hydratedAndAuthorized(access, repositories.apply(type), released, operation); } /** The live entity when the caller may view it, and empty when it is hidden or gone. */ @@ -71,6 +97,49 @@ Map> viewable( return viewable; } + /** The released definitions of one type that the caller may view, by id. */ + Map> viewable( + final Access access, final String type, final List released) { + return authorizedBatch(access, repositories.apply(type), released); + } + + private > T hydratedAndAuthorized( + final Access access, + final EntityRepository repository, + final OntologyDefinition released, + final MetadataOperation operation) { + final T entity = repository.getEntityClass().cast(released); + repository.setFieldsInBulk(ResourceContext.authorizationFields(repository), List.of(entity)); + authorizer.authorize( + access.securityContext(), + new OperationContext(repository.getEntityType(), operation), + new ResourceContext<>(repository.getEntityType(), entity, repository)); + return entity; + } + + private > Map> authorizedBatch( + final Access access, + final EntityRepository repository, + final List released) { + final List batch = released.stream().map(repository.getEntityClass()::cast).toList(); + // Every attribute a condition reads; setFieldsInBulk clears the fields it is not asked for. + repository.setFieldsInBulk(ResourceContext.authorizationFields(repository), batch); + final Map> viewable = new HashMap<>(); + for (final T entity : batch) { + try { + authorizer.authorize( + access.securityContext(), + new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), + new ResourceContext<>(repository.getEntityType(), entity, repository)); + viewable.put(entity.getId(), entity); + } catch (final AuthorizationException hidden) { + LOG.debug( + "Released {} {} is hidden from the reader", repository.getEntityType(), entity.getId()); + } + } + return viewable; + } + private > void loadViewable( final Access access, final EntityRepository repository, @@ -102,9 +171,9 @@ private > T authorized( final Access access, final EntityRepository repository, final UUID id, - final MetadataOperation operation) { - final T entity = - repository.get(access.uriInfo(), id, fields(repository), Include.NON_DELETED, false); + final MetadataOperation operation, + final Include include) { + final T entity = repository.get(access.uriInfo(), id, fields(repository), include, false); authorizer.authorize( access.securityContext(), new OperationContext(repository.getEntityType(), operation), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java index c3e9275e05ca..fe7e678ac8fd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java @@ -45,6 +45,7 @@ import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyColumnBinding; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.exception.EntityNotFoundException; @@ -61,6 +62,7 @@ import org.openmetadata.service.ontology.OntologyRelationPath.End; import org.openmetadata.service.ontology.OntologyRelationPath.Ends; import org.openmetadata.service.ontology.OntologyRelationPath.Held; +import org.openmetadata.service.ontology.OntologyVersion.Wanted; import org.openmetadata.service.ontology.sql.FinishedStatement; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.util.FreshReadScope; @@ -77,6 +79,8 @@ * release. */ public final class OntologyStatementService { + private static final String CLASS = "Class"; + private static final String RELATION = "Relation"; private static final String RELATION_OR_COUNT = "An aggregate over a relation takes the relation and the direction together. A count of the" + " class takes neither, and no related class"; @@ -260,16 +264,42 @@ private OntologyStatementPlan top( private Subject subject( final Access access, final UUID classId, final OntologyStatementVersion asked) { + return asked == OntologyStatementVersion.DRAFT + ? draftSubject(access, classId) + : releaseSubject(access, classId); + } + + private Subject draftSubject(final Access access, final UUID classId) { final OntologyConcept working = viewed(access, Entity.ONTOLOGY_CONCEPT, classId); store.requireLiveOntology(working); - final OntologyVersion version; - if (asked == OntologyStatementVersion.DRAFT) { - draftGate.require(access.securityContext(), working.getOntology().getId()); - version = OntologyVersion.draft(dao, working.getOntology()); - } else { - version = OntologyVersion.release(dao, working.getOntology()); - } - return new Subject(version.type(working), working.getOntology(), version); + draftGate.require(access.securityContext(), working.getOntology().getId()); + return new Subject( + working, working.getOntology(), OntologyVersion.draft(dao, working.getOntology())); + } + + /** + * The class as the active release declares it. The working row, deleted or not, only says which + * ontology the class belongs to, so the release answers as it was released whatever the draft + * lost since. + */ + private Subject releaseSubject(final Access access, final UUID classId) { + final OntologyConcept row = + (OntologyConcept) catalog.working(access, Entity.ONTOLOGY_CONCEPT, classId); + store.requireLiveOntology(row); + final OntologyVersion version = OntologyVersion.release(dao, row.getOntology()); + final OntologyConcept declared = + (OntologyConcept) + version.declared( + catalog, + access, + new Wanted( + Entity.ONTOLOGY_CONCEPT, + MemberKind.CONCEPT, + CLASS, + row.getOntology().getId(), + other -> new IllegalStateException("A class belongs to its own ontology")), + classId); + return new Subject(declared, row.getOntology(), version); } private static MappedTable identity( @@ -327,18 +357,32 @@ private Route route(final Access access, final Subject start, final Along along) private OntologyProperty relation( final Access access, final Subject start, final UUID relationId) { - final OntologyProperty working = viewed(access, Entity.ONTOLOGY_PROPERTY, relationId); - final boolean sameOntology = start.ontologyId().equals(working.getOntology().getId()); - final OntologyProperty declared = sameOntology ? start.version().relation(working) : working; - if (!sameOntology || declared.getKind() != OntologyPropertyKind.OBJECT) { - throw new BadRequestException( - String.format( - "Relation %s is not an object property of the ontology of class %s", - working.getIri(), start.iri())); + final OntologyProperty declared = + (OntologyProperty) + start + .version() + .declared( + catalog, + access, + new Wanted( + Entity.ONTOLOGY_PROPERTY, + MemberKind.PROPERTY, + RELATION, + start.ontologyId(), + other -> notAnObjectProperty(((OntologyProperty) other).getIri(), start)), + relationId); + if (declared.getKind() != OntologyPropertyKind.OBJECT) { + throw notAnObjectProperty(declared.getIri(), start); } return declared; } + private static BadRequestException notAnObjectProperty(final URI iri, final Subject start) { + return new BadRequestException( + String.format( + "Relation %s is not an object property of the ontology of class %s", iri, start.iri())); + } + private OntologyConcept relatedClass( final Access access, final Subject start, @@ -346,14 +390,23 @@ private OntologyConcept relatedClass( final Along along) { final UUID id = along.relatedClass() == null ? namedClass(start, relation, along) : along.relatedClass(); - final OntologyConcept working = viewed(access, Entity.ONTOLOGY_CONCEPT, id); - if (!start.ontologyId().equals(working.getOntology().getId())) { - throw new BadRequestException( - String.format( - "Class %s is not a class of the ontology of class %s", - working.getIri(), start.iri())); - } - return start.version().type(working); + return (OntologyConcept) + start + .version() + .declared( + catalog, + access, + new Wanted( + Entity.ONTOLOGY_CONCEPT, + MemberKind.CONCEPT, + CLASS, + start.ontologyId(), + other -> + new BadRequestException( + String.format( + "Class %s is not a class of the ontology of class %s", + ((OntologyConcept) other).getIri(), start.iri()))), + id); } /** The one class a relation names at its far end: its range forward, its domain going back. */ @@ -366,9 +419,9 @@ private UUID namedClass(final Subject start, final OntologyProperty relation, fi "Relation %s names %d classes in its %s, so the request must name the related class", relation.getIri(), named.size(), along.isForward() ? "range" : "domain")); } - return store.liveConcepts(start.ontologyId(), named).stream() - .findFirst() - .map(OntologyConcept::getId) + return start + .version() + .classNamed(store, start.ontologyId(), named) .orElseThrow( () -> EntityNotFoundException.byMessage( @@ -388,10 +441,7 @@ private Map properties( .flatMap(row -> listOrEmpty(row.columns()).stream()) .map(OntologyColumnBinding::getPropertyId) .collect(Collectors.toSet()); - return version.properties( - catalog.viewable(access, Entity.ONTOLOGY_PROPERTY, ids).values().stream() - .map(OntologyProperty.class::cast) - .toList()); + return version.viewableProperties(catalog, access, ids); } @SuppressWarnings("unchecked") diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java index 64f245cfd5ac..362b11f7a9de 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -17,6 +17,7 @@ import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.function.Function; import java.util.stream.Collectors; @@ -27,33 +28,56 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.schema.type.OntologyState; +import org.openmetadata.service.Entity; import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.jdbi3.EntityDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; /** * The version of an ontology that a statement reads: its active release, or its working draft. The * class, its properties, the display name flag and the relations come from that version. Table * bindings sit outside versions (ADR:2026-11-22-record-statements-start-from-the-identity-table). * - *

Every method takes the working definition, because a release keeps the id of the working row - * it was captured from. A definition that the version lacks is a 404 that names its IRI. + *

A release keeps the id of the working row it was captured from, and it answers as it was + * released: a definition is found among the members of the release by id, and a later delete of + * its working row changes nothing. The caller's right to a released definition is checked on the + * definition itself, with the policy inputs the catalog holds now for its id. The working draft + * is read through the working rows, which must be live. */ sealed interface OntologyVersion { + /** The definition a statement looks for, and what to do when it belongs to another ontology. */ + record Wanted( + String entityType, + MemberKind kind, + String noun, + UUID ontologyId, + Function otherOntology) {} + /** What a plan says about the version it read. */ OntologyStatementVersionRead read(); - /** The class as this version declares it. */ - OntologyConcept type(OntologyConcept working); + /** + * The definition as this version declares it, after the caller's right to view it is checked. A + * definition of another ontology is refused with {@code otherOntology}, and one that the version + * lacks is a 404 that names its IRI. + */ + OntologyDefinition declared(OntologyBindingAccess catalog, Access access, Wanted wanted, UUID id); - /** The relation as this version declares it. */ - OntologyProperty relation(OntologyProperty working); + /** The properties among {@code ids} that this version declares and the caller may view. */ + Map viewableProperties( + OntologyBindingAccess catalog, Access access, Collection ids); - /** The properties among {@code working} that this version declares, by id. */ - Map properties(Collection working); + /** + * The id of the one class this version declares with one of {@code iris}, empty when it has + * none. + */ + Optional classNamed(OntologyConceptBindingStore store, UUID ontologyId, List iris); /** The active release of {@code ontology}, or a 404 that says it has none. */ static OntologyVersion release(final CollectionDAO dao, final EntityReference ontology) { @@ -84,28 +108,38 @@ public OntologyStatementVersionRead read() { } @Override - public OntologyConcept type(final OntologyConcept working) { + public OntologyDefinition declared( + final OntologyBindingAccess catalog, + final Access access, + final Wanted wanted, + final UUID id) { + final var working = + (OntologyDefinition) + catalog.authorized(access, wanted.entityType(), id, MetadataOperation.VIEW_BASIC); + if (!wanted.ontologyId().equals(working.getOntology().getId())) { + throw wanted.otherOntology().apply(working); + } return working; } @Override - public OntologyProperty relation(final OntologyProperty working) { - return working; + public Map viewableProperties( + final OntologyBindingAccess catalog, final Access access, final Collection ids) { + return catalog.viewable(access, Entity.ONTOLOGY_PROPERTY, ids).values().stream() + .map(OntologyProperty.class::cast) + .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); } @Override - public Map properties(final Collection working) { - return working.stream() - .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); + public Optional classNamed( + final OntologyConceptBindingStore store, final UUID ontologyId, final List iris) { + return store.liveConcepts(ontologyId, iris).stream().findFirst().map(OntologyConcept::getId); } } /** A sealed release, whose members are stored payloads that never change. */ record Release(CollectionDAO dao, OntologyRelease release, String ontologyName) implements OntologyVersion { - private static final String CLASS = "Class"; - private static final String RELATION = "Relation"; - @Override public OntologyStatementVersionRead read() { return new OntologyStatementVersionRead() @@ -115,45 +149,88 @@ public OntologyStatementVersionRead read() { .withSemanticVersion(release.getSemanticVersion()); } + /** + * A class is found by IRI through the working rows, deleted ones too, and kept only when the + * release holds a member with that id and that IRI. A class deleted for good and made again + * with the same IRI has a new id, which the release lacks, so it is not found. + */ @Override - public OntologyConcept type(final OntologyConcept working) { - return (OntologyConcept) member(MemberKind.CONCEPT, working.getId(), CLASS, working.getIri()); + public Optional classNamed( + final OntologyConceptBindingStore store, final UUID ontologyId, final List iris) { + return store.workingConcepts(ontologyId, iris).stream() + .filter( + row -> + member(MemberKind.CONCEPT, row.getId()) + .map(held -> ((OntologyConcept) held).getIri().equals(row.getIri())) + .orElse(false)) + .findFirst() + .map(OntologyConcept::getId); + } + + /** The member of this release with the id, or empty when the release lacks it. */ + Optional member(final MemberKind kind, final UUID id) { + return Optional.ofNullable( + dao.ontologyReleaseDAO().getMember(release.getId(), kind.value(), id)) + .map(member -> OntologyReleaseReader.definition(release, member)); } @Override - public OntologyProperty relation(final OntologyProperty working) { - return (OntologyProperty) - member(MemberKind.PROPERTY, working.getId(), RELATION, working.getIri()); + public OntologyDefinition declared( + final OntologyBindingAccess catalog, + final Access access, + final Wanted wanted, + final UUID id) { + final Optional held = member(wanted.kind(), id); + if (held.isPresent()) { + return (OntologyDefinition) + catalog.authorized( + access, wanted.entityType(), held.get(), MetadataOperation.VIEW_BASIC); + } + // The release lacks it. The working row, deleted or not, says which refusal fits: a + // definition of another ontology is a 400, and one of this ontology is a 404. + final var working = + (OntologyDefinition) + catalog.authorizedWorking( + access, wanted.entityType(), id, MetadataOperation.VIEW_BASIC); + if (!wanted.ontologyId().equals(working.getOntology().getId())) { + throw wanted.otherOntology().apply(working); + } + throw lacks(wanted.noun(), iriOf(working)); + } + + private static URI iriOf(final OntologyDefinition definition) { + return definition instanceof OntologyConcept concept + ? concept.getIri() + : ((OntologyProperty) definition).getIri(); + } + + /** The 404 for a class or relation that this release does not hold. */ + EntityNotFoundException lacks(final String noun, final URI iri) { + return EntityNotFoundException.byMessage( + String.format( + "%s %s is not in the active release of ontology %s", noun, iri, ontologyName)); } @Override - public Map properties(final Collection working) { - final List ids = - working.stream().map(property -> property.getId().toString()).toList(); + public Map viewableProperties( + final OntologyBindingAccess catalog, final Access access, final Collection ids) { + final List memberIds = ids.stream().map(UUID::toString).toList(); final List releaseIds = List.of(release.getId().toString()); final List members = - ids.isEmpty() + memberIds.isEmpty() ? List.of() : EntityDAO.queryInChunks( - ids, + memberIds, chunk -> dao.ontologyReleaseDAO() .listMemberPayloads(releaseIds, MemberKind.PROPERTY.value(), chunk)); - return members.stream() - .map(member -> (OntologyProperty) OntologyReleaseReader.definition(release, member)) + final List released = + members.stream() + .map(member -> (OntologyProperty) OntologyReleaseReader.definition(release, member)) + .toList(); + return catalog.viewable(access, Entity.ONTOLOGY_PROPERTY, released).values().stream() + .map(OntologyProperty.class::cast) .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); } - - private OntologyDefinition member( - final MemberKind kind, final UUID id, final String noun, final URI iri) { - final OntologyReleaseMember member = - dao.ontologyReleaseDAO().getMember(release.getId(), kind.value(), id); - if (member == null) { - throw EntityNotFoundException.byMessage( - String.format( - "%s %s is not in the active release of ontology %s", noun, iri, ontologyName)); - } - return OntologyReleaseReader.definition(release, member); - } } } From 1a118c036f820dcaf2934fc1fd324bdf165fcc35 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 18:05:52 -0800 Subject: [PATCH 046/203] Test a release statement after a draft delete and the rights of its readers --- .../OntologyStatementReleaseDeleteIT.java | 423 ++++++++++++++++++ 1 file changed, 423 insertions(+) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementReleaseDeleteIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementReleaseDeleteIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementReleaseDeleteIT.java new file mode 100644 index 000000000000..3e4f5a856caa --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementReleaseDeleteIT.java @@ -0,0 +1,423 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.columnPlan; + +import java.net.URI; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; + +/** + * A statement that reads the active release answers as it was released, whatever is deleted from + * the working draft afterwards. The release holds the class, the relation, the related class and + * the properties, so a plain delete in the draft changes the release answer in no way, and the + * same request on the draft still answers from the draft. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyStatementReleaseDeleteIT extends BaseOntologyApprovalIT { + private static final String ORDER = "https://example.org/columnRelation#Order"; + private static final String CUSTOMER = "https://example.org/columnRelation#Customer"; + private static final String LATE = "https://example.org/columnRelation#Late"; + private static final Ask MATCH_CUSTOMERS = + new Ask( + "find-match", + OntologyStatementKind.FIND, + "Customer", + "ada", + null, + null, + null, + null, + null); + private static final String ORDER_TOTAL = "1 property Order orderTotal"; + private static final String CUSTOMER_NAME = "2 displayName Customer customerName"; + + @Test + void aClassDeletedFromTheDraftIsStillReadOnTheRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final Map before = everyAnswer(fixture, admin()); + + deleteClass(fixture, "Order", false); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("find"))); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("expand-forward"))); + } + } + + @Test + void aRelationDeletedFromTheDraftIsStillFollowedOnTheRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedRelation"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final Map before = everyAnswer(fixture, admin()); + + admin().ontologyProperties().delete(fixture.property("placedBy").getId().toString()); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("expand-forward"))); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("aggregate-forward"))); + assertEquals( + List.of("0 key Order part 0", ORDER_TOTAL), + columnPlan(fixture.ask(admin(), COLUMN_RELATION.ask("open"), DRAFT).getColumns())); + } + } + + @Test + void aRelatedClassDeletedFromTheDraftIsStillReachedWithAndWithoutItBeingNamed( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedRelated"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final UUID order = fixture.type("Order").getId(); + final UUID customer = fixture.type("Customer").getId(); + final OntologyProperty placedBy = fixture.property("placedBy"); + final Map before = everyAnswer(fixture, admin()); + final String named = expandForward(order, placedBy, customer); + assertEquals(before.get("expand-forward"), named); + + deleteClass(fixture, "Customer", false); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals(named, expandForward(order, placedBy, customer)); + assertEquals(named, expandForward(order, placedBy, null)); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("expand-forward"))); + } + } + + @Test + void aDataPropertyDeletedFromTheDraftStaysInTheReleasePlan(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedProperty"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final Map before = everyAnswer(fixture, admin()); + + admin().ontologyProperties().delete(fixture.property("orderTotal").getId().toString()); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals( + List.of("0 key Order part 0", ORDER_TOTAL), + columnPlan(fixture.ask(admin(), COLUMN_RELATION.ask("open"), null).getColumns())); + assertEquals( + List.of("0 key Order part 0"), + columnPlan(fixture.ask(admin(), COLUMN_RELATION.ask("open"), DRAFT).getColumns())); + } + } + + @Test + void theDisplayNameDeletedFromTheDraftStaysInTheReleaseAndMatchTextIsStillAccepted( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedDisplayName"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final Map before = everyAnswer(fixture, admin()); + assertTrue(before.get("find-match").contains("LIKE"), before.get("find-match")); + + admin().ontologyProperties().delete(fixture.property("customerName").getId().toString()); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals( + List.of("0 key Order part 0", "1 key Customer part 0", CUSTOMER_NAME), + columnPlan( + fixture.ask(admin(), COLUMN_RELATION.ask("expand-forward"), null).getColumns())); + assertRefused( + 409, + "Class " + + CUSTOMER + + " binds no display name column on its identity table, so it takes no match text", + () -> fixture.ask(admin(), MATCH_CUSTOMERS, DRAFT)); + } + } + + @Test + void aReaderWithoutEditRightsReadsTheReleaseAndIsRefusedTheDraft(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedForReader"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtDelRead" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient consumer = client(access.userToken("consumer", List.of())); + final String name = readerReference(consumer).getName(); + final Map before = everyAnswer(fixture, consumer); + + deleteClass(fixture, "Order", false); + admin().ontologyProperties().delete(fixture.property("placedBy").getId().toString()); + + assertEquals(before, everyAnswer(fixture, consumer)); + // The draft of a class that is still there is refused before anything else is read. + assertRefused( + 403, + "Principal: CatalogPrincipal{name='" + name + "'} operations [EditAll] not allowed", + () -> fixture.ask(consumer, MATCH_CUSTOMERS, DRAFT)); + } + } + + @Test + void aReaderWithoutViewBasicOnTheDeletedClassIsRefusedAsForALiveOne(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedHiddenClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtDelClass" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final var denied = access.denyRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT); + final OpenMetadataClient reader = client(access.userToken("reader", List.of(denied.getId()))); + final String refusal = + "Principal: CatalogPrincipal{name='" + + readerReference(reader).getName() + + "'} operation ViewBasic denied"; + final Map live = refusals(fixture, reader); + + deleteClass(fixture, "Order", false); + deleteClass(fixture, "Customer", false); + + assertEquals(live, refusals(fixture, reader)); + live.values().forEach(message -> assertTrue(message.startsWith(refusal), message)); + assertEquals(COLUMN_RELATION.asks().size(), live.size()); + } + } + + @Test + void aReaderWithoutViewBasicOnADeletedPropertyGetsThePlanWithoutIt(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedHiddenProperty"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtDelProp" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.ONTOLOGY_PROPERTY); + owns(reader, fixture.property("placedBy")); + owns(reader, fixture.property("customerName")); + final Ask open = COLUMN_RELATION.ask("open"); + final Ask expand = COLUMN_RELATION.ask("expand-forward"); + assertEquals( + List.of("0 key Order part 0"), columnPlan(fixture.ask(reader, open, null).getColumns())); + final String expandAnswer = fixture.answer(reader, expand, null); + + admin().ontologyProperties().delete(fixture.property("orderTotal").getId().toString()); + + assertEquals( + List.of("0 key Order part 0"), columnPlan(fixture.ask(reader, open, null).getColumns())); + assertEquals(expandAnswer, fixture.answer(reader, expand, null)); + assertEquals( + List.of("0 key Order part 0", ORDER_TOTAL), + columnPlan(fixture.ask(admin(), open, null).getColumns())); + } + } + + @Test + void aReaderWithoutViewBasicOnTheRelationIsRefusedByEveryStatementAlongIt( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedHiddenRelation"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtDelRel" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.ONTOLOGY_PROPERTY); + owns(reader, fixture.property("orderTotal")); + owns(reader, fixture.property("customerName")); + final String refusal = + "Principal: CatalogPrincipal{name='" + + readerReference(reader).getName() + + "'} operation ViewBasic denied"; + final String openAnswer = fixture.answer(reader, COLUMN_RELATION.ask("open"), null); + final Map live = alongTheRelation(fixture, reader); + + admin().ontologyProperties().delete(fixture.property("placedBy").getId().toString()); + + assertEquals(live, alongTheRelation(fixture, reader)); + assertEquals(4, live.size()); + live.values().forEach(message -> assertTrue(message.startsWith(refusal), message)); + assertEquals(openAnswer, fixture.answer(reader, COLUMN_RELATION.ask("open"), null)); + } + } + + @Test + void aClassDeletedForGoodLeavesNoRowToFindItsOntologyAndNoBindings(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hardDeleted"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final UUID order = fixture.type("Order").getId(); + final UUID customer = fixture.type("Customer").getId(); + final OntologyProperty placedBy = fixture.property("placedBy"); + + deleteClass(fixture, "Customer", true); + + assertRefused( + 409, + "Class " + CUSTOMER + " has no identity table", + () -> expandForward(order, placedBy, customer)); + assertRefused( + 404, + "Class " + CUSTOMER + " is not a class of ontology " + ontology.getFullyQualifiedName(), + () -> expandForward(order, placedBy, null)); + assertRefused( + 404, + "ontologyConcept instance for " + customer + " not found", + () -> fixture.ask(admin(), COLUMN_RELATION.ask("expand-inverse"), null)); + } + } + + @Test + void aClassWhoseWorkingRowIsLiveButTheReleaseLacksIsNotInTheRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "lateClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final UUID late = declareClass(ontology, "Late", URI.create(LATE)).getId(); + + assertRefused( + 404, + "Class " + + LATE + + " is not in the active release of ontology " + + ontology.getFullyQualifiedName(), + () -> postFind(late)); + } + } + + /** + * Deletes the class from the draft. A class that a property still names in its domain or range + * cannot be deleted, so the properties that name it go first and the class goes last. + */ + private static void deleteClass( + final OntologyShapeFixture fixture, final String name, final boolean hard) { + final URI iri = fixture.type(name).getIri(); + for (final String property : List.of("orderTotal", "customerName", "placedBy")) { + final OntologyProperty held = fixture.property(property); + final boolean names = held.getDomain().contains(iri) || held.getRange().contains(iri); + final var current = admin().ontologyProperties().get(held.getId().toString(), null, "all"); + if (names && !Boolean.TRUE.equals(current.getDeleted())) { + admin().ontologyProperties().delete(held.getId().toString()); + } + } + admin() + .ontologyConcepts() + .delete( + fixture.type(name).getId().toString(), Map.of("hardDelete", Boolean.toString(hard))); + } + + private static Map everyAnswer( + final OntologyShapeFixture fixture, final OpenMetadataClient client) { + final Map answers = new LinkedHashMap<>(); + for (final Ask asked : COLUMN_RELATION.asks()) { + answers.put(asked.name(), fixture.answer(client, asked, null)); + } + answers.put(MATCH_CUSTOMERS.name(), fixture.answer(client, MATCH_CUSTOMERS, null)); + return answers; + } + + private static Map refusals( + final OntologyShapeFixture fixture, final OpenMetadataClient client) { + final Map refused = new LinkedHashMap<>(); + for (final Ask asked : COLUMN_RELATION.asks()) { + refused.put(asked.name(), refusal(() -> fixture.ask(client, asked, null))); + } + return refused; + } + + private static Map alongTheRelation( + final OntologyShapeFixture fixture, final OpenMetadataClient client) { + final Map refused = new LinkedHashMap<>(); + for (final String name : + List.of("expand-forward", "expand-inverse", "aggregate-forward", "aggregate-inverse")) { + refused.put(name, refusal(() -> fixture.ask(client, COLUMN_RELATION.ask(name), null))); + } + return refused; + } + + private static String refusal(final Runnable request) { + final OpenMetadataException refused = assertThrows(OpenMetadataException.class, request::run); + assertEquals(403, refused.getStatusCode()); + return refused.getMessage(); + } + + private static int draftStatus(final OntologyShapeFixture fixture, final Ask asked) { + return assertThrows(OpenMetadataException.class, () -> fixture.ask(admin(), asked, DRAFT)) + .getStatusCode(); + } + + private static void owns(final OpenMetadataClient reader, final OntologyProperty property) { + final String id = property.getId().toString(); + admin() + .ontologyProperties() + .update( + id, + admin() + .ontologyProperties() + .get(id, "owners") + .withOwners(List.of(readerReference(reader)))); + } + + /** The body of the expand statement of order 31 on the release, as the server wrote it. */ + private static String expandForward( + final UUID type, final OntologyProperty relation, final UUID relatedClass) { + return admin() + .getHttpClient() + .executeForString( + HttpMethod.POST, + "/v1/ontologyConcepts/" + type + "/statements/expand", + new OntologyExpandStatementRequest() + .withKey(List.of(31)) + .withRelation(relation.getId()) + .withDirection(OntologyStatementDirection.FORWARD) + .withRelatedClass(relatedClass)); + } + + private static OntologyStatementPlan postFind(final UUID type) { + return admin() + .getHttpClient() + .execute( + HttpMethod.POST, + "/v1/ontologyConcepts/" + type + "/statements/find", + new org.openmetadata.schema.api.data.OntologyFindStatementRequest(), + OntologyStatementPlan.class); + } +} From 55e0997226d4ea6cb18b9891b30c1107a14cb530 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 18:10:28 -0800 Subject: [PATCH 047/203] Read the operations of a change set only with the draft read right, and refuse a save made on stale sight A change set is excluded from the RDF projection and its RDF view refuses the type. The audit log and the entity tool of the MCP server ask for the same right that reads the draft over REST, through one access class. A save refuses with a 412 when the withheld count a writer read differs from what the stored operation withholds from that writer now. The refusal of the patch tool no longer names an endpoint the resource lacks. --- .../openmetadata/mcp/tools/GetEntityTool.java | 20 +++++ .../mcp/tools/PatchEntityTool.java | 8 ++ .../mcp/tools/PatchEntityToolTest.java | 16 +++- .../ontology/OntologyChangeEvidenceView.java | 37 +++++++- .../ontology/OntologyChangeSetReadAccess.java | 87 +++++++++++++++++++ .../service/rdf/RdfExcludedEntities.java | 6 +- .../resources/audit/AuditLogResource.java | 34 ++++++++ .../ontology/OntologyChangeSetResource.java | 23 +++-- .../service/resources/rdf/RdfResource.java | 5 ++ .../OntologyChangeEvidenceViewTest.java | 65 ++++++++++++++ .../service/rdf/RdfExcludedEntitiesTest.java | 5 ++ .../schema/type/ontologyChangeOperation.json | 2 +- 12 files changed, 292 insertions(+), 16 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java index 59042e0cf1c5..7936ff57bf5a 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java @@ -33,6 +33,7 @@ import org.openmetadata.service.jdbi3.LineageRepository; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.lineage.LineagePermissionFilter; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.search.vector.OpenSearchVectorService; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.auth.CatalogSecurityContext; @@ -252,6 +253,7 @@ private Map readOne( String fqn) { List includes = McpParams.getStringList(params, INCLUDE_PARAM).stream().distinct().toList(); + requireDraftRead(authorizer, securityContext, entityType, fqn); if (includes.size() == 1 && includes.contains(INCLUDE_CONTENT)) { return readContentOnly(authorizer, securityContext, params, entityType, fqn); } @@ -297,6 +299,24 @@ private Map readOne( return windowed; } + /** + * A change set holds operations no release has published, so it is read with the right that + * edits its scope, as the REST resource does, whatever sections the call asks for. + */ + private static void requireDraftRead( + Authorizer authorizer, + CatalogSecurityContext securityContext, + String entityType, + String fqn) { + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + OntologyChangeSetReadAccess.requireRead( + authorizer, + securityContext, + Entity.getEntityByName( + entityType, fqn, OntologyChangeSetReadAccess.SCOPE_FIELDS, Include.ALL)); + } + } + private static Map readContentOnly( Authorizer authorizer, CatalogSecurityContext securityContext, diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java index cda3a2b86faf..069374b907f3 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java @@ -156,6 +156,14 @@ private static void requireTarget(String entityType, String fqn) { } private static void requireGenericPatchLifecycle(String entityType) { + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + throw new IllegalArgumentException( + "entityType '" + + entityType + + "' cannot be patched through patch_entity because a change set is saved whole," + + " with its edit lease and the evidence each reader may see. A change set has no" + + " PATCH endpoint. Nothing was changed."); + } if (DEDICATED_PATCH_LIFECYCLES.contains(entityType)) { throw new IllegalArgumentException( "entityType '" diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java index c53753ac0f88..09233168e3c3 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java @@ -380,7 +380,6 @@ void execute_letsMetricDescriptionEditsThrough() { "ingestionPipeline", "intakeForm", "notificationTemplate", - "ontologyChangeSet", "persona", "testCase", "testSuite", @@ -403,6 +402,21 @@ void execute_rejectsEntitiesWhoseResourceOwnsThePatchLifecycle(String entityType verifyNoInteractions(authorizer); } + @Test + void execute_refusesAChangeSetWithoutNamingAnEndpointItLacks() { + Map params = new HashMap<>(); + params.put("entityType", "ontologyChangeSet"); + params.put("fqn", "target"); + params.put("patch", "[]"); + + assertThatThrownBy(() -> new PatchEntityTool().execute(authorizer, securityContext, params)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("A change set has no PATCH endpoint") + .hasMessageNotContaining("dedicated OpenMetadata REST PATCH API") + .hasMessageContaining("Nothing was changed"); + verifyNoInteractions(authorizer); + } + @Test void execute_rejectsTimeSeriesEntitiesBeforeAuthorization() { Map params = new HashMap<>(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java index 80ce74e860ef..0c4bea2dfdac 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java @@ -32,6 +32,7 @@ import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.PreconditionFailedException; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.security.Authorizer; @@ -112,24 +113,54 @@ public void applyAll(final Collection changeSets) { */ public List savedByReader( final List stored, final List incoming) { + return savedByReader(stored, incoming, Map.of()); + } + + /** As above, refusing the save when an operation's sight changed since the writer read it. */ + public List savedByReader( + final List stored, + final List incoming, + final Map readWithheldCounts) { final Map> storedEvidence = stored.stream() - .filter(operation -> !listOrEmpty(operation.getEvidence()).isEmpty()) .collect( Collectors.toMap( OntologyChangeOperation::getId, - OntologyChangeOperation::getEvidence, + operation -> listOrEmpty(operation.getEvidence()), (first, second) -> first)); decide(Stream.concat(stored.stream(), incoming.stream())); for (final OntologyChangeOperation operation : incoming) { final List kept = storedEvidence.get(operation.getId()); - if (kept != null || !listOrEmpty(operation.getEvidence()).isEmpty()) { + requireSameSight(operation, kept, readWithheldCounts.get(operation.getId())); + if (!listOrEmpty(kept).isEmpty() || !listOrEmpty(operation.getEvidence()).isEmpty()) { save(operation, listOrEmpty(kept)); } } return incoming; } + /** + * A writer sends back how many entries its read withheld. When the stored operation withholds a + * different number from this writer now, a table came into or went out of its sight after the + * read, and the entries it sends no longer say what it read. The one change it cannot see is a + * table that becomes visible while another becomes hidden, which leaves the number equal. + */ + private void requireSameSight( + final OntologyChangeOperation operation, + final List stored, + final Integer readWithheld) { + if (stored != null && readWithheld != null) { + final long withheldNow = stored.stream().filter(entry -> !mayView(entry)).count(); + if (readWithheld.longValue() != withheldNow) { + throw new PreconditionFailedException( + "The evidence of operation '" + + operation.getId() + + "' changed for you since you read this change set. Read the change set again," + + " then save."); + } + } + } + /** * Walks the stored entries in order. A withheld one keeps its place, and the place of a shown one * goes to the next entry the reader sent about a table it may view. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java new file mode 100644 index 000000000000..de6c42a50a14 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import jakarta.ws.rs.core.SecurityContext; +import org.openmetadata.schema.entity.data.Glossary; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.service.Entity; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.CreateResourceContext; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; + +/** + * The right that reads the operations of a change set, whatever the path that returns them. A + * change set holds operations that no release has published, so it is read with the right that + * edits its scope: edit on the ontology it targets, or edit on each glossary it targets. Every + * response that carries the operations asks for this, so a user who may only view change sets + * learns nothing a draft read would not show. + */ +public final class OntologyChangeSetReadAccess { + /** The fields a check needs to find the scope of a stored change set. */ + public static final String SCOPE_FIELDS = "operations"; + + private OntologyChangeSetReadAccess() {} + + /** Throws the authorizer's refusal unless the caller may read the operations of this change set. */ + public static void requireRead( + final Authorizer authorizer, + final SecurityContext securityContext, + final OntologyChangeSet changeSet) { + if (changeSet.getOntology() != null) { + authorizer.authorize( + securityContext, + new OperationContext(Entity.ONTOLOGY, MetadataOperation.EDIT_ALL), + new ResourceContext<>(Entity.ONTOLOGY, changeSet.getOntology().getId(), null)); + return; + } + for (final EntityReference glossary : listOrEmpty(changeSet.getGlossaries())) { + requireGlossaryRead( + authorizer, securityContext, glossary, plannedGlossary(changeSet, glossary)); + } + } + + private static void requireGlossaryRead( + final Authorizer authorizer, + final SecurityContext securityContext, + final EntityReference glossary, + final Glossary planned) { + if (planned != null) { + authorizer.authorize( + securityContext, + new OperationContext(Entity.GLOSSARY, MetadataOperation.CREATE), + new CreateResourceContext<>(Entity.GLOSSARY, planned)); + return; + } + authorizer.authorize( + securityContext, + new OperationContext(Entity.GLOSSARY, MetadataOperation.EDIT_ALL), + new ResourceContext<>(Entity.GLOSSARY, glossary.getId(), null)); + } + + private static Glossary plannedGlossary( + final OntologyChangeSet changeSet, final EntityReference glossary) { + return listOrEmpty(changeSet.getOperations()).stream() + .filter(change -> change.getGlossary() != null) + .map(change -> change.getGlossary()) + .filter(candidate -> candidate.getId().equals(glossary.getId())) + .findFirst() + .orElse(null); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java index 808a20ad6a99..0050dd0f667e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java @@ -30,7 +30,8 @@ public final class RdfExcludedEntities { private static final String AI_CHART = "aiChart"; - // Native ontology meaning is published only through the active release's dedicated graph. + // Native ontology meaning is published only through the active release's dedicated graph. A + // change set is a draft: its operations and their evidence are read through the draft read right. public static final Set EXCLUDED_ENTITY_TYPES = Set.of( AI_CHART, @@ -39,7 +40,8 @@ public final class RdfExcludedEntities { Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_AXIOM, Entity.ONTOLOGY_SHAPE, - Entity.ONTOLOGY_RELEASE); + Entity.ONTOLOGY_RELEASE, + Entity.ONTOLOGY_CHANGE_SET); private RdfExcludedEntities() {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java index 2b60d992e525..ddbb17520503 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java @@ -28,7 +28,9 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.utils.ResultList; @@ -40,6 +42,8 @@ import org.openmetadata.service.csv.CsvAsyncJobManager; import org.openmetadata.service.csv.CsvExportPayload; import org.openmetadata.service.csv.CsvExportSpool; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.resources.Collection; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.DefaultAuthorizer; @@ -419,6 +423,9 @@ private void authorizeAuditLogAccess( ResourceContext entityContext = new ResourceContext<>(entityType, null, entityFqn); OperationContext viewOp = new OperationContext(entityType, MetadataOperation.VIEW_BASIC); authorizer.authorize(securityContext, viewOp, entityContext); + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + authorizeChangeSetOperations(securityContext, entityFqn); + } } else if (!nullOrEmpty(serviceName) && !nullOrEmpty(entityType)) { // Service-level authorization: user needs VIEW_BASIC on the service String serviceType = Entity.getServiceType(entityType); @@ -433,6 +440,33 @@ private void authorizeAuditLogAccess( } } + /** + * The events of a change set hold its operations, which a draft read returns only to the right + * that edits its scope. A change set that cannot be loaded, such as a deleted one, leaves only + * the audit-log permission. + */ + private void authorizeChangeSetOperations(SecurityContext securityContext, String entityFqn) { + OntologyChangeSet changeSet = null; + try { + changeSet = + Entity.getEntityByName( + Entity.ONTOLOGY_CHANGE_SET, + entityFqn, + OntologyChangeSetReadAccess.SCOPE_FIELDS, + Include.ALL); + } catch (EntityNotFoundException e) { + LOG.debug("Change set {} cannot be loaded; the audit-log permission applies", entityFqn); + } + if (changeSet == null) { + authorizer.authorize( + securityContext, + new OperationContext(Entity.AUDIT_LOG, MetadataOperation.AUDIT_LOGS), + AuditLogResourceContext.INSTANCE); + return; + } + OntologyChangeSetReadAccess.requireRead(authorizer, securityContext, changeSet); + } + /** * Resource context for audit log permission checks. Uses singleton pattern since audit logs have * no owners, tags, or domains - just a resource type for policy evaluation. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java index f79d6878d50a..42df77391299 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java @@ -73,6 +73,7 @@ import org.openmetadata.service.ontology.OntologyBindingChanges; import org.openmetadata.service.ontology.OntologyChangeApplicationService; import org.openmetadata.service.ontology.OntologyChangeEvidenceView; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.ontology.OntologyChangeSetValidator; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.ontology.OntologyDraftPreflight; @@ -267,11 +268,22 @@ private List savable( final UpdateOntologyChangeSet request) { final OntologyChangeSet draft = scopedChangeSet(id); final List stored = listOrEmpty(draft.getOperations()); + final Map readWithheld = withheldCountsRead(request.getOperations()); draft.setOperations(request.getOperations()); draft.setUndoCursor(request.getUndoCursor()); OntologyChangeSetValidator.normalizeAndValidate(draft); requireResolved(draft); - return evidence.savedByReader(stored, draft.getOperations()); + return evidence.savedByReader(stored, draft.getOperations(), readWithheld); + } + + /** What each operation says its writer's read withheld, taken before validation clears it. */ + private static Map withheldCountsRead(final List sent) { + final Map counts = new LinkedHashMap<>(); + listOrEmpty(sent).stream() + .filter(operation -> operation.getId() != null) + .filter(operation -> operation.getWithheldEvidenceCount() != null) + .forEach(operation -> counts.put(operation.getId(), operation.getWithheldEvidenceCount())); + return counts; } private void requireResolved(final OntologyChangeSet draft) { @@ -474,14 +486,7 @@ private void authorizeChangeSet(final SecurityContext securityContext, final UUI */ private void authorizeScopeRead( final SecurityContext securityContext, final OntologyChangeSet changeSet) { - if (changeSet.getOntology() != null) { - OntologyResourceAccess.requireDraftRead( - authorizer, - securityContext, - new ResourceContext<>(Entity.ONTOLOGY, changeSet.getOntology().getId(), null)); - return; - } - authorizeGlossaryScope(securityContext, changeSet, MetadataOperation.EDIT_ALL); + OntologyChangeSetReadAccess.requireRead(authorizer, securityContext, changeSet); } private void authorizeScope( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java index 9b441ceb3137..d323fa6d90f0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java @@ -998,6 +998,11 @@ public Response getEntityAsRdf( @Parameter(description = "Entity id", required = true) @PathParam("id") UUID id, @Parameter(description = "RDF format") @QueryParam("format") @DefaultValue("jsonld") String format) { + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + // A change set is a draft read with the draft read right, and its evidence is masked per + // reader. + throw new AuthorizationException("A change set has no RDF view"); + } authorizer.authorize( securityContext, new OperationContext(entityType, MetadataOperation.VIEW_ALL), diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java index a162ecdf92b4..355cbb165e57 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java @@ -35,6 +35,7 @@ import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.PreconditionFailedException; import org.openmetadata.service.secrets.masker.MaskedFields; /** Evidence as a reader sees it, what a save by that reader stores, and what no reader is sent. */ @@ -200,6 +201,70 @@ void aSaveRefusesMoreEvidenceThanAnOperationHolds() { refusal.getMessage()); } + @Test + void aSaveThatSendsBackTheCountItsReadWithheldIsAccepted() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN))); + + assertEquals( + List.of(name(SHOWN), profile(HIDDEN)), + view.savedByReader( + stored, + List.of(operation(OPERATION_ID, name(SHOWN))), + java.util.Map.of(OPERATION_ID, 1)) + .getFirst() + .getEvidence()); + } + + @Test + void + aSaveIsRefusedWhenTheCountItsReadWithheldIsLargerOrSmallerThanTheStoredOperationWithholdsNow() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN))); + + for (final int read : new int[] {0, 2}) { + final PreconditionFailedException refusal = + assertThrows( + PreconditionFailedException.class, + () -> + view.savedByReader( + stored, + List.of(operation(OPERATION_ID, name(SHOWN))), + java.util.Map.of(OPERATION_ID, read))); + assertEquals( + "The evidence of operation '" + + OPERATION_ID + + "' changed for you since you read this change set. Read the change set again," + + " then save.", + refusal.getMessage()); + } + } + + @Test + void aCountSentWhenNothingIsWithheldIsRefusedOnlyWhenItIsNotZero() { + final List stored = List.of(operation(OPERATION_ID, name(SHOWN))); + final List sent = List.of(operation(OPERATION_ID, name(SHOWN))); + + assertEquals( + List.of(name(SHOWN)), + view.savedByReader(stored, sent, java.util.Map.of(OPERATION_ID, 0)) + .getFirst() + .getEvidence()); + assertThrows( + PreconditionFailedException.class, + () -> view.savedByReader(stored, sent, java.util.Map.of(OPERATION_ID, 3))); + } + + @Test + void aCountForAnOperationTheDraftDoesNotStoreIsNotChecked() { + final UUID added = UUID.randomUUID(); + + assertNull( + view.savedByReader(List.of(), List.of(operation(added)), java.util.Map.of(added, 4)) + .getFirst() + .getEvidence()); + } + private List saved( final List stored, final OntologyChangeOperation sent) { return view.savedByReader(stored, List.of(sent)).getFirst().getEvidence(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfExcludedEntitiesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfExcludedEntitiesTest.java index 7f521948ce3f..a0638747d77b 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfExcludedEntitiesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfExcludedEntitiesTest.java @@ -34,6 +34,11 @@ void nativeWorkingDefinitionsNeverEnterGenericProjection() { .forEach(type -> assertTrue(RdfExcludedEntities.isExcluded(type))); } + @Test + void aChangeSetNeverEntersTheProjectionOrItsRelationshipEdges() { + assertTrue(RdfExcludedEntities.isExcluded(Entity.ONTOLOGY_CHANGE_SET)); + } + @Test @DisplayName("aiChart is excluded from RDF") void aiChartIsExcluded() { diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json index a7eaa89e7454..d8c2a0c8f05f 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json @@ -143,7 +143,7 @@ "mask": true }, "withheldEvidenceCount": { - "description": "How many evidence entries a read left out of this operation because the reader may not view the table they name, or because that table no longer exists. The server sets it on every operation it returns that stores evidence. It is never stored, and a value that a client sends is ignored.", + "description": "How many evidence entries a read left out of this operation because the reader may not view the table they name, or because that table no longer exists. The server sets it on every operation it returns that stores evidence. It is never stored. It is read-only in effect: a client sends it back unchanged on a save, and when it is present and differs from the number the server withholds from that writer now for the stored operation, the save is refused with a 412 and the writer reads the change set again. A save that sends none is not checked.", "type": "integer", "minimum": 0, "mask": true From 4d0919e62c54bc04dd699fb3ba826f86fd8469c8 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 18:27:09 -0800 Subject: [PATCH 048/203] Test the draft read right on the audit log, the entity tool and the RDF view, and the refusal of a save made on stale sight The audit log also answers the service name path of a change set with the draft read right, because the events of a change set carry its own name as their service name. Two more integration tests show that an apply is refused without edit on the class and without view on a join target, and the record states the covered paths and the one save case the count cannot catch. --- ...set-can-carry-table-bindings-and-shapes.md | 47 ++- .../it/tests/OntologyChangeSetBindingIT.java | 63 ++++ .../tests/OntologyChangeSetDraftReadIT.java | 199 ++++++++++++ .../OntologyChangeSetDraftReadMcpIT.java | 201 ++++++++++++ .../tests/OntologyChangeSetSaveSightIT.java | 301 ++++++++++++++++++ .../it/tests/RdfOntologyChangeSetViewIT.java | 123 +++++++ .../resources/audit/AuditLogResource.java | 4 + 7 files changed, 932 insertions(+), 6 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadMcpIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetSaveSightIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfOntologyChangeSetViewIT.java diff --git a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md index 5a43f2115ad6..f254fa92383b 100644 --- a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md +++ b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md @@ -1,9 +1,9 @@ # An ontology change set can carry table bindings and shapes - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (every path that returns operations asks for the draft read right, and a save is refused when the writer's sight changed since its read) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyBindingAndShapeOperationTest`, `OntologyDraftPreflightTest`, `OntologyBindingChangeExecutorTest`, `OntologyChangeApplicationServiceTest`, `OntologyChangeEvidenceViewTest`, `OntologyChangeSetBindingIT`, `OntologyChangeSetEvidenceIT`, `OntologyChangeSetEvidenceMcpIT`, `PatchEntityToolTest` +- **Guard:** `OntologyBindingAndShapeOperationTest`, `OntologyDraftPreflightTest`, `OntologyBindingChangeExecutorTest`, `OntologyChangeApplicationServiceTest`, `OntologyChangeEvidenceViewTest`, `OntologyChangeSetBindingIT`, `OntologyChangeSetEvidenceIT`, `OntologyChangeSetEvidenceMcpIT`, `OntologyChangeSetDraftReadIT`, `OntologyChangeSetDraftReadMcpIT`, `OntologyChangeSetSaveSightIT`, `RdfOntologyChangeSetViewIT`, `RdfExcludedEntitiesTest`, `PatchEntityToolTest` - **Related:** ADR:2026-10-19-native-concept-bindings-remain-operational-metadata (amended by this record), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records, ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints, @@ -53,6 +53,27 @@ operations leaves out each entry whose table its caller lacks `ViewBasic` on, an every caller. The stored operation keeps every entry. "Every response" means every endpoint of the change set resource, the versions it serves and the MCP tool that reads an entity. +The paths that return the operations of a change set and the way each is covered: + +- The change set resource, its versions and its history: evidence masked per reader, and the draft + read right, which is `EditAll` on the ontology the change set targets or on each glossary it + targets. +- The audit log, read for one change set: the same draft read right, asked after `ViewBasic`. A + change set that is deleted is still checked, and one that cannot be loaded leaves only the + audit-log permission. The audit log of an entity type that has no service never answers a + service name for a change set, and the export of the audit log needs the audit-log permission. +- The MCP tool that reads an entity, in each call shape: the same draft read right, then the + evidence masked per reader. +- The RDF view and the knowledge graph: a change set is not in them. It is excluded from the + projection and from its relationship edges, and the RDF endpoint for one entity refuses the type. + A graph built before this record holds change sets until its next full rebuild. +- Change events, recorded changes and stored versions: they hold the operations without evidence, + and a version is masked when it is read. + +No other endpoint returns the operations of a change set. Entity versions, feed and activity, +lineage, search and the generic entity readers carry no operations of a change set, and an event +subscription receives the stored change event, which holds no evidence. + The MCP tool that patches an entity refuses a change set. A JSON Patch can copy a stored entry into a member that every reader is shown, and the change set resource itself offers no patch. @@ -61,6 +82,16 @@ may view, and keeps the stored entries the writer was not shown, each in its pla entry about a table the writer may not view. Storing one would repeat a withheld entry, and merging the repeat would tell the writer what is withheld. +A client sends back the `withheldEvidenceCount` that it read on each operation. When it is present +and differs from the number the stored operation withholds from that writer now, the save is a 412 +that names the operation and tells the writer to read the change set again. Without this, a writer +who read an operation while a table was hidden from it, and saved after the table became visible, +would send an operation that omits an entry it could now see, and the save would remove that entry. +An operation that sends no count is not checked. One case is not caught: a table becomes visible to +the writer while another becomes hidden, so the two counts agree. The save then stores the entries +the writer sent about tables it can view and keeps those it cannot, and the entry that became +visible stays in the draft as the stored operation holds it. + `evidence` and `withheldEvidenceCount` are masked fields (ADR:2026-10-26-masked-fields-stay-out-of-change-events-and-version-history), so no stored change event holds them, and the recorded change of `operations` holds the operations without their @@ -111,10 +142,14 @@ therefore learn from a refusal whether the table and a named column exist. The a draft that only someone who may view every table it names can save. That rule would tie a review to the rights of the author. -The fields of a binding operation are part of the operation, and every reader of the change set -sees them. Only evidence is masked for each reader. Reading the operations of a change set already -requires the right to edit its scope -(ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights). +The fields of a binding operation are part of the operation, and every reader who holds the draft +read right sees them, the table id, the key columns and the row filter among them. They are not +masked, for this reason: the same draft declares the classes and properties that were made from +those tables, so it already says what the columns are, and the bindings API hides a stored binding +and not a proposal. The table id is opaque. Applying still checks the rights of whoever applies. +Every path that returns them asks for the draft read right +(ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights), so a user who may only view +change sets learns none of it. An author cites only tables it may view. A service that drafts with wider rights than the person it drafts for therefore saves the draft itself, and that person then reads it through their own view. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java index bc2e9fa5fad9..02db987a89ed 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java @@ -44,6 +44,7 @@ import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; import static org.openmetadata.it.tests.OntologyMappingFixtures.join; import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; import static org.openmetadata.it.tests.OntologyMappingFixtures.put; import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; import static org.openmetadata.it.tests.OntologyMappingFixtures.table; @@ -188,6 +189,68 @@ void aBindingIsWrittenWithTheRightsOfTheCallerWhoAppliesAndNotOfTheAuthor( } } + @Test + void aBindingAppliedByACallerWithoutEditAllOnTheClassIsRefusedAndNothingIsWritten( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + try (var fixtures = new RdfAccessFixtures("applyClass" + ns.shortPrefix())) { + final OpenMetadataClient cannotEditClass = + callerWithout(fixtures, MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CONCEPT, null); + final OntologyChangeSet draft = draft(admin(), ns, ontology, binds(bindingOf(ORDER, orders))); + final long revision = workingRevision(ontology); + + assertRefused(FORBIDDEN, "EditAll", () -> apply(cannotEditClass, draft)); + + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(revision, workingRevision(ontology)); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), draft).getState()); + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), draft).getState()); + } + } + + @Test + void aJoinAppliedByACallerWhoMayNotViewItsTargetIsRefusedAndNothingIsWritten( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept customer = declareClass(ontology, "Customer", CUSTOMER); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final OntologyProperty placedBy = objectProperty(ontology, "placedBy", order, customer); + final DatabaseSchema schema = schema(ns); + final Table customers = table(schema, "customers", column("id", ColumnDataType.BIGINT)); + try (var fixtures = new RdfAccessFixtures("applyJoin" + ns.shortPrefix())) { + final OpenMetadataClient ownTablesOnly = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final Table orders = + ownedTable( + schema, + "orders", + OntologyBindingFixtures.readerReference(ownTablesOnly), + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, orders) + .withColumns( + List.of( + boundColumn(placedBy.getIri(), "customer_id") + .withJoin(joinTo(customers, "customer_id", "id")))))); + final long revision = workingRevision(ontology); + + assertRefused(FORBIDDEN, "ViewBasic", () -> apply(ownTablesOnly, draft)); + + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(revision, workingRevision(ontology)); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), draft).getState()); + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), draft).getState()); + } + } + @Test void aRowFilterAppliedByACallerWithoutViewSampleDataIsRefusedAsItsCaseExpects( final TestNamespace ns) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java new file mode 100644 index 000000000000..5ab9ca2811b3 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java @@ -0,0 +1,199 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.time.Duration; +import java.util.List; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * The audit log of a change set holds its operations, so it is read with the right that reads the + * draft: edit on the ontology the change set targets. View rights on change sets and on the table + * are not enough, and a deleted change set leaves only the audit-log permission. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetDraftReadIT extends BaseOntologyApprovalIT { + private static final String COLUMN = "draft_read_column"; + private static final String VALUE = "draft_read_value"; + private static final String AUDIT = "/v1/audit/logs?limit=50&entityType=ontologyChangeSet"; + private static final int FORBIDDEN = 403; + + private record Scene( + OntologyChangeSet draft, Table table, OpenMetadataClient author, OpenMetadataClient viewer) { + String fqn() { + return draft.getFullyQualifiedName(); + } + + void assertNoSecretIn(final String body) { + assertFalse(body.contains(table.getId().toString()), body); + assertFalse(body.contains(COLUMN), body); + assertFalse(body.contains(VALUE), body); + } + } + + @Test + void aUserWhoMayOnlyViewChangeSetsIsRefusedItsAuditLogAndTheEditorsAndAdminAreNot( + final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditRead" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditReadViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + + final OpenMetadataException refusal = + assertThrows(OpenMetadataException.class, () -> audit(scene.viewer(), scene.fqn())); + + assertEquals(FORBIDDEN, refusal.getStatusCode()); + scene.assertNoSecretIn(refusal.getMessage()); + assertTrue(audit(scene.author(), scene.fqn()).contains(scene.table().getId().toString())); + assertTrue(audit(admin(), scene.fqn()).contains(scene.table().getId().toString())); + } + } + + @Test + void aSoftDeletedChangeSetIsStillCheckedAgainstTheDraftReadRight(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditSoft" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditSoftViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + delete(scene, false); + + final OpenMetadataException refusal = + assertThrows(OpenMetadataException.class, () -> audit(scene.viewer(), scene.fqn())); + + assertEquals(FORBIDDEN, refusal.getStatusCode()); + scene.assertNoSecretIn(refusal.getMessage()); + assertTrue(audit(scene.author(), scene.fqn()).contains(scene.table().getId().toString())); + assertTrue(audit(admin(), scene.fqn()).contains(scene.table().getId().toString())); + } + } + + @Test + void aHardDeletedChangeSetLeavesOnlyTheAuditLogPermission(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditHard" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditHardViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + delete(scene, true); + + final OpenMetadataException refusal = + assertThrows(OpenMetadataException.class, () -> audit(scene.viewer(), scene.fqn())); + assertEquals(FORBIDDEN, refusal.getStatusCode()); + scene.assertNoSecretIn(refusal.getMessage()); + assertTrue(audit(admin(), scene.fqn()).contains(scene.table().getId().toString())); + } + } + + @Test + void theServiceNamePathIsNotAWayRoundTheDraftReadRight(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditService" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditServiceViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + + for (final String serviceName : List.of(scene.fqn(), scene.draft().getName())) { + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> get(scene.viewer(), AUDIT + "&serviceName=" + serviceName)); + assertEquals(FORBIDDEN, refusal.getStatusCode(), serviceName); + scene.assertNoSecretIn(refusal.getMessage()); + } + assertTrue( + get(scene.author(), AUDIT + "&serviceName=" + scene.fqn()) + .contains(scene.table().getId().toString())); + } + } + + private static Scene scene( + final TestNamespace ns, final RdfAccessFixtures fixtures, final RdfAccessFixtures viewers) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final OpenMetadataClient author = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final var viewAll = viewers.allowRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_CHANGE_SET); + final var viewBasic = + viewers.allowRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CHANGE_SET); + final var noTables = viewers.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OpenMetadataClient viewer = + OntologyBindingFixtures.client( + viewers.userToken( + "viewer", List.of(viewAll.getId(), viewBasic.getId(), noTables.getId()))); + final Table table = table(schema(ns), "hidden", column(COLUMN, ColumnDataType.VARCHAR)); + final OntologyChangeSet draft = + draft( + author, + ns, + ontology, + binds( + bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(COLUMN))) + .withRowFilter(filter(COLUMN, OntologyRowFilterOperator.EQUALS, VALUE)))); + return new Scene(draft, table, author, viewer); + } + + private static void awaitCreated(final Scene scene) { + Awaitility.await("the audit event of the draft") + .atMost(Duration.ofSeconds(60)) + .until(() -> audit(admin(), scene.fqn()).contains("entityCreated")); + } + + private static void delete(final Scene scene, final boolean hard) { + admin() + .getHttpClient() + .executeForString( + HttpMethod.DELETE, + CHANGE_SETS + "/" + scene.draft().getId() + "?hardDelete=" + hard, + null); + } + + private static String audit(final OpenMetadataClient caller, final String fqn) { + return get(caller, AUDIT + "&entityFQN=" + fqn); + } + + private static String get(final OpenMetadataClient caller, final String path) { + return caller.getHttpClient().executeForString(HttpMethod.GET, path, null); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadMcpIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadMcpIT.java new file mode 100644 index 000000000000..136c0319b40a --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadMcpIT.java @@ -0,0 +1,201 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.tests.mcp.McpTestBase; +import org.openmetadata.it.tests.mcp.McpTestUtils; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * get_entity_details reads a change set with the right that reads its draft, as REST does, in every + * call shape. A user with view rights on change sets and none on the ontology is refused, and the + * answer holds no table id, column or filter value of a binding operation. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetDraftReadMcpIT extends McpTestBase { + private static final String BEARER = "Bearer "; + private static final String COLUMN = "draft_read_column"; + private static final String VALUE = "draft_read_value"; + private static final String NOT_ALLOWED = "not allowed"; + + private record Scene(OntologyChangeSet draft, Table table, String editor, String viewer) { + String fqn() { + return draft.getFullyQualifiedName(); + } + + void assertRefused(final String call, final JsonNode answer) { + final String text = answer.toString(); + assertTrue(text.contains(NOT_ALLOWED), call + ": " + text); + assertFalse(text.contains(table.getId().toString()), call + ": " + text); + assertFalse(text.contains(COLUMN), call + ": " + text); + assertFalse(text.contains(VALUE), call + ": " + text); + } + + void assertAnswered(final String call, final JsonNode answer) { + final String text = answer.toString(); + assertFalse(text.contains(NOT_ALLOWED), call + ": " + text); + assertTrue(text.contains(table.getId().toString()), call + ": " + text); + } + } + + @Test + void aUserWhoMayOnlyViewChangeSetsIsRefusedInEveryCallShape(final TestNamespace ns) + throws Exception { + initAuth(); + try (var fixtures = new RdfAccessFixtures("mcpDraft" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("mcpDraftViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + + for (final var call : calls(scene).entrySet()) { + scene.assertRefused(call.getKey(), executeMcpRequest(call.getValue(), scene.viewer())); + } + } + } + + @Test + void theEditorAndAnAdminReadTheSameChangeSetInEveryCallShape(final TestNamespace ns) + throws Exception { + initAuth(); + try (var fixtures = new RdfAccessFixtures("mcpDraftEditor" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("mcpDraftEditorViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + + for (final var call : calls(scene).entrySet()) { + if (!call.getKey().startsWith("content")) { + scene.assertAnswered( + call.getKey() + " editor", executeMcpRequest(call.getValue(), scene.editor())); + scene.assertAnswered( + call.getKey() + " admin", executeMcpRequest(call.getValue(), authToken)); + } + } + } + } + + @Test + void aDeletedChangeSetIsRefusedOrMissingAndNeverReadByAViewer(final TestNamespace ns) + throws Exception { + initAuth(); + try (var fixtures = new RdfAccessFixtures("mcpDraftGone" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("mcpDraftGoneViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + final Map call = calls(scene).get("single"); + admin() + .getHttpClient() + .executeForString( + HttpMethod.DELETE, + CHANGE_SETS + "/" + scene.draft().getId() + "?hardDelete=false", + null); + + scene.assertRefused("soft deleted", executeMcpRequest(call, scene.viewer())); + + admin() + .getHttpClient() + .executeForString( + HttpMethod.DELETE, + CHANGE_SETS + "/" + scene.draft().getId() + "?hardDelete=true", + null); + final String gone = executeMcpRequest(call, scene.viewer()).toString(); + assertFalse(gone.contains(scene.table().getId().toString()), gone); + assertFalse(gone.contains(COLUMN), gone); + assertFalse(gone.contains(VALUE), gone); + } + } + + private static Map> calls(final Scene scene) { + return Map.of( + "single", + McpTestUtils.createGetEntityToolCall("ontologyChangeSet", scene.fqn()), + "batch", + McpTestUtils.createToolCallRequest( + "get_entity_details", Map.of("entities", List.of("ontologyChangeSet:" + scene.fqn()))), + "include", + McpTestUtils.createToolCallRequest( + "get_entity_details", + Map.of( + "entityType", + "ontologyChangeSet", + "fqn", + scene.fqn(), + "include", + List.of("lineage", "quality", "context", "content"))), + "content only", + McpTestUtils.createToolCallRequest( + "get_entity_details", + Map.of( + "entityType", + "ontologyChangeSet", + "fqn", + scene.fqn(), + "include", + List.of("content")))); + } + + private static Scene scene( + final TestNamespace ns, final RdfAccessFixtures fixtures, final RdfAccessFixtures viewers) { + final Ontology ontology = BaseOntologyApprovalIT.createOntology(ns); + BaseOntologyApprovalIT.declareClass(ontology, "Order", ORDER); + final String editor = + BEARER + + OntologyDraftFixtures.tokenWithout( + fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final var viewAll = viewers.allowRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_CHANGE_SET); + final var viewBasic = + viewers.allowRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CHANGE_SET); + final var noTables = viewers.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final String viewer = + BEARER + + viewers.userToken( + "viewer", List.of(viewAll.getId(), viewBasic.getId(), noTables.getId())); + final Table table = table(schema(ns), "hidden", column(COLUMN, ColumnDataType.VARCHAR)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(COLUMN))) + .withRowFilter(filter(COLUMN, OntologyRowFilterOperator.EQUALS, VALUE)))); + return new Scene(draft, table, editor, viewer); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetSaveSightIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetSaveSightIT.java new file mode 100644 index 000000000000..351d376a38ee --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetSaveSightIT.java @@ -0,0 +1,301 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.evidence; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.read; +import static org.openmetadata.it.tests.OntologyDraftFixtures.release; +import static org.openmetadata.it.tests.OntologyDraftFixtures.replaceOperations; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.service.Entity; + +/** + * A save stores the evidence its writer read, so a writer whose sight of a table changed after the + * read must read again. The client sends back the number of entries its read withheld, and a save is + * a 412 when the stored operation withholds a different number from that writer now. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetSaveSightIT extends BaseOntologyApprovalIT { + private static final int PRECONDITION_FAILED = 412; + private static final List> ID_COLUMN = List.of(List.of("id")); + + @Test + void aTableDeletedAtTheReadAndRestoredBeforeTheSaveRefusesTheSaveAndKeepsItsEvidence( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table table = table(schema(ns), "payments", column("id", ColumnDataType.BIGINT)); + final OntologyChangeOperation operation = + creates(proposedClass(ontology, "Customer", CUSTOMER)).withEvidence(List.of(about(table))); + final OntologyChangeSet draft = draft(admin(), ns, ontology, operation); + admin().tables().delete(table.getId()); + final OntologyChangeOperation seen = read(admin(), draft).getOperations().getFirst(); + assertEquals(1, seen.getWithheldEvidenceCount()); + admin().tables().restore(table.getId().toString()); + + final OpenMetadataException refusal = saveRefused(admin(), draft, seen); + + assertEquals(PRECONDITION_FAILED, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains("operation '" + operation.getId() + "'")); + assertTrue(refusal.getMessage().contains("Read the change set again")); + assertEquals( + List.of(about(table)), read(admin(), draft).getOperations().getFirst().getEvidence()); + final OntologyChangeOperation again = read(admin(), draft).getOperations().getFirst(); + assertEquals(0, again.getWithheldEvidenceCount()); + assertEquals(List.of(about(table)), save(admin(), draft, again).getEvidence()); + } + + @Test + void aPolicyThatHidesATableAfterTheReadRefusesTheSave(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("sightPolicy" + ns.shortPrefix())) { + final DatabaseSchema schema = schema(ns); + final var everything = fixtures.allowRole(MetadataOperation.ALL, "All"); + final var deny = + fixtures.denyRole( + MetadataOperation.VIEW_BASIC, Entity.TABLE, "matchAnyTag('PII.Sensitive')"); + final OpenMetadataClient writer = + OntologyBindingFixtures.client( + fixtures.userToken("writer", List.of(everything.getId(), deny.getId()))); + final Table first = table(schema, "first", column("id", ColumnDataType.BIGINT)); + final Table second = table(schema, "second", column("id", ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + writer, + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(List.of(about(first), about(second)))); + final OntologyChangeOperation seen = read(writer, draft).getOperations().getFirst(); + assertEquals(0, seen.getWithheldEvidenceCount()); + sensitive(second); + Awaitility.await("the policy hides the table from the writer") + .atMost(Duration.ofSeconds(30)) + .until(() -> hidesFrom(writer, second)); + + final OpenMetadataException refusal = saveRefused(writer, draft, seen); + + assertEquals(PRECONDITION_FAILED, refusal.getStatusCode()); + assertEquals( + List.of(about(first), about(second)), + read(admin(), draft).getOperations().getFirst().getEvidence()); + } + } + + @Test + void aSaveThatSendsBackTheCountItsReadWithheldIsAcceptedAndKeepsTheWithheldEntry( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("sightEqual" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OntologyChangeSet draft = bothTablesDraft(ns, ontology, scene); + final OntologyChangeOperation seen = read(scene.reader(), draft).getOperations().getFirst(); + assertEquals(1, seen.getWithheldEvidenceCount()); + + final OntologyChangeOperation saved = save(scene.reader(), draft, seen); + + assertEquals(1, saved.getWithheldEvidenceCount()); + assertEquals( + List.of(about(scene.shown()), about(scene.hidden())), + read(admin(), draft).getOperations().getFirst().getEvidence()); + } + } + + @Test + void aSaveThatSendsALargerOrASmallerCountThanTheOperationWithholdsIsRefused( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("sightCount" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OntologyChangeSet draft = bothTablesDraft(ns, ontology, scene); + final OntologyChangeOperation seen = read(scene.reader(), draft).getOperations().getFirst(); + + assertEquals( + PRECONDITION_FAILED, + saveRefused(scene.reader(), draft, seen.withWithheldEvidenceCount(2)).getStatusCode()); + assertEquals( + PRECONDITION_FAILED, + saveRefused(scene.reader(), draft, seen.withWithheldEvidenceCount(0)).getStatusCode()); + assertEquals( + List.of(about(scene.shown()), about(scene.hidden())), + read(admin(), draft).getOperations().getFirst().getEvidence()); + } + } + + @Test + void aCountSentWhenNothingIsWithheldIsAcceptedAtZeroAndRefusedAboveIt(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table table = table(schema(ns), "payments", column("id", ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(List.of(about(table)))); + final OntologyChangeOperation seen = read(admin(), draft).getOperations().getFirst(); + assertEquals(0, seen.getWithheldEvidenceCount()); + + assertEquals( + PRECONDITION_FAILED, + saveRefused(admin(), draft, seen.withWithheldEvidenceCount(3)).getStatusCode()); + assertEquals( + List.of(about(table)), + save(admin(), draft, seen.withWithheldEvidenceCount(0)).getEvidence()); + } + + @Test + void aSaveThatSendsNoCountIsNotChecked(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("sightNone" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OntologyChangeSet draft = bothTablesDraft(ns, ontology, scene); + final OntologyChangeOperation seen = read(scene.reader(), draft).getOperations().getFirst(); + + final OntologyChangeOperation saved = + save(scene.reader(), draft, seen.withWithheldEvidenceCount(null)); + + assertEquals(1, saved.getWithheldEvidenceCount()); + assertEquals( + List.of(about(scene.shown()), about(scene.hidden())), + read(admin(), draft).getOperations().getFirst().getEvidence()); + } + } + + @Test + void aCountOnAnOperationTheDraftDoesNotStoreYetIsNotChecked(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyChangeSet draft = + draft(admin(), ns, ontology, creates(proposedClass(ontology, "Customer", CUSTOMER))); + final OntologyChangeOperation added = + creates(proposedClass(ontology, "Order", OntologyMappingFixtures.ORDER)) + .withWithheldEvidenceCount(4); + final List operations = + new ArrayList<>(read(admin(), draft).getOperations()); + operations.add(added); + final OntologyEditLeaseToken lease = lease(admin(), draft); + + final OntologyChangeSet saved = replaceOperations(admin(), draft, lease, operations); + release(admin(), draft, lease); + + assertEquals(2, saved.getOperations().size()); + assertNull(read(admin(), draft).getOperations().getLast().getEvidence()); + } + + private static OntologyChangeOperation save( + final OpenMetadataClient writer, + final OntologyChangeSet draft, + final OntologyChangeOperation operation) { + final OntologyEditLeaseToken lease = lease(writer, draft); + try { + return replaceOperations(writer, draft, lease, List.of(operation)).getOperations().getFirst(); + } finally { + release(writer, draft, lease); + } + } + + private static OpenMetadataException saveRefused( + final OpenMetadataClient writer, + final OntologyChangeSet draft, + final OntologyChangeOperation operation) { + return assertThrows(OpenMetadataException.class, () -> save(writer, draft, operation)); + } + + private static OntologyChangeEvidence about(final Table table) { + return evidence(table, OntologyChangeEvidenceKind.NAME).withColumns(ID_COLUMN); + } + + private static void sensitive(final Table table) { + final Table stored = admin().tables().get(table.getId().toString(), "tags"); + stored.setTags( + new ArrayList<>( + List.of( + new TagLabel() + .withTagFQN("PII.Sensitive") + .withSource(TagLabel.TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL) + .withState(TagLabel.State.CONFIRMED)))); + admin().tables().update(table.getId(), stored); + } + + private static boolean hidesFrom(final OpenMetadataClient caller, final Table table) { + try { + caller.tables().get(table.getId().toString()); + return false; + } catch (OpenMetadataException refused) { + return true; + } + } + + private static OntologyChangeSet bothTablesDraft( + final TestNamespace ns, final Ontology ontology, final Scene scene) { + return draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(List.of(about(scene.shown()), about(scene.hidden())))); + } + + /** A writer who may view the tables it owns and no other, with one table of each kind. */ + private record Scene(OpenMetadataClient reader, Table shown, Table hidden) {} + + private static Scene scene(final TestNamespace ns, final RdfAccessFixtures fixtures) { + final DatabaseSchema schema = schema(ns); + final OpenMetadataClient reader = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final Table shown = + ownedTable( + schema, + "customers", + OntologyBindingFixtures.readerReference(reader), + column("id", ColumnDataType.BIGINT)); + return new Scene(reader, shown, table(schema, "payments", column("id", ColumnDataType.BIGINT))); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfOntologyChangeSetViewIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfOntologyChangeSetViewIT.java new file mode 100644 index 000000000000..c31c251c9e94 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfOntologyChangeSetViewIT.java @@ -0,0 +1,123 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.evidence; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * A change set is a draft, read with the draft read right and with its evidence masked per reader, + * so the knowledge graph holds none of it and its RDF view refuses every caller. + */ +@ExtendWith(TestNamespaceExtension.class) +class RdfOntologyChangeSetViewIT extends BaseOntologyApprovalIT { + private static final String COLUMN = "hidden_evidence_column"; + private static final String OPERATIONS = "https://open-metadata.org/ontology/operations"; + private static final int POLLS = 12; + private static final long POLL_MILLIS = 1500; + + @Test + void noCallerReadsAChangeSetAsRdfOrFindsItsOperationsInTheGraph(final TestNamespace ns) + throws InterruptedException { + final Ontology ontology = createOntology(ns); + try (var editor = new RdfAccessFixtures("rdfEditor" + ns.shortPrefix()); + var viewer = new RdfAccessFixtures("rdfViewer" + ns.shortPrefix())) { + final OpenMetadataClient reader = + callerWithout(editor, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final var deny = viewer.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OpenMetadataClient plain = + OntologyBindingFixtures.client(viewer.userToken("plain", List.of(deny.getId()))); + final Table hidden = table(schema(ns), "hidden", column(COLUMN, ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence( + List.of( + evidence(hidden, OntologyChangeEvidenceKind.NAME) + .withColumns(List.of(List.of(COLUMN)))))); + + for (final OpenMetadataClient caller : List.of(reader, plain, admin())) { + for (final String format : List.of("turtle", "jsonld", "ntriples", "rdfxml")) { + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + caller + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/rdf/entity/ontologyChangeSet/" + + draft.getId() + + "?format=" + + format, + null), + format); + assertEquals(403, refusal.getStatusCode(), format); + assertFalse(refusal.getMessage().contains(hidden.getId().toString()), format); + } + } + + viewer.markProjectionReady(); + final String query = + "SELECT ?o WHERE { <" + + OPERATIONS + + "> ?o }"; + for (int poll = 0; poll < POLLS; poll++) { + for (final OpenMetadataClient caller : List.of(plain, reader, admin())) { + final String body = + caller + .getHttpClient() + .executeForString( + HttpMethod.POST, "/v1/rdf/sparql/agent", Map.of("query", query)); + assertFalse(body.contains(hidden.getId().toString()), body); + assertFalse(body.contains(COLUMN), body); + } + Thread.sleep(POLL_MILLIS); + } + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java index ddbb17520503..3fad61781570 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java @@ -432,6 +432,10 @@ private void authorizeAuditLogAccess( ResourceContext serviceContext = new ResourceContext<>(serviceType, null, serviceName); OperationContext viewOp = new OperationContext(serviceType, MetadataOperation.VIEW_BASIC); authorizer.authorize(securityContext, viewOp, serviceContext); + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + // A change set has no service, so its events carry its own name as the service name. + authorizeChangeSetOperations(securityContext, serviceName); + } } else { // Global audit log access: requires AUDIT_LOGS permission (admin-only) OperationContext operationContext = From 778c507b8342262a9a18bac7c5dd6bbad886e9db Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 18:27:23 -0800 Subject: [PATCH 049/203] Correct the audit log paragraph of the change set record --- ...ntology-change-set-can-carry-table-bindings-and-shapes.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md index f254fa92383b..21c1c2ee2e8e 100644 --- a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md +++ b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md @@ -60,8 +60,9 @@ The paths that return the operations of a change set and the way each is covered targets. - The audit log, read for one change set: the same draft read right, asked after `ViewBasic`. A change set that is deleted is still checked, and one that cannot be loaded leaves only the - audit-log permission. The audit log of an entity type that has no service never answers a - service name for a change set, and the export of the audit log needs the audit-log permission. + audit-log permission. A request that names the change set type and a service name is checked the + same way, because the events of a change set carry its own name as their service name. The + export of the audit log needs the audit-log permission. - The MCP tool that reads an entity, in each call shape: the same draft read right, then the evidence masked per reader. - The RDF view and the knowledge graph: a change set is not in them. It is excluded from the From e2c94af34305b781b2ffe82a4e6ea524f360b0f0 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 19:04:40 -0800 Subject: [PATCH 050/203] Read the operations again before a save that follows a change of sight The save test that guessed evidence about a table its writer could not view sent an operation read before another writer stored entries. It now reads the operation again first, as the refusal of a stale save requires. --- .../openmetadata/it/tests/OntologyChangeSetEvidenceIT.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java index 2cc0890906ea..268268af7299 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java @@ -201,13 +201,15 @@ void aSaveStoresNoEvidenceAboutATableItsWriterMayNotView(final TestNamespace ns) final OntologyEditLeaseToken byAdmin = lease(admin(), created); replaceOperations(admin(), created, byAdmin, List.of(supported)); release(admin(), created, byAdmin); + final OntologyChangeOperation reread = read(writer, created).getOperations().getFirst(); + assertEquals(1, reread.getWithheldEvidenceCount()); final OntologyChangeOperation guessed = replaceOperations( writer, created, lease(writer, created), List.of( - answered.withEvidence( + reread.withEvidence( List.of( scene.aboutTheShownTable(), scene.aboutTheHiddenTable(), From 99b5fa7586447a947de0dd4d2dd713915a32a96f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 19:05:22 -0800 Subject: [PATCH 051/203] Refuse a reader without the right before saying a release is missing --- .../ontology/OntologyStatementService.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java index fe7e678ac8fd..8b1040e3fecc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java @@ -286,7 +286,7 @@ private Subject releaseSubject(final Access access, final UUID classId) { final OntologyConcept row = (OntologyConcept) catalog.working(access, Entity.ONTOLOGY_CONCEPT, classId); store.requireLiveOntology(row); - final OntologyVersion version = OntologyVersion.release(dao, row.getOntology()); + final OntologyVersion version = activeRelease(access, row); final OntologyConcept declared = (OntologyConcept) version.declared( @@ -302,6 +302,20 @@ private Subject releaseSubject(final Access access, final UUID classId) { return new Subject(declared, row.getOntology(), version); } + /** + * The active release of the ontology of {@code row}. An ontology with none is a 404 for a reader + * who may view the class, and the refusal of the right comes first for one who may not. + */ + private OntologyVersion activeRelease(final Access access, final OntologyConcept row) { + try { + return OntologyVersion.release(dao, row.getOntology()); + } catch (final EntityNotFoundException noRelease) { + catalog.authorizedWorking( + access, Entity.ONTOLOGY_CONCEPT, row.getId(), MetadataOperation.VIEW_BASIC); + throw noRelease; + } + } + private static MappedTable identity( final Subject subject, final Bindings bindings, final Tables tables) { return OntologyMappingReader.identity( From 3c297468dfce7389ef3470d391989a1407c1f430 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 20:23:56 -0800 Subject: [PATCH 052/203] Regenerate the UI's TypeScript types from the statement schemas --- .../data/ontologyAggregateStatementRequest.ts | 51 ++++ .../api/data/ontologyConceptQuery.ts | 13 +- .../data/ontologyExpandStatementRequest.ts | 51 ++++ .../api/data/ontologyFindStatementRequest.ts | 38 +++ .../api/data/ontologyOpenStatementRequest.ts | 31 +++ .../api/data/ontologyStatementPlan.ts | 223 ++++++++++++++++++ 6 files changed, 404 insertions(+), 3 deletions(-) create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyExpandStatementRequest.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyFindStatementRequest.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyOpenStatementRequest.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts new file mode 100644 index 000000000000..9667635434f2 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts @@ -0,0 +1,51 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Asks for a counting statement. Without a relation it counts the records of the class. + * With a relation and a direction it returns the 8 records of the class that relate to the + * most records along that relation, each with its count. + */ +export interface OntologyAggregateStatementRequest { + direction?: Direction; + /** + * Id of the class at the far end of the relation. Leave it out when the relation names one + * class on that side, its range for `forward` and its domain for `inverse`. + */ + relatedClass?: string; + /** + * Id of the object property to follow. + */ + relation?: string; + version?: Version; +} + +/** + * Which way a statement follows a relation. `forward` goes from a record of the class that + * binds the relation to the records it names. `inverse` goes from a named record back to + * the records that name it. + */ +export enum Direction { + Forward = "forward", + Inverse = "inverse", +} + +/** + * Which version of the ontology a statement reads. `release` is the active release. `draft` + * is the working draft, and reading it takes `EditAll` on the ontology. The class, its + * properties, the display name flag and the relations come from that version. Bindings sit + * outside versions and are always current. + */ +export enum Version { + Draft = "draft", + Release = "release", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyConceptQuery.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyConceptQuery.ts index 05b082ddd4d2..ed4bcdb20df5 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyConceptQuery.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyConceptQuery.ts @@ -18,6 +18,12 @@ */ export interface OntologyConceptQuery { dialect?: Dialect; + /** + * The same statement with every colon written as a backslash and a colon. It is the only + * form to run through a SQLAlchemy `text()` call, which reads `\:` as a colon and would + * read a bare colon as the start of a bind parameter. Set by the server. + */ + escapedSql?: string; /** * Search-around hops in order, at most five. */ @@ -31,9 +37,10 @@ export interface OntologyConceptQuery { */ serviceType?: string; /** - * Generated SELECT limited to 50 rows. It applies the row filter of each table it reads. - * Every colon is written as a backslash and a colon, so a consumer that reads `:name` as a - * bind parameter finds none. Set by the server. + * Generated SELECT limited to 50 rows, for a person to read. It starts from the only bound + * table of the concept, or from its identity table when the concept binds several tables, + * and applies the row filter of each table it reads. Every colon is written as a colon. Do + * not pass it to a library that reads `:name` as a bind parameter. Set by the server. */ sql?: string; /** diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyExpandStatementRequest.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyExpandStatementRequest.ts new file mode 100644 index 000000000000..6650caaf7e5a --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyExpandStatementRequest.ts @@ -0,0 +1,51 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Asks for the statement that lists the records one record relates to along one relation. + * The statement asks for 26 rows, and the 26th says only that more exist. + */ +export interface OntologyExpandStatementRequest { + direction: Direction; + key: any[]; + /** + * Id of the class at the far end of the relation. Leave it out when the relation names one + * class on that side, its range for `forward` and its domain for `inverse`. + */ + relatedClass?: string; + /** + * Id of the object property to follow. + */ + relation: string; + version?: Version; +} + +/** + * Which way a statement follows a relation. `forward` goes from a record of the class that + * binds the relation to the records it names. `inverse` goes from a named record back to + * the records that name it. + */ +export enum Direction { + Forward = "forward", + Inverse = "inverse", +} + +/** + * Which version of the ontology a statement reads. `release` is the active release. `draft` + * is the working draft, and reading it takes `EditAll` on the ontology. The class, its + * properties, the display name flag and the relations come from that version. Bindings sit + * outside versions and are always current. + */ +export enum Version { + Draft = "draft", + Release = "release", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyFindStatementRequest.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyFindStatementRequest.ts new file mode 100644 index 000000000000..afd5d315a9b7 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyFindStatementRequest.ts @@ -0,0 +1,38 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Asks for the statement that lists records of a class: the key, the display name and the + * bound columns of its identity table, at most 25 rows. + */ +export interface OntologyFindStatementRequest { + /** + * Text to look for in the display name. Empty text matches every record. Text with no + * uppercase letter matches without regard to case. Text with an uppercase letter is + * compared as the engine compares the column. It takes at most 256 characters and no + * control character. A class that binds no display name column on its identity table takes + * no match text. + */ + matchText?: string; + version?: Version; +} + +/** + * Which version of the ontology a statement reads. `release` is the active release. `draft` + * is the working draft, and reading it takes `EditAll` on the ontology. The class, its + * properties, the display name flag and the relations come from that version. Bindings sit + * outside versions and are always current. + */ +export enum Version { + Draft = "draft", + Release = "release", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyOpenStatementRequest.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyOpenStatementRequest.ts new file mode 100644 index 000000000000..ab44761dd772 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyOpenStatementRequest.ts @@ -0,0 +1,31 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Asks for the statement that reads one record: every bound column of its identity table + * and of the contributing tables the caller may view. + */ +export interface OntologyOpenStatementRequest { + key: any[]; + version?: Version; +} + +/** + * Which version of the ontology a statement reads. `release` is the active release. `draft` + * is the working draft, and reading it takes `EditAll` on the ontology. The class, its + * properties, the display name flag and the relations come from that version. Bindings sit + * outside versions and are always current. + */ +export enum Version { + Draft = "draft", + Release = "release", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts new file mode 100644 index 000000000000..acf83468dd49 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts @@ -0,0 +1,223 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * One generated SELECT about the records of a class, with a column plan that says what each + * result column holds. A record is a row of the identity table of its class, and its id is + * the class IRI with the values of the subject key of that table. OpenMetadata writes the + * statement and never runs it + * (ADR:2026-11-22-record-statements-start-from-the-identity-table). + */ +export interface OntologyStatementPlan { + /** + * The binding revision of every class whose bindings the statement read. A statement that + * follows a relation names both classes. + */ + bindingRevisions: BindingRevision[]; + /** + * The result columns in order. + */ + columns: Column[]; + dialect: Dialect; + /** + * The same statement with every colon written as a backslash and a colon. It is the only + * form to run through a SQLAlchemy `text()` call, which reads `\:` as a colon and would + * read a bare colon as the start of a bind parameter. + */ + escapedSql: string; + /** + * Whether the statement asks for one row more than `rowCap`. That row is not part of the + * answer. It says only that more rows exist. + */ + extraRow: boolean; + family: EngineFamily; + relation?: Relation; + /** + * The most rows a reader takes from the result. `find` and `expand` take 25, `open` takes + * 100, a relation count takes 8 and a class count takes 1. + */ + rowCap: number; + /** + * Name of the database service that holds the tables the statement reads. + */ + service: string; + /** + * Type of that database service. + */ + serviceType: string; + /** + * The statement for a person to read, with every colon written as a colon. It is a single + * SELECT in the dialect of the engine and carries its own `LIMIT` or `TOP`. Do not pass it + * to a library that reads `:name` as a bind parameter. + */ + sql: string; + statement: StatementKind; + /** + * Fully qualified names of the tables the statement reads, in join order. A table the + * caller may not view is never listed. + */ + tables: string[]; + version: VersionRead; +} + +/** + * The binding revision of one class whose bindings the statement was built from. + */ +export interface BindingRevision { + /** + * IRI of the class. + */ + classIri: string; + /** + * Id of the class. + */ + conceptId: string; + /** + * Revision of the bindings of the class, as the bindings endpoint returns it. + */ + revision: number; +} + +/** + * One result column of the statement. + */ +export interface Column { + /** + * IRI of the class whose record the column describes. A `count` column of a class count + * carries the counted class, and a `count` column of a relation carries the class of the + * records that were counted. + */ + classIri: string; + /** + * Position of the column in each result row, from zero. + */ + index: number; + /** + * For a `key` column, its position in the subject key of the class, from zero. + */ + keyPart?: number; + kind: ColumnKind; + /** + * For a `displayName` or `property` column, the IRI of the data property it holds. + */ + propertyIri?: string; +} + +/** + * What a result column holds. `key` is one part of a record key. `displayName` is the value + * of the display name property of the class. `property` is the value of one data property. + * `count` is a number of records. + */ +export enum ColumnKind { + Count = "count", + DisplayName = "displayName", + Key = "key", + Property = "property", +} + +/** + * Identifier quoting family of the bound table's service. + */ +export enum Dialect { + ANSI = "ansi", + Bigquery = "bigquery", + Mysql = "mysql", + Snowflake = "snowflake", + Spark = "spark", + Tsql = "tsql", +} + +/** + * The engines that read a name, a string and a `LIKE` pattern the same way. The family of + * the service writes every name and every value of the statement. + */ +export enum EngineFamily { + Bigquery = "bigquery", + Clickhouse = "clickhouse", + Mysql = "mysql", + Postgres = "postgres", + Redshift = "redshift", + Snowflake = "snowflake", + Spark = "spark", + Trino = "trino", + Tsql = "tsql", +} + +/** + * The relation a statement follows. + */ +export interface Relation { + direction: Direction; + /** + * IRI of the object property. + */ + propertyIri: string; + /** + * IRI of the class at the far end of the relation. + */ + relatedClassIri: string; +} + +/** + * Which way a statement follows a relation. `forward` goes from a record of the class that + * binds the relation to the records it names. `inverse` goes from a named record back to + * the records that name it. + */ +export enum Direction { + Forward = "forward", + Inverse = "inverse", +} + +/** + * What a statement asks. `find` lists records of a class. `expand` lists the records that + * one record relates to. `open` reads every bound column of one record. `aggregate` counts. + */ +export enum StatementKind { + Aggregate = "aggregate", + Expand = "expand", + Find = "find", + Open = "open", +} + +/** + * The version of the ontology that the statement was built from. + */ +export interface VersionRead { + kind: Version; + /** + * Id of the active release, when the statement read a release. + */ + releaseId?: string; + /** + * Release number of that release. + */ + releaseRevision?: number; + /** + * Semantic version of that release. Absent on a release that has none. + */ + semanticVersion?: string; + /** + * Working revision of the ontology, when the statement read the draft. + */ + workingRevision?: number; +} + +/** + * Which version of the ontology a statement reads. `release` is the active release. `draft` + * is the working draft, and reading it takes `EditAll` on the ontology. The class, its + * properties, the display name flag and the relations come from that version. Bindings sit + * outside versions and are always current. + */ +export enum Version { + Draft = "draft", + Release = "release", +} From 351d59ee6a18dbbd7b6a56ae4e590728bfa8d734 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 20:43:45 -0800 Subject: [PATCH 053/203] Ask the draft read right on every path to a change set, and keep its operations out of stored change events The history listing keeps only the snapshots of change sets the caller may read. Undo, redo, discard, replace, delete, restore and the lease endpoints ask the same right before they write or answer. The audit log limits the rows it returns through that right to the change set that holds the name now. The operations field is masked, so a stored change event holds no operations, and a masked field is dropped from the recorded field changes of an event. --- .../service/audit/AuditLogRepository.java | 66 +++++++++- .../service/events/ChangeEventMasking.java | 56 ++++++++- .../service/jdbi3/EntityRepository.java | 10 ++ .../jdbi3/OntologyChangeSetRepository.java | 9 ++ .../ontology/OntologyChangeSetReadAccess.java | 20 +++ .../resources/audit/AuditLogResource.java | 49 ++++++-- .../ontology/OntologyChangeSetResource.java | 27 ++++ .../ontology/OntologyEditLockResource.java | 22 ++++ .../events/ChangeEventMaskingTest.java | 92 ++++++++++++++ .../OntologyChangeEventPublisherTest.java | 31 +++++ .../OntologyChangeEvidenceViewTest.java | 11 +- .../OntologyChangeSetReadAccessTest.java | 115 ++++++++++++++++++ .../OntologyChangeSetEndpointRightsTest.java | 111 +++++++++++++++++ .../schema/entity/data/ontologyChangeSet.json | 4 +- 14 files changed, 598 insertions(+), 25 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyChangeSetEndpointRightsTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java index 54b82c0045c8..434ea7609ce5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java @@ -350,7 +350,8 @@ public int streamExportAsJson( eventType, startTs, endTs, - searchTerm), + searchTerm, + null), totalLimit, userName, actorType, @@ -396,7 +397,8 @@ public int streamExportAsJson( null, // before afterCursor, false, // skip the count — it would re-run once per batch - readsUserEmails); + readsUserEmails, + null); if (batch.getData().isEmpty()) { break; @@ -479,6 +481,43 @@ public ResultList list( String before, String after, boolean readsUserEmails) { + return list( + userName, + actorType, + serviceName, + entityType, + entityFqn, + eventType, + startTs, + endTs, + searchTerm, + limitParam, + before, + after, + readsUserEmails, + null); + } + + /** + * As above, limited to the rows of one entity when {@code entityId} is set. A name can be held by + * an entity that no longer exists and by another that took it, and the rows of the two are not + * the same reader's to see. + */ + public ResultList list( + String userName, + String actorType, + String serviceName, + String entityType, + String entityFqn, + String eventType, + Long startTs, + Long endTs, + String searchTerm, + int limitParam, + String before, + String after, + boolean readsUserEmails, + UUID entityId) { return list( userName, actorType, @@ -493,7 +532,8 @@ public ResultList list( before, after, true, - readsUserEmails); + readsUserEmails, + entityId); } private ResultList list( @@ -510,7 +550,8 @@ private ResultList list( String before, String after, boolean countTotal, - boolean readsUserEmails) { + boolean readsUserEmails, + UUID entityId) { RestUtil.validateCursors(before, after); int limit = Math.max(1, limitParam); @@ -529,7 +570,8 @@ private ResultList list( eventType, startTs, endTs, - searchTerm); + searchTerm, + entityId); List records; boolean isBackward = beforeCursor != null; @@ -887,7 +929,8 @@ private String buildBaseCondition( String eventType, Long startTs, Long endTs, - String searchTerm) { + String searchTerm, + UUID entityId) { StringBuilder condition = new StringBuilder("WHERE 1 = 1"); appendEq(condition, userName, "user_name", "userName"); appendEq(condition, actorType, "actor_type", "actorType"); @@ -896,6 +939,7 @@ private String buildBaseCondition( // entity_fqn has no index; its hash does, and the write path always populates both together. appendEq(condition, entityFqnHash, "entity_fqn_hash", "entityFQNHASH"); appendEq(condition, eventType, "event_type", "eventType"); + appendEntityId(condition, entityId); if (startTs != null) { condition.append(" AND event_ts >= :startTs"); } @@ -914,6 +958,16 @@ private String buildBaseCondition( return condition.toString(); } + /** + * The id is a {@link UUID}, so the literal holds only hex digits and dashes. The row filter binds + * no parameter because the listing and its count take a fixed set of them. + */ + private void appendEntityId(StringBuilder condition, UUID entityId) { + if (entityId != null) { + condition.append(" AND entity_id = '").append(entityId).append("'"); + } + } + private void appendEq(StringBuilder condition, String value, String column, String param) { if (!nullOrEmpty(value)) { condition.append(" AND ").append(column).append(" = :").append(param); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java index 6d7f22b8986a..7b6f60d944cb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java @@ -17,9 +17,12 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.io.UncheckedIOException; +import java.util.Iterator; +import java.util.List; import java.util.Optional; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -28,7 +31,8 @@ /** * What a change event is stored as. The entity it carries leaves out every field its schema marks * {@code "mask": true}, such as bot tokens, password hashes and connection secrets, whichever code - * made the event and whether it holds the entity as an object or as a string of JSON. Every alert, + * made the event and whether it holds the entity as an object or as a string of JSON. Its recorded + * field changes leave out the changes of a field that is masked as a whole. Every alert, * the audit log and {@code GET /v1/events} read the stored event. */ public final class ChangeEventMasking { @@ -36,6 +40,9 @@ public final class ChangeEventMasking { private static final JsonFactory JSON_FACTORY = new JsonFactory(); private static final String ENTITY = "entity"; private static final String ENTITY_TYPE = "entityType"; + private static final String CHANGE_DESCRIPTION = "changeDescription"; + private static final List FIELD_CHANGE_LISTS = + List.of("fieldsAdded", "fieldsUpdated", "fieldsDeleted"); private ChangeEventMasking() {} @@ -43,12 +50,18 @@ public static String masked(final String changeEventJson) { return entityTypeOf(changeEventJson) .map(Entity::getEntityClassFromType) .filter(MaskedFields::anyIn) - .map(entityClass -> withMaskedEntity(changeEventJson, entityClass)) + .map(entityClass -> withMaskedEvent(changeEventJson, entityClass)) .orElse(changeEventJson); } - private static String withMaskedEntity(final String changeEventJson, final Class entityClass) { + private static String withMaskedEvent(final String changeEventJson, final Class entityClass) { final ObjectNode event = (ObjectNode) JsonUtils.readTree(changeEventJson); + final boolean isEntityMasked = maskEntity(event, entityClass); + final boolean isChangeDropped = dropMaskedFieldChanges(event, entityClass); + return isEntityMasked || isChangeDropped ? JsonUtils.pojoToJson(event) : changeEventJson; + } + + private static boolean maskEntity(final ObjectNode event, final Class entityClass) { final JsonNode entity = event.path(ENTITY); final boolean isPresent = !entity.isMissingNode() && !entity.isNull(); if (isPresent) { @@ -58,7 +71,42 @@ private static String withMaskedEntity(final String changeEventJson, final Class : JsonUtils.convertValueLenient(entity, entityClass); event.put(ENTITY, JsonUtils.pojoToMaskedJson(typed)); } - return isPresent ? JsonUtils.pojoToJson(event) : changeEventJson; + return isPresent; + } + + /** + * A recorded field change holds the old and the new value of a field, so a change of a field + * that is masked as a whole is left out of the event. Nothing in the stored event then holds the + * field's values, and the entity's own endpoints still decide who reads them. + */ + private static boolean dropMaskedFieldChanges( + final ObjectNode event, final Class entityClass) { + final List masked = MaskedFields.wholeFieldsOf(entityClass); + final JsonNode description = event.path(CHANGE_DESCRIPTION); + boolean isDropped = false; + for (final String kind : FIELD_CHANGE_LISTS) { + if (!masked.isEmpty() && description.path(kind) instanceof ArrayNode changes) { + isDropped |= removeChangesOf(changes, masked); + } + } + return isDropped; + } + + private static boolean removeChangesOf(final ArrayNode changes, final List masked) { + final int before = changes.size(); + final Iterator each = changes.elements(); + while (each.hasNext()) { + if (isChangeOf(masked, each.next().path("name").asText())) { + each.remove(); + } + } + return changes.size() != before; + } + + // A change names a field or a path inside it, such as "authenticationMechanism.config". + private static boolean isChangeOf(final List maskedFields, final String changedField) { + return maskedFields.stream() + .anyMatch(field -> changedField.equals(field) || changedField.startsWith(field + ".")); } // entityType comes early in a stored event, so this reads a few tokens, not the whole event. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java index a63dc554624b..0805097d5faa 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java @@ -6989,6 +6989,15 @@ protected List getFieldsHiddenFromHistory() { return Collections.emptyList(); } + /** + * Fields its schema masks that its versions still hold. A mask keeps a field out of change + * events. A version is read through the entity's own endpoints, which decide who may read it, so + * an entity whose masked field is its content, such as the operations of a draft, keeps it there. + */ + protected List getMaskedFieldsShownInHistory() { + return Collections.emptyList(); + } + /** Stores each entity as the version it was before an update. The only writer of versions. */ protected final void storeVersions(final List originals) { storeVersions(versionRows(originals)); @@ -7038,6 +7047,7 @@ final String serializeForVersionHistory(final T entity) { */ private List fieldsHiddenFromHistory() { final List hidden = new ArrayList<>(MaskedFields.wholeFieldsOf(entityClass)); + hidden.removeAll(getMaskedFieldsShownInHistory()); hidden.addAll(getFieldsHiddenFromHistory()); return hidden; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java index 6032659a5256..7215891866b4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java @@ -89,6 +89,15 @@ protected void applyInheritance( } } + /** + * The schema masks {@code operations} so that no change event holds them. A version of the draft + * is its content, and the resource that serves it asks the draft read right. + */ + @Override + protected List getMaskedFieldsShownInHistory() { + return List.of(OPERATIONS_FIELD); + } + @Override public void setFields( final OntologyChangeSet entity, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java index de6c42a50a14..0643c2f29dc4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java @@ -16,11 +16,14 @@ import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import jakarta.ws.rs.core.SecurityContext; +import java.util.function.Supplier; import org.openmetadata.schema.entity.data.Glossary; import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.policyevaluator.CreateResourceContext; import org.openmetadata.service.security.policyevaluator.OperationContext; @@ -57,6 +60,23 @@ public static void requireRead( } } + /** + * Whether the caller may read the change set the loader returns. A refusal answers false, and so + * does a change set that cannot be loaded or whose scope no longer exists: nothing decides the + * right for it, so nothing is shown. + */ + public static boolean mayRead( + final Authorizer authorizer, + final SecurityContext securityContext, + final Supplier loader) { + try { + requireRead(authorizer, securityContext, loader.get()); + return true; + } catch (AuthorizationException | EntityNotFoundException unreadable) { + return false; + } + } + private static void requireGlossaryRead( final Authorizer authorizer, final SecurityContext securityContext, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java index 3fad61781570..f2f4f8163b3f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java @@ -45,6 +45,7 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.resources.Collection; +import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.DefaultAuthorizer; import org.openmetadata.service.security.policyevaluator.OperationContext; @@ -140,7 +141,7 @@ public ResultList listAuditLogs( String searchTerm) { // Authorization: service-level, entity-level, or global based on filters provided - authorizeAuditLogAccess(securityContext, serviceName, entityType, entityFqn); + UUID changeSetId = authorizeAuditLogAccess(securityContext, serviceName, entityType, entityFqn); return repository.list( userName, @@ -155,7 +156,8 @@ public ResultList listAuditLogs( limit, before, after, - readsUserEmails(securityContext)); + readsUserEmails(securityContext), + changeSetId); } private static boolean readsUserEmails(SecurityContext securityContext) { @@ -415,16 +417,22 @@ private static boolean isLegacySpoolJobId(String jobId) { *

  • If serviceName AND entityType are provided: Check VIEW_BASIC on the service *
  • Otherwise: Require global AUDIT_LOGS permission (admin-only) * + * + * @return the id of the change set whose rows the caller may read through the draft read right, + * or null when the audit-log permission or another entity's right decided the request. Only + * the rows of that change set may be returned, because the name can have been used by a + * change set that no longer exists. */ - private void authorizeAuditLogAccess( + private UUID authorizeAuditLogAccess( SecurityContext securityContext, String serviceName, String entityType, String entityFqn) { + UUID changeSetId = null; if (!nullOrEmpty(entityFqn) && !nullOrEmpty(entityType)) { // Entity-level authorization: user needs VIEW_BASIC on the specific entity ResourceContext entityContext = new ResourceContext<>(entityType, null, entityFqn); OperationContext viewOp = new OperationContext(entityType, MetadataOperation.VIEW_BASIC); authorizer.authorize(securityContext, viewOp, entityContext); if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { - authorizeChangeSetOperations(securityContext, entityFqn); + changeSetId = authorizeChangeSetOperations(securityContext, entityFqn); } } else if (!nullOrEmpty(serviceName) && !nullOrEmpty(entityType)) { // Service-level authorization: user needs VIEW_BASIC on the service @@ -434,7 +442,7 @@ private void authorizeAuditLogAccess( authorizer.authorize(securityContext, viewOp, serviceContext); if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { // A change set has no service, so its events carry its own name as the service name. - authorizeChangeSetOperations(securityContext, serviceName); + changeSetId = authorizeChangeSetOperations(securityContext, serviceName); } } else { // Global audit log access: requires AUDIT_LOGS permission (admin-only) @@ -442,14 +450,24 @@ private void authorizeAuditLogAccess( new OperationContext(Entity.AUDIT_LOG, MetadataOperation.AUDIT_LOGS); authorizer.authorize(securityContext, operationContext, AuditLogResourceContext.INSTANCE); } + return changeSetId; } /** * The events of a change set hold its operations, which a draft read returns only to the right - * that edits its scope. A change set that cannot be loaded, such as a deleted one, leaves only - * the audit-log permission. + * that edits its scope. Whoever holds the audit-log permission reads every event, so that + * permission decides first and the request is not narrowed. Otherwise the draft read right of + * the change set that holds the name now decides, and the audit-log permission alone decides when + * no change set can be loaded, such as a deleted one. + * + * @return the id of the change set the rows are limited to, which is set only when the draft + * read right decided. A name can have been held by a change set that no longer exists, and + * its rows are not the reader's to see. */ - private void authorizeChangeSetOperations(SecurityContext securityContext, String entityFqn) { + private UUID authorizeChangeSetOperations(SecurityContext securityContext, String entityFqn) { + if (holdsAuditLogPermission(securityContext)) { + return null; + } OntologyChangeSet changeSet = null; try { changeSet = @@ -466,9 +484,22 @@ private void authorizeChangeSetOperations(SecurityContext securityContext, Strin securityContext, new OperationContext(Entity.AUDIT_LOG, MetadataOperation.AUDIT_LOGS), AuditLogResourceContext.INSTANCE); - return; + return null; } OntologyChangeSetReadAccess.requireRead(authorizer, securityContext, changeSet); + return changeSet.getId(); + } + + private boolean holdsAuditLogPermission(SecurityContext securityContext) { + try { + authorizer.authorize( + securityContext, + new OperationContext(Entity.AUDIT_LOG, MetadataOperation.AUDIT_LOGS), + AuditLogResourceContext.INSTANCE); + return true; + } catch (AuthorizationException e) { + return false; + } } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java index 42df77391299..c6151a98eef5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java @@ -313,6 +313,26 @@ protected Optional> snapshotRedaction( return Optional.of(evidence(null, securityContext)); } + /** + * A snapshot is a version of a change set, so it is kept only when its change set may be read + * with the draft read right. The right is asked once for each change set in the page, and a + * refusal, or a change set that cannot be loaded, drops its snapshots and leaves the answer a 200. + */ + @Override + protected List retainReadableHistory( + final SecurityContext securityContext, final List snapshots) { + final Map readable = new LinkedHashMap<>(); + return snapshots.stream() + .filter( + snapshot -> + readable.computeIfAbsent( + snapshot.getId(), + id -> + OntologyChangeSetReadAccess.mayRead( + authorizer, securityContext, () -> readableChangeSet(id)))) + .toList(); + } + @POST @Path("/{id}/undo") @Operation(operationId = "undoOntologyChange", summary = "Move the draft cursor backward") @@ -423,6 +443,7 @@ public Response delete( @Context final SecurityContext securityContext, @PathParam("id") final UUID id, @QueryParam("hardDelete") @DefaultValue("false") final boolean hardDelete) { + authorizeScopeRead(securityContext, readableChangeSet(id)); return masked( evidence(uriInfo, securityContext), delete(uriInfo, securityContext, id, false, hardDelete)); @@ -435,6 +456,7 @@ public Response restore( @Context final UriInfo uriInfo, @Context final SecurityContext securityContext, @Valid final RestoreEntity restore) { + authorizeScopeRead(securityContext, readableChangeSet(restore.getId())); return masked( evidence(uriInfo, securityContext), restoreEntity(uriInfo, securityContext, restore.getId())); @@ -472,7 +494,12 @@ private static String requireStates(final String states) { } } + /** + * A command on a draft answers with its operations and may write them, so it asks the draft read + * right before the edit right on the change set, and before any write. + */ private void authorizeChangeSet(final SecurityContext securityContext, final UUID changeSetId) { + authorizeScopeRead(securityContext, readableChangeSet(changeSetId)); authorizer.authorize( securityContext, new OperationContext(entityType, MetadataOperation.EDIT_ALL), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyEditLockResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyEditLockResource.java index a4e735b089fc..d21afeee4a73 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyEditLockResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyEditLockResource.java @@ -32,10 +32,12 @@ import java.time.Clock; import java.util.UUID; import org.openmetadata.schema.api.data.AcquireOntologyEditLock; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyEditLock; import org.openmetadata.service.Entity; import org.openmetadata.service.limits.Limits; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.ontology.OntologyEditLeasePolicy; import org.openmetadata.service.ontology.OntologyEditLockService; import org.openmetadata.service.resources.Collection; @@ -105,12 +107,32 @@ public Response release( private void authorizeEdit( final SecurityContext securityContext, final String resourceType, final UUID resourceId) { + requireDraftRead(securityContext, resourceType, resourceId); final OperationContext operationContext = new OperationContext(resourceType, editOperation(resourceType)); authorizer.authorize( securityContext, operationContext, new ResourceContext<>(resourceType, resourceId, null)); } + /** + * A lease on a draft is held by someone who edits it, and its holder is named in the answer, so + * taking, renewing, reading or releasing one asks the draft read right first. Without it a user + * who may not read the draft could hold its lease and block the people who edit it. + */ + private void requireDraftRead( + final SecurityContext securityContext, final String resourceType, final UUID resourceId) { + if (Entity.ONTOLOGY_CHANGE_SET.equalsIgnoreCase(resourceType)) { + OntologyChangeSetReadAccess.requireRead( + authorizer, + securityContext, + Entity.getEntity( + Entity.ONTOLOGY_CHANGE_SET, + resourceId, + OntologyChangeSetReadAccess.SCOPE_FIELDS, + Include.ALL)); + } + } + static MetadataOperation editOperation(final String resourceType) { return MetadataOperation.EDIT_ALL; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java index 9a51113845e0..949973c98f24 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java @@ -27,14 +27,20 @@ import org.junit.jupiter.api.Test; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.auth.JWTAuthMechanism; +import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.entity.services.ingestionPipelines.IngestionPipeline; import org.openmetadata.schema.entity.teams.AuthenticationMechanism; import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.security.client.OpenMetadataJWTClientConfig; import org.openmetadata.schema.services.connections.metadata.OpenMetadataConnection; +import org.openmetadata.schema.type.ChangeDescription; import org.openmetadata.schema.type.ChangeEvent; import org.openmetadata.schema.type.EventType; +import org.openmetadata.schema.type.FieldChange; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -128,6 +134,92 @@ void anEventOfATypeWithNoMaskedFieldIsStoredAsItCame() { assertSame(event, ChangeEventMasking.masked(event)); } + @Test + void aChangeOfAMaskedFieldLeavesTheRecordedChanges() { + final ChangeDescription changes = + new ChangeDescription() + .withFieldsAdded(List.of(change("authenticationMechanism", null, "added-secret"))) + .withFieldsUpdated( + List.of( + change("authenticationMechanism", "old-secret", "new-secret"), + change("authenticationMechanism.config", "old-secret", "new-secret"), + change("displayName", "Old", "New"))) + .withFieldsDeleted(List.of(change("authenticationMechanism", "gone-secret", null))); + + final String stored = + ChangeEventMasking.masked( + JsonUtils.pojoToJson(userEvent(bot()).withChangeDescription(changes))); + + final JsonNode kept = JsonUtils.readTree(stored).path("changeDescription"); + assertEquals(0, kept.path("fieldsAdded").size()); + assertEquals(0, kept.path("fieldsDeleted").size()); + assertEquals(1, kept.path("fieldsUpdated").size()); + assertEquals("displayName", kept.path("fieldsUpdated").get(0).path("name").asText()); + assertEquals("New", kept.path("fieldsUpdated").get(0).path("newValue").asText()); + assertFalse(stored.contains("secret")); + } + + @Test + void aChangeOfAFieldThatOnlyHoldsASecretInsideItStaysInTheRecordedChanges() { + final ChangeDescription changes = + new ChangeDescription().withFieldsUpdated(List.of(change("description", "Old", "New"))); + + final String event = JsonUtils.pojoToJson(userEvent(bot()).withChangeDescription(changes)); + + assertEquals( + List.of("description"), + JsonUtils.readTree(ChangeEventMasking.masked(event)) + .path("changeDescription") + .path("fieldsUpdated") + .findValuesAsText("name")); + } + + @Test + void aDraftsOperationsLeaveItsEntityAndItsRecordedChanges() { + EntityInterface.ENTITY_TYPE_TO_CLASS_MAP.putIfAbsent( + Entity.ONTOLOGY_CHANGE_SET.toLowerCase(Locale.ROOT), OntologyChangeSet.class); + final UUID tableId = UUID.randomUUID(); + final OntologyChangeOperation operation = + new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding(new OntologyBindingChange().withTableId(tableId)); + final ChangeDescription changes = + new ChangeDescription() + .withFieldsUpdated( + List.of( + change("operations", "[]", JsonUtils.pojoToJson(List.of(operation))), + change("undoCursor", "0", "1"))); + final ChangeEvent event = + new ChangeEvent() + .withId(UUID.randomUUID()) + .withEventType(EventType.ENTITY_UPDATED) + .withEntityType(Entity.ONTOLOGY_CHANGE_SET) + .withChangeDescription(changes) + .withEntity( + new OntologyChangeSet() + .withId(UUID.randomUUID()) + .withName("draft") + .withUndoCursor(1) + .withOperations(List.of(operation))); + + final String stored = ChangeEventMasking.masked(JsonUtils.pojoToJson(event)); + + assertFalse(stored.contains(tableId.toString())); + final JsonNode entity = storedEntity(stored); + assertFalse(entity.has("operations")); + assertEquals("draft", entity.path("name").asText()); + assertEquals(1, entity.path("undoCursor").asInt()); + final JsonNode updated = + JsonUtils.readTree(stored).path("changeDescription").path("fieldsUpdated"); + assertEquals(List.of("undoCursor"), updated.findValuesAsText("name")); + } + + private static FieldChange change( + final String name, final Object oldValue, final Object newValue) { + return new FieldChange().withName(name).withOldValue(oldValue).withNewValue(newValue); + } + private static ChangeEvent userEvent(final Object entity) { return new ChangeEvent() .withId(UUID.randomUUID()) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEventPublisherTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEventPublisherTest.java index 8342983ed552..db1f07bccab0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEventPublisherTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEventPublisherTest.java @@ -14,6 +14,7 @@ package org.openmetadata.service.ontology; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.time.Clock; import java.time.Instant; @@ -23,8 +24,11 @@ import java.util.UUID; import org.junit.jupiter.api.Test; import org.openmetadata.schema.entity.data.Glossary; +import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.type.ChangeEvent; import org.openmetadata.schema.type.EventType; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.utils.JsonUtils; class OntologyChangeEventPublisherTest { @@ -50,4 +54,31 @@ void publishesTypedOntologyEventsWithEntityContext() { assertEquals("steward", event.getUserName()); assertEquals(1234, event.getTimestamp()); } + + @Test + void anAppliedChangeSetEventHoldsNoOperations() { + final List storedEvents = new ArrayList<>(); + final UUID tableId = UUID.randomUUID(); + final OntologyChangeSet changeSet = + new OntologyChangeSet() + .withId(UUID.randomUUID()) + .withName("draft") + .withFullyQualifiedName("draft") + .withVersion(0.2) + .withOperations( + List.of( + new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withBinding(new OntologyBindingChange().withTableId(tableId)))); + + new OntologyChangeEventPublisher(storedEvents::add, Clock.systemUTC()) + .publish(EventType.ONTOLOGY_CHANGE_SET_APPLIED, changeSet, "steward"); + + final ChangeEvent event = JsonUtils.readValue(storedEvents.getFirst(), ChangeEvent.class); + assertEquals(EventType.ONTOLOGY_CHANGE_SET_APPLIED, event.getEventType()); + assertEquals("ontologyChangeSet", event.getEntityType()); + assertFalse(storedEvents.getFirst().contains(tableId.toString())); + assertFalse(storedEvents.getFirst().contains("operations")); + assertEquals("draft", JsonUtils.readTree(storedEvents.getFirst()).at("/entity/name").asText()); + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java index 355cbb165e57..d88eb8c6358e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java @@ -109,17 +109,18 @@ void aRecordedChangeHoldsTheOperationsWithNoEvidence() { } @Test - void aStoredChangeEventLeavesOutTheEvidenceOfEveryOperation() { + void aMaskedCopyOfADraftLeavesOutEveryOperationAndSoItsEvidence() { final OntologyChangeSet changeSet = changeSet( - operation(OPERATION_ID, name(SHOWN), profile(HIDDEN)).withWithheldEvidenceCount(1)); + operation(OPERATION_ID, name(SHOWN), profile(HIDDEN)).withWithheldEvidenceCount(1)) + .withName("draft"); final JsonNode stored = JsonUtils.readTree(JsonUtils.pojoToMaskedJson(changeSet)); assertTrue(MaskedFields.anyIn(OntologyChangeSet.class)); - assertEquals(OPERATION_ID.toString(), stored.at("/operations/0/id").asText()); - assertTrue(stored.at("/operations/0/evidence").isMissingNode()); - assertTrue(stored.at("/operations/0/withheldEvidenceCount").isMissingNode()); + assertEquals(List.of("operations"), MaskedFields.wholeFieldsOf(OntologyChangeSet.class)); + assertTrue(stored.path("operations").isMissingNode()); + assertEquals("draft", stored.path("name").asText()); } @Test diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java new file mode 100644 index 000000000000..139a2e41df6d --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java @@ -0,0 +1,115 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.ws.rs.core.SecurityContext; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; +import org.mockito.Mockito; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; + +class OntologyChangeSetReadAccessTest { + private static final SecurityContext CALLER = Mockito.mock(SecurityContext.class); + + @Test + void aCallerWhoMayEditTheOntologyMayReadItsDraft() { + try (MockedConstruction ignored = + Mockito.mockConstruction(ResourceContext.class)) { + assertTrue( + OntologyChangeSetReadAccess.mayRead( + grantingOnly(Entity.ONTOLOGY), CALLER, OntologyChangeSetReadAccessTest::draft)); + } + } + + @Test + void aCallerRefusedTheOntologyMayNotReadItsDraft() { + try (MockedConstruction ignored = + Mockito.mockConstruction(ResourceContext.class)) { + assertFalse( + OntologyChangeSetReadAccess.mayRead( + grantingOnly(Entity.GLOSSARY), CALLER, OntologyChangeSetReadAccessTest::draft)); + } + } + + @Test + void aDraftThatCannotBeLoadedIsNotShown() { + assertFalse( + OntologyChangeSetReadAccess.mayRead( + grantingOnly(Entity.ONTOLOGY), + CALLER, + () -> { + throw new EntityNotFoundException("gone"); + })); + } + + @Test + void aScopeThatNoLongerExistsIsNotShown() { + final Authorizer missingScope = Mockito.mock(Authorizer.class); + Mockito.doThrow(new EntityNotFoundException("ontology gone")) + .when(missingScope) + .authorize( + Mockito.any(SecurityContext.class), + Mockito.any(OperationContext.class), + Mockito.any(ResourceContextInterface.class)); + + try (MockedConstruction ignored = + Mockito.mockConstruction(ResourceContext.class)) { + assertFalse( + OntologyChangeSetReadAccess.mayRead( + missingScope, CALLER, OntologyChangeSetReadAccessTest::draft)); + } + } + + private static OntologyChangeSet draft() { + return new OntologyChangeSet() + .withId(UUID.randomUUID()) + .withOntology(new EntityReference().withId(UUID.randomUUID()).withType(Entity.ONTOLOGY)) + .withOperations(List.of()); + } + + private static Authorizer grantingOnly(final String resource) { + final Authorizer authorizer = Mockito.mock(Authorizer.class); + Mockito.doAnswer( + call -> { + final OperationContext operation = call.getArgument(1); + final boolean granted = + resource.equals(operation.getResource()) + && operation.getOperations(null).equals(List.of(MetadataOperation.EDIT_ALL)); + if (!granted) { + throw new AuthorizationException("denied"); + } + return null; + }) + .when(authorizer) + .authorize( + Mockito.any(SecurityContext.class), + Mockito.any(OperationContext.class), + Mockito.any(ResourceContextInterface.class)); + return authorizer; + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyChangeSetEndpointRightsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyChangeSetEndpointRightsTest.java new file mode 100644 index 000000000000..e778f87de51e --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyChangeSetEndpointRightsTest.java @@ -0,0 +1,111 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.resources.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.TreeMap; +import org.junit.jupiter.api.Test; + +/** + * Every endpoint of the change set resource, its own and the ones it inherits, states the right it + * asks. A new endpoint fails this test until its row is added below, so whoever adds it decides + * whether it may return operations and which right a caller needs first. + */ +class OntologyChangeSetEndpointRightsTest { + private static final String DRAFT_READ = "draft read right"; + private static final String BASE = "/v1/ontologyChangeSets"; + + /** The right each endpoint asks before it writes anything or answers, as HTTP method and path. */ + private static final Map RIGHT_OF = + Map.ofEntries( + Map.entry("GET " + BASE, DRAFT_READ + " for every row"), + Map.entry("POST " + BASE, "EditAll on the scope, then the right of each definition"), + Map.entry("GET " + BASE + "/{id}", DRAFT_READ), + Map.entry("GET " + BASE + "/{id}/versions", DRAFT_READ), + Map.entry("GET " + BASE + "/{id}/versions/{version}", DRAFT_READ), + Map.entry("GET " + BASE + "/history", DRAFT_READ + " for each change set, else dropped"), + Map.entry("PUT " + BASE + "/{id}/operations", DRAFT_READ + ", then EditAll, then lease"), + Map.entry("POST " + BASE + "/{id}/undo", DRAFT_READ + ", then EditAll, then lease"), + Map.entry("POST " + BASE + "/{id}/redo", DRAFT_READ + ", then EditAll, then lease"), + Map.entry("POST " + BASE + "/{id}/discard", DRAFT_READ + ", then EditAll, then lease"), + Map.entry("POST " + BASE + "/{id}/submit", "EditAll on the scope, then lease"), + Map.entry("POST " + BASE + "/{id}/apply", "EditAll on the scope, then lease"), + Map.entry("DELETE " + BASE + "/{id}", DRAFT_READ + ", then Delete"), + Map.entry("PUT " + BASE + "/restore", DRAFT_READ + ", then EditAll"), + Map.entry("GET " + BASE + "/{id}/context", "ViewAll, and the answer holds no operations"), + Map.entry( + "GET " + BASE + "/name/{fqn}/context", + "ViewAll, and the answer holds no operations")); + + @Test + void everyEndpointOfTheResourceStatesItsRight() { + assertEquals(RIGHT_OF.keySet(), endpointsOf(OntologyChangeSetResource.class).keySet()); + } + + @Test + void everyRowNamesARight() { + RIGHT_OF.forEach((endpoint, right) -> assertFalse(right.isBlank(), endpoint)); + } + + @Test + void theResourceExposesNoEndpointTwice() { + final Map counts = new TreeMap<>(); + for (final Method method : OntologyChangeSetResource.class.getMethods()) { + final String endpoint = endpointOf(method); + if (endpoint != null) { + counts.merge(endpoint, 1, Integer::sum); + } + } + + counts.forEach((endpoint, count) -> assertEquals(1, count, endpoint)); + } + + private static Map endpointsOf(final Class resource) { + final Map endpoints = new TreeMap<>(); + for (final Method method : resource.getMethods()) { + final String endpoint = endpointOf(method); + if (endpoint != null) { + endpoints.put(endpoint, method); + } + } + return endpoints; + } + + private static String endpointOf(final Method method) { + final String verb = verbOf(method); + final Path own = method.getAnnotation(Path.class); + final Path base = OntologyChangeSetResource.class.getAnnotation(Path.class); + return verb == null ? null : verb + " " + base.value() + (own == null ? "" : own.value()); + } + + private static String verbOf(final Method method) { + String verb = null; + verb = method.isAnnotationPresent(GET.class) ? "GET" : verb; + verb = method.isAnnotationPresent(POST.class) ? "POST" : verb; + verb = method.isAnnotationPresent(PUT.class) ? "PUT" : verb; + verb = method.isAnnotationPresent(DELETE.class) ? "DELETE" : verb; + verb = method.isAnnotationPresent(PATCH.class) ? "PATCH" : verb; + return verb; + } +} diff --git a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyChangeSet.json b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyChangeSet.json index d9ed082b38fa..b1a65603add7 100644 --- a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyChangeSet.json +++ b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyChangeSet.json @@ -47,11 +47,13 @@ "$ref": "#/definitions/state" }, "operations": { + "description": "The operations of the draft. Reads that ask the draft read right return them. A stored change event never holds them, because an event reaches every subscriber and the server cannot know who may read the draft.", "type": "array", "items": { "$ref": "../../type/ontologyChangeOperation.json" }, - "default": [] + "default": [], + "mask": true }, "undoCursor": { "description": "Number of active operations at the current undo/redo position.", From e6548f3f289c5839d122a52641c2afd16d80e384 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 20:47:08 -0800 Subject: [PATCH 054/203] Count a class's records and a relation's links from stored column profiles when they are exact --- .../2026-11-22-a-count-is-exact-or-absent.md | 97 +++ .../tests/NativeOntologyDataGraphCountIT.java | 408 +++++++++++ .../jdbi3/OntologyConceptBindingDAO.java | 20 + .../jdbi3/OntologyConceptBindingStore.java | 13 + .../NativeOntologyDataGraphPager.java | 4 + .../NativeOntologyDataGraphService.java | 48 +- .../ontology/OntologyBindingAccess.java | 37 +- .../service/ontology/OntologyCountReader.java | 243 +++++++ .../service/ontology/OntologyCountRules.java | 437 ++++++++++++ .../ontology/OntologyRelationPath.java | 59 +- .../resources/ontology/OntologyResource.java | 3 +- .../ontology/OntologyCountRulesTest.java | 657 ++++++++++++++++++ .../api/data/nativeOntologyAssetCluster.json | 4 + .../schema/api/data/nativeOntologyCount.json | 36 + .../api/data/nativeOntologyDataGraph.json | 4 + 15 files changed, 2047 insertions(+), 23 deletions(-) create mode 100644 docs/decisions/2026-11-22-a-count-is-exact-or-absent.md create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java create mode 100644 openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyCount.json diff --git a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md new file mode 100644 index 000000000000..7c419a27ab08 --- /dev/null +++ b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md @@ -0,0 +1,97 @@ +# A record or link count comes from the stored profiles when they are exact, and is absent when they are not + +- **Status:** Accepted +- **Revisions:** v1 2026-11-22 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyCountRulesTest`, `NativeOntologyDataGraphCountIT` +- **Related:** ADR:2026-11-21-graph-table-assets-carry-latest-profile-facts (the profile facts this record does not reuse), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, subject key and joins that a count reads), ADR:2026-11-22-record-statements-start-from-the-identity-table (the identity table and the join that a count follows) + +## Context + +The graph of an ontology draws a class for each bound concept and an edge for each relation. A +reader wants to know how many records a class has and how many links a relation has. A number that +is wrong is worse than no number, so the number must come from stored facts that settle it, and +nothing may be sent to the database that a bound table lives in. + +A table profile has a `rowCount`, but it is not always counted. Where an engine's catalog holds a +row count, the profiler stores that figure and runs no `COUNT(*)`. On Postgres it is `reltuples` +and on MySQL `TABLE_ROWS`, and both are estimates. The column metrics `valuesCount`, `nullCount` +and `distinctCount` are different: the profiler counts them with a query over the rows it read. +Those rows are the whole table, a sample, a partition window or the result of a custom query. + +## Decision + +**`rowCount` is never used.** Every count comes from the metrics of columns. + +**The response carries a count or the reason for none.** `NativeOntologyCount` has a `state`, and +`value` and `profiledAt` exactly when the state is `exact`. A cluster has `records` and an edge has +`links`. + +| State | Meaning | +|---|---| +| `exact` | the stored profiles give the number | +| `noIdentityTable` | the class binds tables and none is its identity table | +| `identityTableHidden` | the identity table is deleted, or the reader may not view it; one state answers both, so it says no more than a statement about the class does | +| `noProfile` | the reader may not view the data profile of the table, or the table has no stored profile; the two are not told apart | +| `joinNotConfirmed` | the relation has a join onto the identity table of the related class and it is only inferred; this wins over `noJoin` | +| `noJoin` | the relation has no join onto it | +| `notDerivable` | any other rule below fails: the stored profiles cannot give the exact number and a query over the table could | + +A class that binds no table has no `records`. An edge whose first class the page does not hold has +no `links`. A name, id or column path of a hidden table is never in a count. + +**A column's metrics covered the whole table** when the latest table profile and the latest column +profile have one timestamp, and the table profile records no sample, a `PERCENTAGE` of 100 or more, +or a `ROWS` cap that the column's `valuesCount` plus `nullCount` stays below, and the table has no +`tablePartition`, and its profiler configuration names no `profileQuery` and enables no +partitioning. + +**A declared key counts only on an engine that checks it.** Postgres, Timescale, Cockroach, +Greenplum, MySQL, MariaDB, SingleStore, SQL Server, Azure SQL, Oracle, Db2 and SQLite check a +declared primary or unique key. Snowflake, BigQuery, Redshift, Databricks, Unity Catalog, Synapse +and Fabric store one and do not, so a duplicate row would make a count wrong with nothing to say +so. The list is in `OntologyCountRules`. + +**A key is unique** when its column is alone in the key, its metrics covered the whole table, and +`distinctCount` equals `valuesCount`; when those metrics exist the catalog is not asked, and a +difference means not unique. Otherwise it is unique when the catalog declares a primary or unique +table constraint whose columns are all in the key, or a primary or unique column constraint on one +of them, on an engine that checks it. **A key column has no nulls** by the same order: its metrics +when they covered the table (`nullCount` of 0), otherwise a `NOT_NULL` column constraint, or a +primary key on an engine that checks it. + +**Records of a class** need an identity binding with no row filter on a table the reader may view +and may view the data profile of. A key of one column counts `distinctCount` of that column when +its metrics covered the table. A key of several columns needs the key to be unique, every key +column's metrics to have covered the table and at most one key column to hold nulls. The count is +`valuesCount` of that column, or of any key column when none holds nulls. + +**Links of a relation** need the join that `OntologyRelationPath.lookup` finds for the relation +onto the identity table of the related class, confirmed and held by the identity binding of the +first class. A join held by a contributing table gives no count. The join's parent columns are the +related class's subject key in order. Neither identity binding has a row filter. The key of the +first class is unique and holds no nulls. The metrics of every child column covered the whole table +and at most one holds nulls. The count is `valuesCount` of that child column, or of any child +column when none holds nulls. It counts non-null references, so a reference that matches no row of +the related table still counts. The reader needs the data profile right on the first class's table +and the right to view the related class's table. + +**The counts are read again for each response, with one read for each kind.** One statement reads +the binding rows of all classes of the response, with the identity row of each class first. The +identity tables come from one batch read with their columns, constraints, partition and profiler +configuration. One statement reads their latest table profiles, and one reads the latest column +profiles of their key columns and join columns. A page of 60 classes and 500 edges runs those four +reads and no query for a class or an edge. Nothing is stored and nothing is cached. The counts are +not part of `contextDigest`, so a count changing between two pages never refuses a cursor. + +## Consequences + +A client shows a number only when the state is `exact`, and shows what is missing otherwise. + +A profile taken by a workflow that runs outside the platform can use a partition or a query that +neither the table nor the profile records. A count from such a profile covers that window. This is +a known limit of reading stored profiles. + +A class with a row filter, a sampled or partitioned table, or a key that no metric or enforced +constraint proves unique has no count here. A query over the table is the way to count it, and that +is not part of this record. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java new file mode 100644 index 000000000000..117a95ab9a8f --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java @@ -0,0 +1,408 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.clusterPage; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.graphPage; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertionRequest; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.graph; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.util.Comparator; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateTableProfile; +import org.openmetadata.schema.api.data.NativeOntologyAssetCluster; +import org.openmetadata.schema.api.data.NativeOntologyClusterAsset; +import org.openmetadata.schema.api.data.NativeOntologyConceptEdge; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.api.data.NativeOntologyCount.State; +import org.openmetadata.schema.api.data.NativeOntologyDataGraph; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.Paging; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * The records of each class and the links of each relation on {@code GET /dataGraph} and on {@code + * POST /dataGraph/pages}, read from the stored profiles of identity tables. Every case compares + * the whole graph, with each entity reference cut down to the id, type and name that identify it. + */ +@ExtendWith(TestNamespaceExtension.class) +class NativeOntologyDataGraphCountIT extends BaseOntologyApprovalIT { + private static final long PROFILED_AT = 1_700_000_000_000L; + private static final double MISLEADING_ROW_COUNT = 999d; + + @Test + void anUnfilteredClassAndItsConfirmedRelationCountFromTheStoredProfiles(final TestNamespace ns) { + final World world = world(ns, OntologyJoinStatus.CONFIRMED, false, false); + + final var expected = world.expected(exact(100), exact(50), exact(90), true, true); + assertAllEndpoints(admin(), world, expected); + } + + @Test + void aFilteredClassAndTheRelationFromItCountNothing(final TestNamespace ns) { + final World world = world(ns, OntologyJoinStatus.CONFIRMED, true, false); + + final var expected = + world.expected( + state(State.NOT_DERIVABLE), exact(50), state(State.NOT_DERIVABLE), true, true); + assertAllEndpoints(admin(), world, expected); + } + + @Test + void aRelationHeldByALinkTableCountsNothingAndItsClassStillCountsItsRecords( + final TestNamespace ns) { + final World world = world(ns, OntologyJoinStatus.CONFIRMED, false, true); + + final var expected = + world.expectedWithLinkTable(exact(100), exact(50), state(State.NOT_DERIVABLE)); + assertAllEndpoints(admin(), world, expected); + } + + @Test + void aJoinThatIsOnlyInferredIsNotConfirmed(final TestNamespace ns) { + final World world = world(ns, OntologyJoinStatus.INFERRED, false, false); + + final var expected = + world.expected(exact(100), exact(50), state(State.JOIN_NOT_CONFIRMED), true, true); + assertAllEndpoints(admin(), world, expected); + } + + @Test + void aReaderWithoutTheDataProfileRightSeesNoProfileInsteadOfACount(final TestNamespace ns) { + final World world = world(ns, OntologyJoinStatus.CONFIRMED, false, false); + try (var fixtures = new RdfAccessFixtures("countDenied" + ns.shortPrefix())) { + final var denied = fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE); + final OpenMetadataClient reader = + client(fixtures.userToken("noProfile", List.of(denied.getId()))); + + final var expected = + world.expected( + state(State.NO_PROFILE), + state(State.NO_PROFILE), + state(State.NO_PROFILE), + false, + false); + assertAllEndpoints(reader, world, expected); + } + } + + @Test + void aReaderWhoMayNotViewTheIdentityTableSeesItHiddenAndLearnsNothingMore( + final TestNamespace ns) { + final World world = world(ns, OntologyJoinStatus.CONFIRMED, false, false); + final Table notes = + table(world.schema(), ns.prefix("order_notes"), column("order_id", ColumnDataType.BIGINT)); + put(admin(), world.order(), binding(notes, OntologyBindingRole.CONTRIBUTING, "order_id"), 1L); + try (var fixtures = new RdfAccessFixtures("countHidden" + ns.shortPrefix())) { + final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); + final EntityReference owner = readerReference(reader); + own(world.customers(), owner); + own(notes, owner); + + final var expected = + world.expectedHidden(notes, state(State.IDENTITY_TABLE_HIDDEN), exact(50)); + assertAllEndpoints(reader, world, expected); + } + } + + private static void assertAllEndpoints( + final OpenMetadataClient caller, final World world, final NativeOntologyDataGraph expected) { + final NativeOntologyDataGraph graph = graph(caller, world.ontology(), "?limit=12"); + assertEquals(expected, slim(graph)); + final var page = graphPage(caller, world.ontology(), List.of(), clusterPage(0, 12)); + assertEquals(expected.getClusters(), slim(page.getClusters())); + assertEquals(expected.getEdges(), slimEdges(page.getTopology().getEdges())); + assertEquals(List.of(), page.getTopology().getLineageEdges()); + assertNull(page.getBindings()); + } + + private static NativeOntologyCount exact(final long value) { + return new NativeOntologyCount() + .withState(State.EXACT) + .withValue(value) + .withProfiledAt(PROFILED_AT); + } + + private static NativeOntologyCount state(final State state) { + return new NativeOntologyCount().withState(state); + } + + /** Customers and orders, with a profile for each that covered the whole table. */ + private static World world( + final TestNamespace ns, + final OntologyJoinStatus status, + final boolean filteredOrders, + final boolean joinOnLinkTable) { + final Ontology ontology = createOntology(ns, "counts"); + final OntologyConcept order = declareClass(ontology, "Order", OntologyBindingFixtures.ORDER); + final OntologyConcept customer = + declareClass(ontology, "Customer", OntologyBindingFixtures.CUSTOMER); + final OntologyProperty placedBy = objectProperty(ontology, "placedBy", order, customer); + admin() + .ontologyAxioms() + .create( + assertionRequest( + ontology, + OntologyBindingFixtures.ORDER, + OntologyBindingFixtures.CUSTOMER, + "placedByAxiom") + .withPropertyIri(placedBy.getIri())); + final DatabaseSchema schema = OntologyMappingFixtures.schema(ns); + final Table customers = + table(schema, ns.prefix("customers"), column("id", ColumnDataType.BIGINT)); + final Table orders = + table( + schema, + ns.prefix("orders"), + column("id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT), + column("status", ColumnDataType.VARCHAR)); + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "id"), 0L); + final var joined = + column(placedBy, "customer_id").withJoin(join(customers, status, "customer_id", "id")); + var orderBinding = + binding(orders, OntologyBindingRole.IDENTITY, "id") + .withColumns(joinOnLinkTable ? List.of() : List.of(joined)); + if (filteredOrders) { + orderBinding = + orderBinding.withRowFilter( + filter("status", OntologyRowFilterOperator.NOT_EQUALS, "DELETED")); + } + put(admin(), order, orderBinding, 0L); + Table items = null; + if (joinOnLinkTable) { + items = + table( + schema, + ns.prefix("order_items"), + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + put( + admin(), + order, + binding(items, OntologyBindingRole.CONTRIBUTING, "order_id").withColumns(List.of(joined)), + 1L); + } + profile(customers, columnProfile("id", 50, 0, 50)); + profile( + orders, + columnProfile("id", 100, 0, 100), + columnProfile("customer_id", 90, 10, 40), + columnProfile("status", 100, 0, 3)); + return new World(ontology, order, customer, placedBy, schema, customers, orders, items); + } + + private static ColumnProfile columnProfile( + final String name, final double values, final double nulls, final double distinct) { + return new ColumnProfile() + .withName(name) + .withTimestamp(PROFILED_AT) + .withValuesCount(values) + .withNullCount(nulls) + .withDistinctCount(distinct); + } + + private static void profile(final Table table, final ColumnProfile... columns) { + admin() + .getHttpClient() + .execute( + HttpMethod.PUT, + "/v1/tables/" + table.getId() + "/tableProfile", + new CreateTableProfile() + .withTableProfile( + new TableProfile() + .withTimestamp(PROFILED_AT) + .withRowCount(MISLEADING_ROW_COUNT)) + .withColumnProfile(List.of(columns)), + Table.class); + } + + private static void own(final Table table, final EntityReference owner) { + final var current = admin().tables().get(table.getId().toString()); + admin().tables().update(table.getId().toString(), current.withOwners(List.of(owner))); + } + + private static EntityReference slim(final EntityReference reference) { + return reference == null + ? null + : new EntityReference() + .withId(reference.getId()) + .withType(reference.getType()) + .withFullyQualifiedName(reference.getFullyQualifiedName()); + } + + private static NativeOntologyDataGraph slim(final NativeOntologyDataGraph graph) { + return graph.withClusters(slim(graph.getClusters())).withEdges(slimEdges(graph.getEdges())); + } + + private static List slim( + final List clusters) { + clusters.forEach( + cluster -> { + cluster.withConcept(slim(cluster.getConcept())); + cluster.getAssets().forEach(asset -> asset.withAsset(slim(asset.getAsset()))); + }); + return clusters.stream() + .sorted(Comparator.comparing(cluster -> cluster.getConcept().getFullyQualifiedName())) + .toList(); + } + + private static List slimEdges( + final List edges) { + edges.forEach(edge -> edge.withProperty(slim(edge.getProperty()))); + return edges; + } + + /** What the tests built: an order class over orders, a customer class over customers. */ + private record World( + Ontology ontology, + OntologyConcept order, + OntologyConcept customer, + OntologyProperty placedBy, + DatabaseSchema schema, + Table customers, + Table orders, + Table items) { + NativeOntologyDataGraph expected( + final NativeOntologyCount orderRecords, + final NativeOntologyCount customerRecords, + final NativeOntologyCount links, + final boolean orderFacts, + final boolean customerFacts) { + return graph( + List.of( + cluster(customer, asset(customers, 0, customerFacts), customerRecords), + cluster(order, asset(orders, 1, orderFacts), orderRecords)), + links); + } + + NativeOntologyDataGraph expectedWithLinkTable( + final NativeOntologyCount orderRecords, + final NativeOntologyCount customerRecords, + final NativeOntologyCount links) { + final var orderCluster = + cluster(order, asset(orders, 0, true), orderRecords) + .withAssetCount(2) + .withAssets( + Stream.of(asset(orders, 0, true), asset(items, 1, false)) + .sorted( + Comparator.comparing( + (NativeOntologyClusterAsset one) -> + one.getAsset().getId().toString())) + .toList()); + return graph( + List.of(cluster(customer, asset(customers, 0, true), customerRecords), orderCluster), + links); + } + + NativeOntologyDataGraph expectedHidden( + final Table notes, + final NativeOntologyCount orderRecords, + final NativeOntologyCount customerRecords) { + final var noFacts = + new NativeOntologyClusterAsset().withAsset(slim(notes.getEntityReference())); + return graph( + List.of( + cluster(customer, asset(customers, 0, true), customerRecords), + cluster( + order, + noFacts.withServiceType(serviceType(notes)).withColumnCount(0), + orderRecords)), + orderRecords); + } + + private NativeOntologyDataGraph graph( + final List clusters, final NativeOntologyCount links) { + return new NativeOntologyDataGraph() + .withClusters( + clusters.stream() + .sorted(Comparator.comparing(item -> item.getConcept().getFullyQualifiedName())) + .toList()) + .withEdges( + List.of( + new NativeOntologyConceptEdge() + .withFromConceptId(order.getId()) + .withToConceptId(customer.getId()) + .withPropertyIri(placedBy.getIri()) + .withLabel("placedBy") + .withProperty(slim(placedBy.getEntityReference())) + .withLinks(links))) + .withLineageEdges(List.of()) + .withPaging(new Paging().withOffset(0).withLimit(12).withTotal(clusters.size())); + } + + private static NativeOntologyAssetCluster cluster( + final OntologyConcept concept, + final NativeOntologyClusterAsset asset, + final NativeOntologyCount records) { + return new NativeOntologyAssetCluster() + .withConcept(slim(concept.getEntityReference())) + .withAssetCount(1) + .withAssets(List.of(asset)) + .withRecords(records); + } + + private static NativeOntologyClusterAsset asset( + final Table table, final int columns, final boolean facts) { + final var asset = + new NativeOntologyClusterAsset() + .withAsset(slim(table.getEntityReference())) + .withServiceType(serviceType(table)) + .withColumnCount(columns); + return facts + ? asset + .withRowCount((long) MISLEADING_ROW_COUNT) + .withProfiledAt(PROFILED_AT) + .withSampled(false) + : asset; + } + + private static String serviceType(final Table table) { + return admin().tables().get(table.getId().toString()).getServiceType().value(); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java index 9694366f0367..ecab302873b5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java @@ -201,6 +201,26 @@ List listForConceptsAfter( List listFirstTablesForConcepts( @BindList("conceptIds") List conceptIds, @Bind("perConcept") int perConcept); + /** + * For each concept, its identity table row first and then its other table rows in asset id + * order, up to {@code perConcept} rows, in one statement. + */ + @SqlQuery( + "SELECT " + + COLUMNS + + " FROM (SELECT " + + COLUMNS + + ", ROW_NUMBER() OVER (PARTITION BY conceptId ORDER BY " + + "CASE WHEN bindingRole = '" + + IDENTITY_ROLE + + "' THEN 0 ELSE 1 END ASC, assetId ASC) AS bindingOrder " + + "FROM ontology_concept_binding WHERE conceptId IN () " + + "AND assetType = 'table') ranked " + + "WHERE bindingOrder <= :perConcept ORDER BY conceptId ASC, assetId ASC") + @RegisterRowMapper(BindingRowMapper.class) + List listIdentityFirstTablesForConcepts( + @BindList("conceptIds") List conceptIds, @Bind("perConcept") int perConcept); + /** The identity table rows of these concepts. A concept holds at most one live identity table. */ @SqlQuery( "SELECT " diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 989c8262f454..3f928b42148c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -238,6 +238,19 @@ public List firstTables(final Collection conceptIds, final int conceptIds.stream().map(UUID::toString).toList(), perConcept); } + /** + * The identity table row of each concept, when it has one, then its other table rows in asset id + * order, up to {@code perConcept} rows in all. One statement for all the concepts. + */ + public List identityFirstTables( + final Collection conceptIds, final int perConcept) { + return conceptIds.isEmpty() + ? List.of() + : dao.ontologyConceptBindingDAO() + .listIdentityFirstTablesForConcepts( + conceptIds.stream().map(UUID::toString).distinct().toList(), perConcept); + } + public List boundConcepts( final UUID ontologyId, final int limit, final int offset) { return dao.ontologyConceptBindingDAO().listBoundConcepts(ontologyId, limit, offset); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java index 80e91ce42fe4..cd2581c0364f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java @@ -80,6 +80,10 @@ public NativeOntologyDataGraphPage page( .withLoaded(scope.loaded()) .withContextFull(scope.loaded().size() >= MAX_CONCEPTS) .withTopology(topology(scope, concepts, cursor)); + graph.addCounts( + scope.access(), + response.getClusters() == null ? List.of() : response.getClusters(), + response.getTopology().getEdges()); requireRevisions(scope.loaded()); return response; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java index 1336107c55ea..b6f67fdf5398 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java @@ -28,6 +28,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.Consumer; +import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.codec.digest.DigestUtils; import org.openmetadata.schema.api.data.NativeOntologyAssetCluster; @@ -51,6 +52,7 @@ import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingPosition; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.ConceptAssetCount; @@ -90,18 +92,26 @@ public interface ReferenceLookup { private final OntologyConceptRepository concepts; private final ViewPermissionFilter visibility; private final ReferenceLookup references; + private final OntologyCountReader counts; public NativeOntologyDataGraphService( final CollectionDAO dao, final OntologyConceptBindingStore store, final OntologyConceptRepository concepts, final Authorizer authorizer, - final ReferenceLookup references) { + final ReferenceLookup references, + final Function> repositories) { this.dao = dao; this.store = store; this.concepts = concepts; this.visibility = new ViewPermissionFilter(authorizer); this.references = references; + this.counts = + new OntologyCountReader( + dao, + store, + new OntologyBindingAccess(authorizer, repositories), + (access, refs, operation) -> viewableIds(access, refs, operation)); } /** The caller's right to view the ontology itself is checked by the resource. */ @@ -113,9 +123,12 @@ public NativeOntologyDataGraph graph( store.boundConcepts(ontologyId, query.limit(), query.offset()), query.assetsPerConcept()); addProfileFacts(access, clusters); + final var responses = clusters.stream().map(Cluster::response).toList(); + final var edges = edges(access, ontologyId, clusters, query.edgeLimit()); + addCounts(access, responses, edges); return new NativeOntologyDataGraph() - .withClusters(clusters.stream().map(Cluster::response).toList()) - .withEdges(edges(access, ontologyId, clusters, query.edgeLimit())) + .withClusters(responses) + .withEdges(edges) .withLineageEdges(lineage(clusters, query.lineageEdgeLimit())) .withPaging( new Paging() @@ -170,6 +183,35 @@ void addProfileFacts(final Access access, final List clusters) { .toList()); } + /** + * Gives each cluster the records of its class and each edge the links of its relation, as the + * stored profiles of identity tables state them. The edges' classes are read whether or not they + * have a cluster in this response. All of it is read once for the response, whatever its size. + */ + void addCounts( + final Access access, + final List clusters, + final List edges) { + final var relations = edges.stream().map(NativeOntologyDataGraphService::relation).toList(); + final var read = + counts.read( + access, + clusters.stream().map(cluster -> cluster.getConcept().getId()).toList(), + relations); + clusters.forEach( + cluster -> cluster.withRecords(read.records().get(cluster.getConcept().getId()))); + for (int index = 0; index < edges.size(); index++) { + edges.get(index).withLinks(read.links().get(relations.get(index))); + } + } + + private static OntologyCountRules.Relation relation(final NativeOntologyConceptEdge edge) { + return new OntologyCountRules.Relation( + edge.getFromConceptId(), + edge.getToConceptId(), + edge.getProperty() == null ? null : edge.getProperty().getId()); + } + /** The same facts, under the same rules, for the tables of one page of a concept's bindings. */ void addProfileFacts(final Access access, final OntologyConceptBindingsResponse page) { fillProfileFacts( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java index 5392e2c8d6e2..8c6176fd9e45 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java @@ -6,11 +6,13 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.function.Function; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.service.Entity; @@ -30,6 +32,8 @@ */ @Slf4j final class OntologyBindingAccess { + private static final Set TABLE_COUNT_FIELDS = + Set.of("tableConstraints", "tablePartition", "tableProfilerConfig"); private final Authorizer authorizer; private final Function> repositories; @@ -93,10 +97,30 @@ void require( Map> viewable( final Access access, final String type, final Collection ids) { final Map> viewable = new HashMap<>(); - loadViewable(access, repositories.apply(type), ids.stream().distinct().toList(), viewable); + final EntityRepository repository = repositories.apply(type); + loadViewable( + access, repository, ids.stream().distinct().toList(), viewable, fields(repository)); return viewable; } + /** + * The live tables that the caller may view, by id, read in one statement with the columns, the + * declared constraints, the partition and the profiler configuration that a count reads. + */ + Map viewableTables(final Access access, final Collection ids) { + final EntityRepository repository = repositories.apply(Entity.TABLE); + final Map> viewable = new HashMap<>(); + loadViewable( + access, + repository, + ids.stream().distinct().toList(), + viewable, + fields(repository, TABLE_COUNT_FIELDS)); + final Map tables = new HashMap<>(); + viewable.forEach((id, table) -> tables.put(id, (Table) table)); + return tables; + } + /** The released definitions of one type that the caller may view, by id. */ Map> viewable( final Access access, final String type, final List released) { @@ -144,12 +168,12 @@ private > void loadViewable( final Access access, final EntityRepository repository, final List ids, - final Map> viewable) { + final Map> viewable, + final Fields fields) { if (ids.isEmpty()) { return; } - final List entities = - repository.get(access.uriInfo(), ids, fields(repository), Include.NON_DELETED); + final List entities = repository.get(access.uriInfo(), ids, fields, Include.NON_DELETED); final var tags = BulkFieldHydrator.forTags(repository, entities); for (final T entity : entities) { try { @@ -194,8 +218,13 @@ private > void require( } private static Fields fields(final EntityRepository repository) { + return fields(repository, Set.of()); + } + + private static Fields fields(final EntityRepository repository, final Set extra) { final var fieldNames = new HashSet<>(ResourceContext.authorizationFields(repository).getFieldList()); + fieldNames.addAll(extra); if (Entity.TABLE.equals(repository.getEntityType())) { fieldNames.add(Entity.FIELD_COLUMNS); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java new file mode 100644 index 000000000000..b24ce75fdca9 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java @@ -0,0 +1,243 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.BinaryOperator; +import java.util.function.ToLongFunction; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.EntityProfile; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.jdbi3.TimeSeriesDAOs.ProfilerDataTimeSeriesDAO; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyCountRules.ClassRows; +import org.openmetadata.service.ontology.OntologyCountRules.Facts; +import org.openmetadata.service.ontology.OntologyCountRules.Relation; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * Reads what {@link OntologyCountRules} needs for the classes and relations of one response, and + * applies the rules. Each kind is read once for the whole response, whatever the number of classes + * and relations: the binding rows of all classes in one statement, their identity tables in one + * batch read, and the latest table profiles and the latest column profiles in one statement each. + * Nothing is stored and nothing is sent to the database that a table is bound to. + */ +final class OntologyCountReader { + /** The ids, among {@code references}, that the caller may perform {@code operation} on. */ + @FunctionalInterface + interface Visibility { + Set viewable( + Access access, List references, MetadataOperation operation); + } + + /** The counts of one response. */ + record Counts(Map records, Map links) { + static final Counts NONE = new Counts(Map.of(), Map.of()); + } + + private final CollectionDAO dao; + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess catalog; + private final Visibility visibility; + + OntologyCountReader( + final CollectionDAO dao, + final OntologyConceptBindingStore store, + final OntologyBindingAccess catalog, + final Visibility visibility) { + this.dao = dao; + this.store = store; + this.catalog = catalog; + this.visibility = visibility; + } + + /** + * @param classes the classes whose records are asked for + * @param relations the relations whose links are asked for; their classes are read too + */ + Counts read(final Access access, final Collection classes, final List relations) { + final Set all = new LinkedHashSet<>(classes); + relations.forEach( + relation -> { + all.add(relation.subject()); + all.add(relation.object()); + }); + if (all.isEmpty()) { + return Counts.NONE; + } + final Map rows = classRows(all); + final Facts facts = facts(access, rows.values()); + final Map records = new LinkedHashMap<>(); + for (final UUID id : classes) { + final var count = OntologyCountRules.records(rows.get(id), facts); + if (count != null) { + records.put(id, count); + } + } + final Map links = new LinkedHashMap<>(); + for (final Relation relation : relations) { + final var count = OntologyCountRules.links(relation, rows, facts); + if (count != null) { + links.put(relation, count); + } + } + return new Counts(records, links); + } + + private Map classRows(final Collection ids) { + final Map> byClass = new HashMap<>(); + store + .identityFirstTables(ids, OntologyCountRules.ROWS_PER_CLASS) + .forEach(row -> byClass.computeIfAbsent(row.conceptId(), id -> new ArrayList<>()).add(row)); + final Map rows = new LinkedHashMap<>(); + for (final UUID id : ids) { + final List own = byClass.getOrDefault(id, List.of()); + final List ordered = + Stream.concat( + own.stream().filter(row -> row.role() == OntologyBindingRole.IDENTITY), + own.stream().filter(row -> row.role() != OntologyBindingRole.IDENTITY)) + .toList(); + rows.put(id, new ClassRows(id, ordered, own.size() >= OntologyCountRules.ROWS_PER_CLASS)); + } + return rows; + } + + private Facts facts(final Access access, final Collection classes) { + final List identities = + classes.stream().map(ClassRows::identity).filter(Objects::nonNull).toList(); + final Map tables = + catalog.viewableTables(access, identities.stream().map(BindingRow::assetId).toList()); + final Set permitted = + tables.isEmpty() + ? Set.of() + : visibility.viewable( + access, + tables.values().stream().map(Table::getEntityReference).toList(), + MetadataOperation.VIEW_DATA_PROFILE); + final List profiled = + identities.stream() + .filter(row -> tables.containsKey(row.assetId()) && permitted.contains(row.assetId())) + .toList(); + return new Facts( + tables, permitted, tableProfiles(profiled, tables), columnProfiles(profiled, tables)); + } + + private Map tableProfiles( + final List profiled, final Map tables) { + final Map byFqn = + latest( + profiled.stream() + .map(row -> tables.get(row.assetId()).getFullyQualifiedName()) + .toList(), + ProfilerDataTimeSeriesDAO.TABLE_PROFILE_EXTENSION, + TableProfile.class, + TableProfile::getTimestamp, + OntologyCountReader::sampledOverWhole); + final Map byId = new HashMap<>(); + for (final BindingRow row : profiled) { + final var profile = byFqn.get(tables.get(row.assetId()).getFullyQualifiedName()); + if (profile != null) { + byId.put(row.assetId(), profile); + } + } + return byId; + } + + /** The profile of the column paths that a class's counts can read, by column name. */ + private Map columnProfiles( + final List profiled, final Map tables) { + final List fqns = new ArrayList<>(); + for (final BindingRow row : profiled) { + final Table table = tables.get(row.assetId()); + for (final List path : OntologyCountRules.profiledPaths(row)) { + final var column = OntologyBindingRules.resolveColumn(table, path); + if (column != null && column.getFullyQualifiedName() != null) { + fqns.add(column.getFullyQualifiedName()); + } + } + } + return latest( + fqns.stream().distinct().toList(), + ProfilerDataTimeSeriesDAO.TABLE_COLUMN_PROFILE_EXTENSION, + ColumnProfile.class, + ColumnProfile::getTimestamp, + (first, second) -> first); + } + + /** + * The newest stored profile of each entity, by fully qualified name, from one statement. Two + * profiles with one timestamp are told apart by {@code tie}. + */ + private Map latest( + final List fqns, + final String extension, + final Class type, + final ToLongFunction timestamp, + final BinaryOperator tie) { + if (fqns.isEmpty()) { + return Map.of(); + } + final Map byHash = + fqns.stream() + .distinct() + .collect(Collectors.toMap(FullyQualifiedName::buildHash, fqn -> fqn, (a, b) -> a)); + final Map latest = new HashMap<>(); + for (final var record : + dao.profilerDataTimeSeriesDao().getLatestExtensionsBatch(fqns, extension)) { + final var entity = JsonUtils.readValue(record.json(), EntityProfile.class); + final String fqn = byHash.get(record.entityFQNHash()); + if (entity == null || entity.getProfileData() == null || fqn == null) { + continue; + } + final T profile = JsonUtils.convertValue(entity.getProfileData(), type); + latest.merge( + fqn, + profile, + (first, second) -> + timestamp.applyAsLong(first) == timestamp.applyAsLong(second) + ? tie.apply(first, second) + : timestamp.applyAsLong(first) > timestamp.applyAsLong(second) ? first : second); + } + return latest; + } + + /** + * Two table profiles with one timestamp can come from different operations. The one that + * records a sample is kept, so a doubt never makes a sampled profile look whole. + */ + private static TableProfile sampledOverWhole( + final TableProfile first, final TableProfile second) { + return first.getProfileSample() != null || second.getProfileSample() == null ? first : second; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java new file mode 100644 index 000000000000..f751543f961a --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java @@ -0,0 +1,437 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.api.data.NativeOntologyCount.State; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyRelationPath.Lookup; + +/** + * When the stored profiles of a table give the exact number of a class's records or of a + * relation's links, and when they do not. A count is exact or it is absent. A profile's table row + * count is never read, because the profiler may take it from the engine's catalog, where it can be + * an estimate (ADR:2026-11-22-a-count-is-exact-or-absent). The column metrics {@code valuesCount}, + * {@code nullCount} and {@code distinctCount} are counted over the rows the profiler read, which + * can be the whole table, a sample, a partition window or the result of a query. + * + *

    Nothing here reads a database or a policy. Callers pass what they read. + */ +final class OntologyCountRules { + /** + * The identity row first, then the other table rows of a class, at most {@value #ROWS_PER_CLASS} + * in all. The identity row alone makes the first read, so a class that binds more tables than + * this is read as far as it goes and is flagged {@link ClassRows#truncated()}. + */ + static final int ROWS_PER_CLASS = OntologyMappingReader.MAX_CONTRIBUTING_TABLES + 2; + + /** + * The engines that check a declared primary or unique key, so a duplicate row cannot exist + * beside one. Snowflake, BigQuery, Redshift, Databricks, Unity Catalog, Synapse and Fabric store + * a declared key and never check it, so a table there can hold a duplicate that its declared key + * says is impossible, and no count may rest on the declaration. + */ + private static final Set ENGINES_THAT_ENFORCE_KEYS = + Set.of( + "Postgres", + "Timescale", + "Cockroach", + "Greenplum", + "Mysql", + "MariaDB", + "SingleStore", + "Mssql", + "AzureSQL", + "Oracle", + "Db2", + "SQLite"); + + private static final double WHOLE_PERCENTAGE = 100d; + + private OntologyCountRules() {} + + /** + * The table bindings of one class, as {@link + * org.openmetadata.service.jdbi3.OntologyConceptBindingStore#identityFirstTables} reads them. + * + * @param rows the identity row first when the class has one, then other table rows, hidden and + * deleted tables included + * @param truncated true when the read stopped at its cap, so the class may bind more tables + */ + record ClassRows(UUID id, List rows, boolean truncated) { + BindingRow identity() { + return rows.stream().filter(OntologyCountRules::isIdentity).findFirst().orElse(null); + } + + /** The identity row, then the contributing rows: the rows that can hold a join. */ + List holders() { + return rows.stream() + .filter(row -> isIdentity(row) || row.role() == OntologyBindingRole.CONTRIBUTING) + .toList(); + } + } + + /** A relation between two classes of a page, from the class that binds it to the one it reaches. */ + record Relation(UUID subject, UUID object, UUID propertyId) {} + + /** + * What the catalog and the profiler store, for the tables the caller may view. + * + * @param tables the live tables the caller may view, by id + * @param profileViewable the ids of the tables whose data profile the caller may view + * @param tableProfiles the latest stored profile of a table, by table id + * @param columnProfiles the latest stored profile of a column, by the column's fully qualified + * name + */ + record Facts( + Map tables, + Set profileViewable, + Map tableProfiles, + Map columnProfiles) {} + + /** The records of a class, or null when the class binds no table. */ + static NativeOntologyCount records(final ClassRows binding, final Facts facts) { + if (binding.rows().isEmpty()) { + return null; + } + final Source source = source(binding, facts); + if (source.refusal() != null) { + return source.refusal(); + } + return source.row().rowFilter() == null && !nullOrEmpty(source.row().subjectKey()) + ? recordCount(source) + : notDerivable(); + } + + /** + * The links of a relation, or null when the class that binds it binds no table or is not in + * {@code classes}. + */ + static NativeOntologyCount links( + final Relation relation, final Map classes, final Facts facts) { + final ClassRows subject = classes.get(relation.subject()); + if (subject == null || subject.rows().isEmpty()) { + return null; + } + final Source source = source(subject, facts); + if (source.refusal() != null) { + return source.refusal(); + } + final ClassRows object = classes.get(relation.object()); + final BindingRow target = object == null ? null : object.identity(); + if (object == null || relation.propertyId() == null) { + return notDerivable(); + } + if (target == null) { + return state(State.NO_JOIN); + } + if (!facts.tables().containsKey(target.assetId())) { + return state(State.IDENTITY_TABLE_HIDDEN); + } + return switch (OntologyRelationPath.lookup( + relation.propertyId(), subject.holders(), target.assetId())) { + case Lookup.Missing ignored -> subject.truncated() ? notDerivable() : state(State.NO_JOIN); + case Lookup.Unconfirmed ignored -> subject.truncated() + ? notDerivable() + : state(State.JOIN_NOT_CONFIRMED); + case Lookup.Confirmed found -> linkCount(source, target, found.stored()); + }; + } + + /** The column paths whose profiles a class's counts can read: its key and the children of joins. */ + static List> profiledPaths(final BindingRow identity) { + final List> paths = new ArrayList<>(listOrEmpty(identity.subjectKey())); + for (final OntologyColumnBinding column : listOrEmpty(identity.columns())) { + if (column.getJoin() != null) { + column.getJoin().getOn().stream().map(OntologyJoinColumnPair::getChild).forEach(paths::add); + } + } + return paths; + } + + private static NativeOntologyCount recordCount(final Source source) { + final List> key = source.row().subjectKey(); + if (key.size() == 1) { + final Metrics metrics = source.metrics(key.getFirst()); + return metrics == null ? notDerivable() : exact(metrics.distinct(), source); + } + final List metrics = new ArrayList<>(); + for (final List path : key) { + metrics.add(source.metrics(path)); + } + return source.isUnique(key) && metrics.stream().allMatch(Metrics::isComplete) + ? valueOfAtMostOneNullable(metrics, source) + : notDerivable(); + } + + /** The values of the one column that holds nulls, or of any column when none does. */ + private static NativeOntologyCount valueOfAtMostOneNullable( + final List metrics, final Source source) { + final List nullable = metrics.stream().filter(Metrics::hasNulls).toList(); + if (nullable.size() > 1) { + return notDerivable(); + } + return exact((nullable.isEmpty() ? metrics.getFirst() : nullable.getFirst()).values(), source); + } + + private static NativeOntologyCount linkCount( + final Source source, final BindingRow target, final OntologyRelationPath.StoredJoin stored) { + final List> key = source.row().subjectKey(); + final List on = listOrEmpty(stored.join().getOn()); + final boolean joined = + !stored.isLink() + && !on.isEmpty() + && on.stream() + .map(OntologyJoinColumnPair::getParent) + .toList() + .equals(target.subjectKey()); + if (!joined + || source.row().rowFilter() != null + || target.rowFilter() != null + || nullOrEmpty(key) + || !source.isUnique(key) + || !key.stream().allMatch(source::hasNoNulls)) { + return notDerivable(); + } + final List children = new ArrayList<>(); + for (final OntologyJoinColumnPair pair : on) { + children.add(source.metrics(pair.getChild())); + } + return children.stream().allMatch(Metrics::isComplete) + ? valueOfAtMostOneNullable(children, source) + : notDerivable(); + } + + /** The identity table of a class with its profile, or the count that says why there is none. */ + private static Source source(final ClassRows binding, final Facts facts) { + final BindingRow row = binding.identity(); + if (row == null) { + return Source.refused(state(State.NO_IDENTITY_TABLE)); + } + final Table table = facts.tables().get(row.assetId()); + if (table == null) { + return Source.refused(state(State.IDENTITY_TABLE_HIDDEN)); + } + final TableProfile profile = + facts.profileViewable().contains(table.getId()) + ? facts.tableProfiles().get(table.getId()) + : null; + return profile == null + ? Source.refused(state(State.NO_PROFILE)) + : new Source(row, table, profile, facts.columnProfiles(), null); + } + + private static boolean isIdentity(final BindingRow row) { + return row.role() == OntologyBindingRole.IDENTITY; + } + + private static NativeOntologyCount state(final State state) { + return new NativeOntologyCount().withState(state); + } + + private static NativeOntologyCount notDerivable() { + return state(State.NOT_DERIVABLE); + } + + private static NativeOntologyCount exact(final Long value, final Source source) { + return value == null + ? notDerivable() + : state(State.EXACT).withValue(value).withProfiledAt(source.profile().getTimestamp()); + } + + /** A non-negative whole number, or null for anything else. */ + private static Long whole(final Number number) { + if (number == null) { + return null; + } + final double value = number.doubleValue(); + return value >= 0 && value == Math.rint(value) && value < Long.MAX_VALUE ? (long) value : null; + } + + /** + * The metrics of one column, which covered the whole table. + * + * @param values the non-null values + */ + private record Metrics(Long values, Long nulls, Long distinct) { + /** True for metrics that exist and state both the values and the nulls. */ + static boolean isComplete(final Metrics metrics) { + return metrics != null && metrics.values != null && metrics.nulls != null; + } + + boolean hasNulls() { + return nulls > 0; + } + } + + /** + * The identity table of a class and what is stored about it. + * + * @param refusal the count that says why the table gives none, or null when it can give one + */ + private record Source( + BindingRow row, + Table table, + TableProfile profile, + Map columnProfiles, + NativeOntologyCount refusal) { + static Source refused(final NativeOntologyCount refusal) { + return new Source(null, null, null, null, refusal); + } + + /** The metrics of the column at {@code path}, or null when they did not cover the table. */ + Metrics metrics(final List path) { + final Column column = OntologyBindingRules.resolveColumn(table, path); + final ColumnProfile stored = + column == null || column.getFullyQualifiedName() == null + ? null + : columnProfiles.get(column.getFullyQualifiedName()); + return stored != null && coversWholeTable(stored) + ? new Metrics( + whole(stored.getValuesCount()), + whole(stored.getNullCount()), + whole(stored.getDistinctCount())) + : null; + } + + private boolean coversWholeTable(final ColumnProfile column) { + final var config = table.getTableProfilerConfig(); + final boolean partitionedRead = + !listOrEmpty( + table.getTablePartition() == null ? null : table.getTablePartition().getColumns()) + .isEmpty(); + final boolean queried = config != null && !nullOrEmpty(config.getProfileQuery()); + final boolean windowed = + config != null + && config.getPartitioning() != null + && Boolean.TRUE.equals(config.getPartitioning().getEnablePartitioning()); + return Objects.equals(profile.getTimestamp(), column.getTimestamp()) + && !partitionedRead + && !queried + && !windowed + && readTheWholeTable(column); + } + + /** No sample, a full percentage, or a row cap that the column's rows stay below. */ + private boolean readTheWholeTable(final ColumnProfile column) { + final Number sample = profile.getProfileSample(); + if (sample == null) { + return true; + } + if (profile.getProfileSampleType() == TableProfile.ProfileSampleType.ROWS) { + final Long values = whole(column.getValuesCount()); + final Long nulls = whole(column.getNullCount()); + return values != null && nulls != null && values + nulls < sample.doubleValue(); + } + return sample.doubleValue() >= WHOLE_PERCENTAGE; + } + + /** + * One row per key value. For a key of one column whose metrics covered the table, they decide + * and the catalog is not asked. Otherwise a primary or unique key that the catalog declares on + * some of the key's columns decides, on an engine that checks it. + */ + boolean isUnique(final List> key) { + if (key.size() == 1) { + final Metrics metrics = metrics(key.getFirst()); + if (metrics != null) { + return metrics.values() != null && Objects.equals(metrics.distinct(), metrics.values()); + } + } + return enforcesKeys() && (declaresTableKey(key) || declaresColumnKey(key)); + } + + /** + * No nulls in a key column. When the metrics covered the table they decide. Otherwise the + * column is declared not null, or is part of a primary key on an engine that checks it. + */ + boolean hasNoNulls(final List path) { + final Metrics metrics = metrics(path); + if (metrics != null) { + return metrics.nulls() != null && metrics.nulls() == 0; + } + final Column column = OntologyBindingRules.resolveColumn(table, path); + return column != null + && (column.getConstraint() == ColumnConstraint.NOT_NULL + || enforcesKeys() && inPrimaryKey(column)); + } + + private boolean enforcesKeys() { + return table.getServiceType() != null + && ENGINES_THAT_ENFORCE_KEYS.contains(table.getServiceType().value()); + } + + /** A declared primary or unique key whose columns are all in the subject key. */ + private boolean declaresTableKey(final List> key) { + final Set names = topLevelNames(key); + return listOrEmpty(table.getTableConstraints()).stream() + .filter(constraint -> isKey(constraint.getConstraintType())) + .map(TableConstraint::getColumns) + .anyMatch(columns -> !nullOrEmpty(columns) && names.containsAll(columns)); + } + + private boolean declaresColumnKey(final List> key) { + return key.stream() + .map(path -> OntologyBindingRules.resolveColumn(table, path)) + .filter(Objects::nonNull) + .map(Column::getConstraint) + .anyMatch( + constraint -> + constraint == ColumnConstraint.PRIMARY_KEY + || constraint == ColumnConstraint.UNIQUE); + } + + private boolean inPrimaryKey(final Column column) { + return column.getConstraint() == ColumnConstraint.PRIMARY_KEY + || listOrEmpty(table.getTableConstraints()).stream() + .filter( + constraint -> + constraint.getConstraintType() == TableConstraint.ConstraintType.PRIMARY_KEY) + .anyMatch( + constraint -> listOrEmpty(constraint.getColumns()).contains(column.getName())); + } + + private static boolean isKey(final TableConstraint.ConstraintType type) { + return type == TableConstraint.ConstraintType.PRIMARY_KEY + || type == TableConstraint.ConstraintType.UNIQUE; + } + + /** The names of the key's columns that sit at the top of the table, which constraints name. */ + private static Set topLevelNames(final List> key) { + return key.stream() + .filter(path -> path.size() == 1) + .map(List::getFirst) + .collect(Collectors.toSet()); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRelationPath.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRelationPath.java index 486f531713cc..26969f019077 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRelationPath.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRelationPath.java @@ -80,19 +80,34 @@ boolean isLink() { record Held(OntologyColumnJoin join, MappedTable link) {} /** - * The confirmed join onto {@code objectTable} that the rows of the subject class store for the - * relation. The identity table is asked before the contributing tables, and the choice never - * depends on which tables a reader may view. A join that is only inferred is a 409, and so is no + * What the rows of the subject class store for a relation onto one table. + * + * @see #lookup + */ + sealed interface Lookup { + /** A confirmed join, from the first row that holds one. */ + record Confirmed(StoredJoin stored) implements Lookup {} + + /** The rows hold a join onto the table and none of them is confirmed. */ + record Unconfirmed() implements Lookup {} + + /** The rows hold no join of the relation onto the table. */ + record Missing() implements Lookup {} + } + + /** + * The join onto {@code objectTable} that {@code subjectRows} store for a relation, in the order + * of the rows: a confirmed join wins over one that is only inferred, and an inferred one over no * join at all. */ - static StoredJoin choose( - final Ends ends, final List subjectRows, final UUID objectTable) { + static Lookup lookup( + final UUID relationId, final List subjectRows, final UUID objectTable) { final List stored = subjectRows.stream() .flatMap( row -> listOrEmpty(row.columns()).stream() - .filter(column -> ends.relationId().equals(column.getPropertyId())) + .filter(column -> relationId.equals(column.getPropertyId())) .filter(column -> column.getJoin() != null) .filter(column -> objectTable.equals(column.getJoin().getTargetAssetId())) .map(column -> new StoredJoin(row, column.getJoin()))) @@ -101,15 +116,29 @@ static StoredJoin choose( stored.stream() .filter(candidate -> candidate.join().getStatus() == OntologyJoinStatus.CONFIRMED) .findFirst(); - return confirmed.orElseThrow( - () -> - stored.isEmpty() - ? conflict( - "Relation %s has no join from class %s to the identity table of class %s", - ends.relation(), ends.subject().iri(), ends.object().iri()) - : conflict( - "The join of relation %s from class %s to class %s is not confirmed", - ends.relation(), ends.subject().iri(), ends.object().iri())); + if (confirmed.isPresent()) { + return new Lookup.Confirmed(confirmed.get()); + } + return stored.isEmpty() ? new Lookup.Missing() : new Lookup.Unconfirmed(); + } + + /** + * The confirmed join onto {@code objectTable} that the rows of the subject class store for the + * relation. The identity table is asked before the contributing tables, and the choice never + * depends on which tables a reader may view. A join that is only inferred is a 409, and so is no + * join at all. + */ + static StoredJoin choose( + final Ends ends, final List subjectRows, final UUID objectTable) { + return switch (lookup(ends.relationId(), subjectRows, objectTable)) { + case Lookup.Confirmed found -> found.stored(); + case Lookup.Unconfirmed ignored -> throw conflict( + "The join of relation %s from class %s to class %s is not confirmed", + ends.relation(), ends.subject().iri(), ends.object().iri()); + case Lookup.Missing ignored -> throw conflict( + "Relation %s has no join from class %s to the identity table of class %s", + ends.relation(), ends.subject().iri(), ends.object().iri()); + }; } /** The path of {@code relation} from {@code start} to {@code related} over the join it holds. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java index 79b0a34bdf6c..b22e4c01845b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java @@ -155,7 +155,8 @@ public class OntologyResource extends EntityResource tables = new HashMap<>(); + final Set profileViewable = new HashSet<>(Set.of(ORDERS_TABLE, CUSTOMERS_TABLE)); + final Map tableProfiles = new HashMap<>(); + final Map columnProfiles = new HashMap<>(); + final List tableConstraints = new ArrayList<>(); + List> subjectKey = List.of(List.of("id")); + List> objectKey = List.of(List.of("id")); + List joinChildren = List.of("customer_id"); + List joinParents = List.of("id"); + OntologyJoinStatus joinStatus = OntologyJoinStatus.CONFIRMED; + OntologyBindingRole subjectRole = OntologyBindingRole.IDENTITY; + OntologyBindingRole objectRole = OntologyBindingRole.IDENTITY; + OntologyRowFilter subjectFilter; + OntologyRowFilter objectFilter; + boolean joinOnContributingTable; + boolean truncated; + List subjectRows; + + World() { + table = + new Table() + .withId(ORDERS_TABLE) + .withFullyQualifiedName(ORDERS_FQN) + .withServiceType(DatabaseServiceType.Postgres) + .withColumns( + List.of( + column(ORDERS_FQN, "id"), + column(ORDERS_FQN, "tenant"), + column(ORDERS_FQN, "customer_id"), + column(ORDERS_FQN, "region"))); + customers = + new Table() + .withId(CUSTOMERS_TABLE) + .withFullyQualifiedName(CUSTOMERS_FQN) + .withServiceType(DatabaseServiceType.Postgres) + .withColumns(List.of(column(CUSTOMERS_FQN, "id"), column(CUSTOMERS_FQN, "tenant"))); + tableProfile = new TableProfile().withTimestamp(PROFILED_AT); + tables.put(ORDERS_TABLE, table); + tables.put(CUSTOMERS_TABLE, customers); + tableProfiles.put(ORDERS_TABLE, tableProfile); + tableProfiles.put(CUSTOMERS_TABLE, new TableProfile().withTimestamp(PROFILED_AT)); + columnProfiles.put( + CUSTOMERS_FQN + ".id", + new ColumnProfile() + .withName("id") + .withTimestamp(PROFILED_AT) + .withValuesCount(50d) + .withNullCount(0d) + .withDistinctCount(50d)); + for (final String name : List.of("id", "tenant", "customer_id", "region")) { + metrics(name, 100, 0, name.equals("id") ? 100 : 40); + } + } + + static World twoColumnKey(final String engine) { + final World world = new World().engine(engine); + world.subjectKey = List.of(List.of("id"), List.of("tenant")); + world.tableConstraint(TableConstraint.ConstraintType.PRIMARY_KEY, "id", "tenant"); + world.metrics("id", 100, 0, 100); + world.metrics("tenant", 100, 0, 3); + return world; + } + + World engine(final String engine) { + table.withServiceType(DatabaseServiceType.fromValue(engine)); + return this; + } + + void metrics( + final String column, final double values, final double nulls, final double distinct) { + columnProfiles.put( + ORDERS_FQN + "." + column, + new ColumnProfile() + .withName(column) + .withTimestamp(PROFILED_AT) + .withValuesCount(values) + .withNullCount(nulls) + .withDistinctCount(distinct)); + } + + void noMetrics(final String column) { + columnProfiles.remove(ORDERS_FQN + "." + column); + } + + void tableConstraint(final TableConstraint.ConstraintType type, final String... columns) { + tableConstraints.add( + new TableConstraint().withConstraintType(type).withColumns(List.of(columns))); + } + + void columnConstraint(final String name, final ColumnConstraint constraint) { + table.getColumns().stream() + .filter(column -> column.getName().equals(name)) + .forEach(column -> column.setConstraint(constraint)); + } + + NativeOntologyCount records(final UUID type) { + return OntologyCountRules.records(classes().get(type), facts()); + } + + NativeOntologyCount links() { + return linksAmong(classes()); + } + + NativeOntologyCount linksAmong(final Map classes) { + return OntologyCountRules.links(new Relation(ORDER, CUSTOMER, PLACED_BY), classes, facts()); + } + + Facts facts() { + table.withTableConstraints(tableConstraints); + return new Facts(tables, profileViewable, tableProfiles, columnProfiles); + } + + Map classes() { + final Map classes = new LinkedHashMap<>(); + classes.put( + ORDER, new ClassRows(ORDER, subjectRows == null ? orderRows() : subjectRows, truncated)); + classes.put( + CUSTOMER, + new ClassRows( + CUSTOMER, + List.of( + row(CUSTOMER, CUSTOMERS_TABLE, objectRole, objectKey, objectFilter, List.of())), + false)); + return classes; + } + + private List orderRows() { + final var join = List.of(joinColumn()); + if (joinOnContributingTable) { + return List.of( + row(ORDER, ORDERS_TABLE, subjectRole, subjectKey, subjectFilter, List.of()), + row(ORDER, LINKS_TABLE, OntologyBindingRole.CONTRIBUTING, subjectKey, null, join)); + } + return List.of( + row( + ORDER, + ORDERS_TABLE, + subjectRole, + subjectKey, + subjectFilter, + joinChildren.isEmpty() ? List.of() : join)); + } + + private OntologyColumnBinding joinColumn() { + return new OntologyColumnBinding() + .withPropertyId(PLACED_BY) + .withColumnPath(List.of(joinChildren.isEmpty() ? "customer_id" : joinChildren.getFirst())) + .withJoin( + new OntologyColumnJoin() + .withTargetAssetId(CUSTOMERS_TABLE) + .withStatus(joinStatus) + .withOn( + IntStream.range(0, joinChildren.size()) + .mapToObj( + part -> + new OntologyJoinColumnPair() + .withChild(List.of(joinChildren.get(part))) + .withParent(List.of(joinParents.get(part)))) + .toList())); + } + + private static Column column(final String table, final String name) { + return new Column().withName(name).withFullyQualifiedName(table + "." + name); + } + + private static BindingRow row( + final UUID type, + final UUID asset, + final OntologyBindingRole role, + final List> key, + final OntologyRowFilter filter, + final List columns) { + return new BindingRow( + type, asset, OntologyBindingAssetType.TABLE, "hash", columns, role, key, filter); + } + } +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json index ac9c7d481499..0868b78f3af3 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json @@ -63,6 +63,10 @@ "after": { "description": "Cursor the concept's bindings endpoint accepts for the next page of viewable assets. Absent when this page holds every viewable asset.", "type": "string" + }, + "records": { + "description": "How many records the concept has, from the stored profiles of its identity table. Absent when the concept binds no table.", + "$ref": "nativeOntologyCount.json" } }, "required": ["concept", "assetCount", "assets"], diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyCount.json b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyCount.json new file mode 100644 index 000000000000..cdd3615b4ee3 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyCount.json @@ -0,0 +1,36 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/nativeOntologyCount.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "NativeOntologyCount", + "description": "A count that the stored profiles of a table give exactly, or the reason they do not. A count is exact or it is absent: a profile's row count is never used, because the profiler may take it from the engine's catalog, which can be an estimate.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.NativeOntologyCount", + "properties": { + "state": { + "description": "exact: the stored profiles give the number. noIdentityTable: the class binds tables and none is its identity table. identityTableHidden: the class has an identity table that the caller may not view, or that is deleted. noProfile: the caller may not view the data profile of the table, or the table has no stored profile. joinNotConfirmed: the relation has a join onto the identity table of the related class and it is not confirmed. noJoin: the relation has no join onto it. notDerivable: the stored profiles cannot give the exact number, and a query over the table could.", + "type": "string", + "enum": [ + "exact", + "noIdentityTable", + "identityTableHidden", + "noProfile", + "joinNotConfirmed", + "noJoin", + "notDerivable" + ] + }, + "value": { + "description": "The count. Present exactly when state is exact.", + "type": "integer", + "existingJavaType": "java.lang.Long", + "format": "int64", + "minimum": 0 + }, + "profiledAt": { + "description": "Time of the profile run whose metrics gave the count. Present exactly when state is exact.", + "$ref": "../../type/basic.json#/definitions/timestamp" + } + }, + "required": ["state"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyDataGraph.json b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyDataGraph.json index d0f070b992d3..dd68dd4ef0b1 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyDataGraph.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyDataGraph.json @@ -29,6 +29,10 @@ "property": { "description": "The declared property, when this ontology declares one for the IRI and the caller may view it.", "$ref": "../../type/entityReference.json" + }, + "links": { + "description": "How many links the relation has from the records of the first concept, from the stored profiles of its identity table. Absent when the page does not hold the first concept.", + "$ref": "nativeOntologyCount.json" } }, "required": ["fromConceptId", "toConceptId", "propertyIri", "label"], From 3cafe7d2906f7db4ac48907e1ba864b7ae84c1c6 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 20:55:48 -0800 Subject: [PATCH 055/203] Test the draft read right on every change set endpoint and the events a draft stores Integration tests for the history listing, the commands and the lease endpoints of a change set, for the audit log after a name is reused, and for the events a webhook receives. A unit test lists every endpoint of the resource with the right it asks. Masked field changes are also dropped from the change description an event's entity carries. The decision record is revised to match. --- ...set-can-carry-table-bindings-and-shapes.md | 62 ++-- .../tests/OntologyChangeSetCommandReadIT.java | 335 ++++++++++++++++++ .../tests/OntologyChangeSetDraftReadIT.java | 89 ++++- .../it/tests/OntologyDraftScene.java | 99 ++++++ .../OntologyChangeSetEventDeliveryIT.java | 125 +++++++ .../service/events/ChangeEventMasking.java | 24 +- .../ontology/OntologyChangeSetReadAccess.java | 25 ++ .../ontology/OntologyChangeSetResource.java | 12 +- .../events/ChangeEventMaskingTest.java | 6 +- .../OntologyChangeSetReadAccessTest.java | 54 +++ 10 files changed, 780 insertions(+), 51 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetCommandReadIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftScene.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java diff --git a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md index 21c1c2ee2e8e..6620b2247853 100644 --- a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md +++ b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md @@ -1,9 +1,9 @@ # An ontology change set can carry table bindings and shapes - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (every path that returns operations asks for the draft read right, and a save is refused when the writer's sight changed since its read) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (every path that returns operations asks for the draft read right, and a save is refused when the writer's sight changed since its read); v3 2026-11-22 (every endpoint that acts on a change set asks that right, and a stored change event holds no operations) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyBindingAndShapeOperationTest`, `OntologyDraftPreflightTest`, `OntologyBindingChangeExecutorTest`, `OntologyChangeApplicationServiceTest`, `OntologyChangeEvidenceViewTest`, `OntologyChangeSetBindingIT`, `OntologyChangeSetEvidenceIT`, `OntologyChangeSetEvidenceMcpIT`, `OntologyChangeSetDraftReadIT`, `OntologyChangeSetDraftReadMcpIT`, `OntologyChangeSetSaveSightIT`, `RdfOntologyChangeSetViewIT`, `RdfExcludedEntitiesTest`, `PatchEntityToolTest` +- **Guard:** `OntologyBindingAndShapeOperationTest`, `OntologyDraftPreflightTest`, `OntologyBindingChangeExecutorTest`, `OntologyChangeApplicationServiceTest`, `OntologyChangeEvidenceViewTest`, `OntologyChangeSetBindingIT`, `OntologyChangeSetEvidenceIT`, `OntologyChangeSetEvidenceMcpIT`, `OntologyChangeSetDraftReadIT`, `OntologyChangeSetDraftReadMcpIT`, `OntologyChangeSetSaveSightIT`, `RdfOntologyChangeSetViewIT`, `RdfExcludedEntitiesTest`, `PatchEntityToolTest`, `OntologyChangeSetCommandReadIT`, `OntologyChangeSetEventDeliveryIT`, `OntologyChangeSetEndpointRightsTest`, `OntologyChangeSetReadAccessTest`, `ChangeEventMaskingTest`, `OntologyChangeEventPublisherTest` - **Related:** ADR:2026-10-19-native-concept-bindings-remain-operational-metadata (amended by this record), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records, ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints, @@ -53,27 +53,40 @@ operations leaves out each entry whose table its caller lacks `ViewBasic` on, an every caller. The stored operation keeps every entry. "Every response" means every endpoint of the change set resource, the versions it serves and the MCP tool that reads an entity. -The paths that return the operations of a change set and the way each is covered: - -- The change set resource, its versions and its history: evidence masked per reader, and the draft - read right, which is `EditAll` on the ontology the change set targets or on each glossary it - targets. -- The audit log, read for one change set: the same draft read right, asked after `ViewBasic`. A - change set that is deleted is still checked, and one that cannot be loaded leaves only the - audit-log permission. A request that names the change set type and a service name is checked the - same way, because the events of a change set carry its own name as their service name. The - export of the audit log needs the audit-log permission. +The paths that return the operations of a change set, or act on one, and the right each asks. +`OntologyChangeSetEndpointRightsTest` lists every endpoint of the resource, inherited ones included, +so a new endpoint fails it until its right is written down. + +- The draft read right is `EditAll` on the ontology the change set targets, or on each glossary it + targets. It is asked by: get, list (for every row), versions and one version; the history + listing, which keeps only the snapshots of change sets the caller may read and drops the rest + with a 200; undo, redo, discard and the save of operations (with or without operations), each + before the edit right on the change set and before the lease; soft delete, hard delete and + restore, before their own rights; and the endpoints of the lease (take, renew, read, release), + because a holder who may not read the draft could otherwise block its editors. Submit and apply + ask `EditAll` on the same scope. The AI context endpoints ask `ViewAll` and answer with no + operations. A refusal is a 403 with the text the get gives, and nothing is written. +- The audit log, read for one change set: the same draft read right, asked after `ViewBasic`, and + the rows returned are those whose entity id is the change set that holds the name now, because a + name freed by a hard delete can be taken by another draft. A change set that is deleted is still + checked, and one that cannot be loaded leaves only the audit-log permission. A request that names + the change set type and a service name is treated the same way, because the events of a change + set carry its own name as their service name. A caller who holds the audit-log permission reads + every row. The export needs the audit-log permission. - The MCP tool that reads an entity, in each call shape: the same draft read right, then the evidence masked per reader. - The RDF view and the knowledge graph: a change set is not in them. It is excluded from the projection and from its relationship edges, and the RDF endpoint for one entity refuses the type. - A graph built before this record holds change sets until its next full rebuild. -- Change events, recorded changes and stored versions: they hold the operations without evidence, - and a version is masked when it is read. + A graph built before this record can still hold change sets. A full recreate of the RDF index + removes them, and a reindex without a recreate does not. +- Change events, recorded changes and stored versions: a stored change event holds no operations, + neither in its entity nor in the old and new value of a recorded field change. An event reaches + every subscriber, every destination and the audit log, and when the server stores it, it cannot + know who will read it. The operations stay readable through the get and the versions, which ask + the draft read right. A stored version is masked when it is read. No other endpoint returns the operations of a change set. Entity versions, feed and activity, -lineage, search and the generic entity readers carry no operations of a change set, and an event -subscription receives the stored change event, which holds no evidence. +lineage, search and the generic entity readers carry no operations of a change set. The MCP tool that patches an entity refuses a change set. A JSON Patch can copy a stored entry into a member that every reader is shown, and the change set resource itself offers no patch. @@ -93,10 +106,13 @@ the writer while another becomes hidden, so the two counts agree. The save then the writer sent about tables it can view and keeps those it cannot, and the entry that became visible stays in the draft as the stored operation holds it. -`evidence` and `withheldEvidenceCount` are masked fields +`operations`, `evidence` and `withheldEvidenceCount` are masked fields (ADR:2026-10-26-masked-fields-stay-out-of-change-events-and-version-history), so no stored change -event holds them, and the recorded change of `operations` holds the operations without their -evidence. A save that changes evidence alone is stored without a new version. +event holds them. A masked field is also left out of the recorded field changes of an event, for +every entity type. The versions of a change set keep `operations`, because they are its content and +the endpoints that serve them ask the draft read right, and the recorded change of `operations` in +a version holds the operations without their evidence. A save that changes evidence alone is stored +without a new version. **A save checks what an operation names, and an apply checks what its caller may do.** @@ -148,9 +164,9 @@ read right sees them, the table id, the key columns and the row filter among the masked, for this reason: the same draft declares the classes and properties that were made from those tables, so it already says what the columns are, and the bindings API hides a stored binding and not a proposal. The table id is opaque. Applying still checks the rights of whoever applies. -Every path that returns them asks for the draft read right -(ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights), so a user who may only view -change sets learns none of it. +Every endpoint that returns them or acts on the change set asks for the draft read right +(ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights), and no stored event holds them, +so a user who may only view change sets, or who subscribes to events, learns none of it. An author cites only tables it may view. A service that drafts with wider rights than the person it drafts for therefore saves the draft itself, and that person then reads it through their own view. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetCommandReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetCommandReadIT.java new file mode 100644 index 000000000000..7e379ee1140a --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetCommandReadIT.java @@ -0,0 +1,335 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.AcquireOntologyEditLock; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * Every endpoint that acts on one change set asks the draft read right, which is edit on the + * ontology it targets. An editor of change sets with no right on the ontology is refused before + * anything is written or answered, and a viewer reads no snapshot of the draft from the history. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetCommandReadIT extends BaseOntologyApprovalIT { + private static final String COLUMN = "command_read_column"; + private static final String VALUE = "command_read_value"; + private static final String LEASES = "/v1/ontologyEditLocks"; + private static final int FORBIDDEN = 403; + + private record Scene( + OntologyChangeSet draft, + Table table, + OpenMetadataClient author, + OpenMetadataClient editor, + OpenMetadataClient viewer, + OntologyEditLeaseToken authorLease, + long startedAt) { + String path() { + return CHANGE_SETS + "/" + draft.getId(); + } + + Map asAuthor() { + return Map.of("lease", authorLease); + } + + void assertNoSecretIn(final String body) { + assertFalse(body.contains(table.getId().toString()), body); + assertFalse(body.contains(COLUMN), body); + assertFalse(body.contains(VALUE), body); + } + } + + @Test + void aViewerOfChangeSetsReadsNoSnapshotOfTheDraftFromTheHistory(final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdHist" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdHistOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + send(scene.author(), HttpMethod.POST, scene.path() + "/undo", scene.asAuthor()); + send(scene.author(), HttpMethod.POST, scene.path() + "/redo", scene.asAuthor()); + final String history = + CHANGE_SETS + "/history?limit=500&startTs=" + scene.startedAt() + "&endTs=" + later(); + final String id = scene.draft().getId().toString(); + + final String viewed = send(scene.viewer(), HttpMethod.GET, history, null); + + assertFalse(viewed.contains(id), viewed); + scene.assertNoSecretIn(viewed); + for (final OpenMetadataClient reader : List.of(scene.author(), admin())) { + final String read = send(reader, HttpMethod.GET, history, null); + assertTrue(read.contains(id), read); + assertTrue(read.contains(scene.table().getId().toString()), read); + } + } + } + + @Test + void anEditorWithoutTheOntologyEditRightIsRefusedEveryCommandAndNothingChanges( + final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdEdit" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdEditOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + final String refusal = refusalOfRead(scene); + final JsonNode operations = stored(scene).path("operations"); + final Map replacement = + Map.of("lease", scene.authorLease(), "operations", operations, "undoCursor", 1); + final Map removal = + Map.of("lease", scene.authorLease(), "operations", List.of(), "undoCursor", 0); + final JsonNode before = stored(scene); + + for (final Attempt attempt : + List.of( + new Attempt("undo", HttpMethod.POST, scene.path() + "/undo", scene.asAuthor()), + new Attempt("redo", HttpMethod.POST, scene.path() + "/redo", scene.asAuthor()), + new Attempt("discard", HttpMethod.POST, scene.path() + "/discard", scene.asAuthor()), + new Attempt("replace", HttpMethod.PUT, scene.path() + "/operations", replacement), + new Attempt("replace none", HttpMethod.PUT, scene.path() + "/operations", removal), + new Attempt( + "soft delete", HttpMethod.DELETE, scene.path() + "?hardDelete=false", null), + new Attempt( + "hard delete", HttpMethod.DELETE, scene.path() + "?hardDelete=true", null), + new Attempt( + "restore", + HttpMethod.PUT, + CHANGE_SETS + "/restore", + Map.of("id", scene.draft().getId().toString())))) { + assertRefusedLikeTheRead(scene, attempt, refusal); + assertEquals(before, stored(scene), attempt.label()); + } + } + } + + @Test + void anEditorCannotTakeReadOrReleaseTheLeaseOfADraftItMayNotRead(final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdLease" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdLeaseOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + final String refusal = refusalOfRead(scene); + final String lease = LEASES + "/" + Entity.ONTOLOGY_CHANGE_SET + "/" + scene.draft().getId(); + final Object request = + new AcquireOntologyEditLock() + .withResourceType(Entity.ONTOLOGY_CHANGE_SET) + .withResourceId(scene.draft().getId()) + .withSessionId(UUID.randomUUID().toString()) + .withLeaseSeconds(60); + final String held = send(scene.author(), HttpMethod.GET, lease, null); + + for (final Attempt attempt : + List.of( + new Attempt("acquire", HttpMethod.POST, LEASES + "/acquire", request), + new Attempt("renew", HttpMethod.PUT, LEASES + "/renew", request), + new Attempt("get", HttpMethod.GET, lease, null), + new Attempt( + "release", + HttpMethod.DELETE, + lease + "?sessionId=" + scene.authorLease().getSessionId(), + null))) { + assertRefusedLikeTheRead(scene, attempt, refusal); + } + + assertEquals(held, send(scene.author(), HttpMethod.GET, lease, null)); + assertEquals( + scene.authorLease().getSessionId(), JsonUtils.readTree(held).path("sessionId").asText()); + } + } + + @Test + void theAuthorCanStillRunEveryCommandAndTheDraftAnswersWithItsOperations(final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdAuthor" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdAuthorOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + final JsonNode operations = stored(scene).path("operations"); + + for (final String command : List.of("/undo", "/redo")) { + final String answer = + send(scene.author(), HttpMethod.POST, scene.path() + command, scene.asAuthor()); + assertTrue(answer.contains(scene.table().getId().toString()), command); + } + final String replaced = + send( + scene.author(), + HttpMethod.PUT, + scene.path() + "/operations", + Map.of("lease", scene.authorLease(), "operations", operations, "undoCursor", 1)); + assertTrue(replaced.contains(scene.table().getId().toString())); + final String discarded = + send(scene.author(), HttpMethod.POST, scene.path() + "/discard", scene.asAuthor()); + assertEquals("DISCARDED", JsonUtils.readTree(discarded).path("state").asText()); + assertTrue(discarded.contains(scene.table().getId().toString())); + } + } + + @Test + void theAuthorCanStillReplaceWithNoOperationsAndDeleteAndRestoreTheDraft(final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdDelete" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdDeleteOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + + send( + scene.author(), + HttpMethod.PUT, + scene.path() + "/operations", + Map.of("lease", scene.authorLease(), "operations", List.of(), "undoCursor", 0)); + final String afterReplace = + send(admin(), HttpMethod.GET, scene.path() + "?fields=operations", null); + assertEquals(0, JsonUtils.readTree(afterReplace).path("operations").size()); + // The binding still shows in the draft's recorded change, as the value the save removed, + // which + // is how a replace with no operations can look as if it left the binding in place. + assertTrue(afterReplace.contains(COLUMN)); + assertEquals( + "operations", + JsonUtils.readTree(afterReplace) + .path("changeDescription") + .path("fieldsUpdated") + .get(0) + .path("name") + .asText()); + final String softDeleted = + send(scene.author(), HttpMethod.DELETE, scene.path() + "?hardDelete=false", null); + assertTrue(JsonUtils.readTree(softDeleted).path("deleted").asBoolean()); + final String restored = + send( + scene.author(), + HttpMethod.PUT, + CHANGE_SETS + "/restore", + Map.of("id", scene.draft().getId().toString())); + assertFalse(JsonUtils.readTree(restored).path("deleted").asBoolean()); + send(scene.author(), HttpMethod.DELETE, scene.path() + "?hardDelete=true", null); + assertEquals( + 404, + assertThrows( + OpenMetadataException.class, + () -> send(admin(), HttpMethod.GET, scene.path(), null)) + .getStatusCode()); + } + } + + private record Attempt(String label, HttpMethod method, String path, Object body) {} + + private static String refusalOfRead(final Scene scene) { + final OpenMetadataException read = + assertThrows( + OpenMetadataException.class, + () -> send(scene.editor(), HttpMethod.GET, scene.path(), null)); + assertEquals(FORBIDDEN, read.getStatusCode()); + return read.getMessage(); + } + + /** + * The editor holds the author's lease token, so a command that skipped the read right would meet + * a different refusal, and one that skipped the lease check would write. + */ + private static void assertRefusedLikeTheRead( + final Scene scene, final Attempt attempt, final String readRefusal) { + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> send(scene.editor(), attempt.method(), attempt.path(), attempt.body()), + attempt.label()); + assertEquals(FORBIDDEN, refused.getStatusCode(), attempt.label()); + assertEquals(readRefusal, refused.getMessage(), attempt.label()); + scene.assertNoSecretIn(refused.getMessage()); + } + + /** What an admin reads of the draft, with the version, the deleted flag and the operations. */ + private static JsonNode stored(final Scene scene) { + return JsonUtils.readTree( + send(admin(), HttpMethod.GET, scene.path() + "?fields=operations&include=all", null)); + } + + private static Scene scene( + final TestNamespace ns, final RdfAccessFixtures authors, final RdfAccessFixtures others) { + final long startedAt = System.currentTimeMillis() - 1000; + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final OpenMetadataClient author = + callerWithout(authors, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final var edit = others.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CHANGE_SET); + final var remove = others.allowRole(MetadataOperation.DELETE, Entity.ONTOLOGY_CHANGE_SET); + final var viewAll = others.allowRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_CHANGE_SET); + final var viewBasic = + others.allowRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CHANGE_SET); + final var noTables = others.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OpenMetadataClient editor = + OntologyBindingFixtures.client( + others.userToken("editor", List.of(edit.getId(), remove.getId(), noTables.getId()))); + final OpenMetadataClient viewer = + OntologyBindingFixtures.client( + others.userToken( + "viewer", List.of(viewAll.getId(), viewBasic.getId(), noTables.getId()))); + final Table table = table(schema(ns), "hidden", column(COLUMN, ColumnDataType.VARCHAR)); + final OntologyChangeSet draft = + draft( + author, + ns, + ontology, + binds( + bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(COLUMN))) + .withRowFilter(filter(COLUMN, OntologyRowFilterOperator.EQUALS, VALUE)))); + return new Scene(draft, table, author, editor, viewer, lease(author, draft), startedAt); + } + + private static long later() { + return System.currentTimeMillis() + 60_000; + } + + private static String send( + final OpenMetadataClient caller, + final HttpMethod method, + final String path, + final Object body) { + return caller.getHttpClient().executeForString(method, path, body); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java index 5ab9ca2811b3..bcbe402f26e0 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java @@ -20,7 +20,11 @@ import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.workingRevision; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; import static org.openmetadata.it.tests.OntologyMappingFixtures.column; @@ -28,21 +32,27 @@ import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; import static org.openmetadata.it.tests.OntologyMappingFixtures.table; +import java.net.URI; import java.time.Duration; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.openmetadata.it.util.RdfAccessFixtures; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyChangeSet; import org.openmetadata.schema.entity.data.Ontology; import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.network.HttpMethod; @@ -86,8 +96,8 @@ void aUserWhoMayOnlyViewChangeSetsIsRefusedItsAuditLogAndTheEditorsAndAdminAreNo assertEquals(FORBIDDEN, refusal.getStatusCode()); scene.assertNoSecretIn(refusal.getMessage()); - assertTrue(audit(scene.author(), scene.fqn()).contains(scene.table().getId().toString())); - assertTrue(audit(admin(), scene.fqn()).contains(scene.table().getId().toString())); + assertReadsTheEventsOnly(audit(scene.author(), scene.fqn()), scene); + assertReadsTheEventsOnly(audit(admin(), scene.fqn()), scene); } } @@ -104,8 +114,8 @@ void aSoftDeletedChangeSetIsStillCheckedAgainstTheDraftReadRight(final TestNames assertEquals(FORBIDDEN, refusal.getStatusCode()); scene.assertNoSecretIn(refusal.getMessage()); - assertTrue(audit(scene.author(), scene.fqn()).contains(scene.table().getId().toString())); - assertTrue(audit(admin(), scene.fqn()).contains(scene.table().getId().toString())); + assertReadsTheEventsOnly(audit(scene.author(), scene.fqn()), scene); + assertReadsTheEventsOnly(audit(admin(), scene.fqn()), scene); } } @@ -121,7 +131,7 @@ void aHardDeletedChangeSetLeavesOnlyTheAuditLogPermission(final TestNamespace ns assertThrows(OpenMetadataException.class, () -> audit(scene.viewer(), scene.fqn())); assertEquals(FORBIDDEN, refusal.getStatusCode()); scene.assertNoSecretIn(refusal.getMessage()); - assertTrue(audit(admin(), scene.fqn()).contains(scene.table().getId().toString())); + assertReadsTheEventsOnly(audit(admin(), scene.fqn()), scene); } } @@ -140,12 +150,75 @@ void theServiceNamePathIsNotAWayRoundTheDraftReadRight(final TestNamespace ns) { assertEquals(FORBIDDEN, refusal.getStatusCode(), serviceName); scene.assertNoSecretIn(refusal.getMessage()); } - assertTrue( - get(scene.author(), AUDIT + "&serviceName=" + scene.fqn()) - .contains(scene.table().getId().toString())); + assertReadsTheEventsOnly(get(scene.author(), AUDIT + "&serviceName=" + scene.fqn()), scene); } } + @Test + void aNameFreedByAHardDeleteDoesNotOpenTheRowsOfTheDeletedDraft(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditReuse" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditReuseViewer" + ns.shortPrefix()); + var reusers = new RdfAccessFixtures("auditReuseUser" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + delete(scene, true); + final var create = reusers.allowRole(MetadataOperation.CREATE, Entity.ONTOLOGY_CHANGE_SET); + final var noTables = reusers.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OpenMetadataClient reuser = + OntologyBindingFixtures.client( + reusers.userToken("reuser", List.of(create.getId(), noTables.getId()))); + final User me = JsonUtils.readValue(get(reuser, "/v1/users/loggedInUser"), User.class); + final Ontology second = + admin() + .ontologies() + .create( + request(ns) + .withName(ns.prefix("auditReuseSecond")) + .withIri(URI.create("https://example.org/model/" + ns.shortPrefix() + "r")) + .withOwners(List.of(me.getEntityReference()))); + ns.trackRoot("ontology", second); + + final OntologyChangeSet reused = + ns.trackRoot( + "ontologyChangeSet", + reuser + .ontologyChangeSets() + .create( + new CreateOntologyChangeSet() + .withName(scene.draft().getName()) + .withDisplayName("Reused name") + .withDescription("A draft that takes a name the first one freed") + .withOntology(second.getFullyQualifiedName()) + .withBaseWorkingRevision(workingRevision(second)) + .withOperations( + List.of(creates(proposedClass(second, "Customer", CUSTOMER)))))); + Awaitility.await("the audit events of both drafts") + .atMost(Duration.ofSeconds(60)) + .until(() -> entityIds(audit(admin(), scene.fqn())).size() == 2); + + assertEquals(Set.of(reused.getId().toString()), entityIds(audit(reuser, scene.fqn()))); + assertEquals( + Set.of(reused.getId().toString()), + entityIds(get(reuser, AUDIT + "&serviceName=" + scene.fqn()))); + assertEquals( + Set.of(scene.draft().getId().toString(), reused.getId().toString()), + entityIds(audit(admin(), scene.fqn()))); + scene.assertNoSecretIn(audit(reuser, scene.fqn())); + } + } + + private static Set entityIds(final String auditBody) { + return JsonUtils.readTree(auditBody).path("data").findValuesAsText("entityId").stream() + .collect(Collectors.toSet()); + } + + /** The audit rows are readable, and no row of a change set holds its operations. */ + private static void assertReadsTheEventsOnly(final String body, final Scene scene) { + assertTrue(body.contains("entityCreated"), body); + scene.assertNoSecretIn(body); + assertFalse(body.contains("operations"), body); + } + private static Scene scene( final TestNamespace ns, final RdfAccessFixtures fixtures, final RdfAccessFixtures viewers) { final Ontology ontology = createOntology(ns); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftScene.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftScene.java new file mode 100644 index 000000000000..6ec714c1bb51 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftScene.java @@ -0,0 +1,99 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.replaceOperations; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.util.ArrayList; +import java.util.List; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.sdk.network.HttpMethod; + +/** + * A draft with one table binding, built and run by an admin, for tests in other packages that + * watch what leaves the server about it. Its table, key column and filter value are strings no + * other draft holds. + */ +public final class OntologyDraftScene extends BaseOntologyApprovalIT { + public static final String COLUMN = "scene_key_column_4417"; + public static final String VALUE = "scene_filter_value_4417"; + + /** The draft with the table it binds, and the lease its builder holds. */ + public record Built(OntologyChangeSet draft, Table table, Ontology ontology) {} + + private OntologyDraftScene() {} + + public static Built build(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final Table table = table(schema(ns), "scenehidden", column(COLUMN, ColumnDataType.VARCHAR)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(COLUMN))) + .withRowFilter(filter(COLUMN, OntologyRowFilterOperator.EQUALS, VALUE)))); + return new Built(draft, table, ontology); + } + + /** Adds a class to the draft in a second save, then applies it. */ + public static OntologyChangeSet saveAgainAndApply(final Built scene) { + final OntologyEditLeaseToken lease = lease(admin(), scene.draft()); + final List operations = new ArrayList<>(scene.draft().getOperations()); + operations.add(creates(proposedClass(scene.ontology(), "Customer", CUSTOMER))); + replaceOperations(admin(), scene.draft(), lease, operations); + return OntologyDraftFixtures.apply(admin(), scene.draft(), lease); + } + + /** The draft as its reader sees it, operations included. */ + public static String read(final Built scene) { + return admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, CHANGE_SETS + "/" + scene.draft().getId() + "?fields=operations", null); + } + + public static String versions(final Built scene) { + return admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, CHANGE_SETS + "/" + scene.draft().getId() + "/versions", null); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java new file mode 100644 index 000000000000..3f892dd71bf6 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java @@ -0,0 +1,125 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests.alerts; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.schema.entity.events.SubscriptionDestination.SubscriptionType.WEBHOOK; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.tests.OntologyDraftScene; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.events.CreateEventSubscription; +import org.openmetadata.schema.entity.events.AlertType; +import org.openmetadata.schema.entity.events.EventSubscription; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; + +/** + * An event reaches every subscriber, destination and the audit log, and the server that stores it + * cannot know who will read it. So a stored event of a change set holds no operations, in its + * entity or in the recorded changes of a field, and a subscriber who may not read the draft + * receives none of its binding. The draft itself still returns its operations to a reader. + */ +@Isolated +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetEventDeliveryIT { + private static final int ONE_DAY_SECONDS = 86400; + private static final int MAX_TICKS = 30; + + @Test + void aWebhookOnEveryResourceReceivesNoOperationsOfADraft(final TestNamespace ns) + throws Exception { + final OpenMetadataClient creator = AlertFixtures.alertCreatorClient(); + try (RecordingReceiver receiver = new RecordingReceiver()) { + final EventSubscription alert = webhookOnEveryResource(ns, creator, receiver); + QuietAlert.settle(alert); + + final OntologyDraftScene.Built scene = OntologyDraftScene.build(ns); + OntologyDraftScene.saveAgainAndApply(scene); + final String draftId = scene.draft().getId().toString(); + for (int tick = 0; tick < MAX_TICKS && !hasApplied(receiver, draftId); tick++) { + DirectTick.run(alert); + } + + final List events = eventsOf(receiver, draftId); + assertEquals( + Set.of("entityCreated", "entityUpdated", "ontologyChangeSetApplied"), + new TreeSet<>(events.stream().map(event -> event.path("eventType").asText()).toList())); + for (final JsonNode event : events) { + assertNoOperations(event, scene); + } + assertTrue(OntologyDraftScene.read(scene).contains(scene.table().getId().toString())); + assertTrue(OntologyDraftScene.read(scene).contains(OntologyDraftScene.VALUE)); + assertTrue(OntologyDraftScene.versions(scene).contains(scene.table().getId().toString())); + } + } + + private static EventSubscription webhookOnEveryResource( + final TestNamespace ns, final OpenMetadataClient creator, final RecordingReceiver receiver) { + final CreateEventSubscription request = + new CreateEventSubscription() + .withName(ns.prefix("draft_events")) + .withAlertType(AlertType.NOTIFICATION) + .withResources(List.of("all")) + .withEnabled(true) + .withBatchSize(100) + .withPollInterval(ONE_DAY_SECONDS) + .withDestinations(List.of(AlertFixtures.external(WEBHOOK, receiver.url("/draft")))); + return AlertFixtures.stored(creator.eventSubscriptions().create(request).getId()); + } + + private static boolean hasApplied(final RecordingReceiver receiver, final String draftId) { + return eventsOf(receiver, draftId).stream() + .anyMatch(event -> "ontologyChangeSetApplied".equals(event.path("eventType").asText())); + } + + private static List eventsOf(final RecordingReceiver receiver, final String draftId) { + return receiver.received().stream() + .map(RecordingReceiver.Received::body) + .filter(body -> body.contains(draftId)) + .map(JsonUtils::readTree) + .filter(event -> "ontologyChangeSet".equals(event.path("entityType").asText())) + .toList(); + } + + private static void assertNoOperations( + final JsonNode event, final OntologyDraftScene.Built scene) { + final String body = event.toString(); + assertFalse(body.contains(scene.table().getId().toString()), body); + assertFalse(body.contains(OntologyDraftScene.COLUMN), body); + assertFalse(body.contains(OntologyDraftScene.VALUE), body); + final JsonNode entity = event.path("entity"); + final JsonNode held = entity.isTextual() ? JsonUtils.readTree(entity.asText()) : entity; + assertEquals(scene.draft().getName(), held.path("name").asText(), body); + assertFalse(held.has("operations"), body); + for (final String kind : List.of("fieldsAdded", "fieldsUpdated", "fieldsDeleted")) { + assertFalse( + event + .path("changeDescription") + .path(kind) + .findValuesAsText("name") + .contains("operations"), + body); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java index 7b6f60d944cb..cf24cb3a7c11 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java @@ -40,7 +40,9 @@ public final class ChangeEventMasking { private static final JsonFactory JSON_FACTORY = new JsonFactory(); private static final String ENTITY = "entity"; private static final String ENTITY_TYPE = "entityType"; - private static final String CHANGE_DESCRIPTION = "changeDescription"; + // The event records the change, and the entity it carries records the change that made it. + private static final List CHANGE_DESCRIPTIONS = + List.of("changeDescription", "incrementalChangeDescription"); private static final List FIELD_CHANGE_LISTS = List.of("fieldsAdded", "fieldsUpdated", "fieldsDeleted"); @@ -69,24 +71,28 @@ private static boolean maskEntity(final ObjectNode event, final Class entityC entity.isTextual() ? JsonUtils.readValueLenient(entity.asText(), entityClass) : JsonUtils.convertValueLenient(entity, entityClass); - event.put(ENTITY, JsonUtils.pojoToMaskedJson(typed)); + final ObjectNode masked = (ObjectNode) JsonUtils.readTree(JsonUtils.pojoToMaskedJson(typed)); + dropMaskedFieldChanges(masked, entityClass); + event.put(ENTITY, masked.toString()); } return isPresent; } /** * A recorded field change holds the old and the new value of a field, so a change of a field - * that is masked as a whole is left out of the event. Nothing in the stored event then holds the - * field's values, and the entity's own endpoints still decide who reads them. + * that is masked as a whole is left out of the event and of the entity it carries. Nothing in the + * stored event then holds the field's values, and the entity's own endpoints still decide who + * reads them. */ private static boolean dropMaskedFieldChanges( - final ObjectNode event, final Class entityClass) { + final ObjectNode holder, final Class entityClass) { final List masked = MaskedFields.wholeFieldsOf(entityClass); - final JsonNode description = event.path(CHANGE_DESCRIPTION); boolean isDropped = false; - for (final String kind : FIELD_CHANGE_LISTS) { - if (!masked.isEmpty() && description.path(kind) instanceof ArrayNode changes) { - isDropped |= removeChangesOf(changes, masked); + for (final String description : CHANGE_DESCRIPTIONS) { + for (final String kind : FIELD_CHANGE_LISTS) { + if (!masked.isEmpty() && holder.path(description).path(kind) instanceof ArrayNode changes) { + isDropped |= removeChangesOf(changes, masked); + } } } return isDropped; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java index 0643c2f29dc4..048c27768ba1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java @@ -16,6 +16,11 @@ import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import jakarta.ws.rs.core.SecurityContext; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; import java.util.function.Supplier; import org.openmetadata.schema.entity.data.Glossary; import org.openmetadata.schema.entity.data.OntologyChangeSet; @@ -77,6 +82,26 @@ public static boolean mayRead( } } + /** + * The snapshots of the change sets the caller may read. The right is asked once for each change + * set, whatever the number of its snapshots, and a snapshot of a change set the caller may not + * read, or that cannot be decided, is dropped. + */ + public static List readable( + final Authorizer authorizer, + final SecurityContext securityContext, + final List snapshots, + final Function loader) { + final Map decided = new HashMap<>(); + return snapshots.stream() + .filter( + snapshot -> + decided.computeIfAbsent( + snapshot.getId(), + id -> mayRead(authorizer, securityContext, () -> loader.apply(id)))) + .toList(); + } + private static void requireGlossaryRead( final Authorizer authorizer, final SecurityContext securityContext, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java index c6151a98eef5..57ab0899a0fa 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java @@ -321,16 +321,8 @@ protected Optional> snapshotRedaction( @Override protected List retainReadableHistory( final SecurityContext securityContext, final List snapshots) { - final Map readable = new LinkedHashMap<>(); - return snapshots.stream() - .filter( - snapshot -> - readable.computeIfAbsent( - snapshot.getId(), - id -> - OntologyChangeSetReadAccess.mayRead( - authorizer, securityContext, () -> readableChangeSet(id)))) - .toList(); + return OntologyChangeSetReadAccess.readable( + authorizer, securityContext, snapshots, this::readableChangeSet); } @POST diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java index 949973c98f24..fbd5699b3142 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java @@ -201,13 +201,17 @@ void aDraftsOperationsLeaveItsEntityAndItsRecordedChanges() { .withId(UUID.randomUUID()) .withName("draft") .withUndoCursor(1) - .withOperations(List.of(operation))); + .withOperations(List.of(operation)) + .withChangeDescription(changes)); final String stored = ChangeEventMasking.masked(JsonUtils.pojoToJson(event)); assertFalse(stored.contains(tableId.toString())); final JsonNode entity = storedEntity(stored); assertFalse(entity.has("operations")); + assertEquals( + List.of("undoCursor"), + entity.path("changeDescription").path("fieldsUpdated").findValuesAsText("name")); assertEquals("draft", entity.path("name").asText()); assertEquals(1, entity.path("undoCursor").asInt()); final JsonNode updated = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java index 139a2e41df6d..b2822e7215be 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java @@ -13,11 +13,15 @@ package org.openmetadata.service.ontology; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import jakarta.ws.rs.core.SecurityContext; +import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.List; +import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; @@ -85,6 +89,56 @@ void aScopeThatNoLongerExistsIsNotShown() { } } + @Test + void aHistoryKeepsTheSnapshotsOfReadableDraftsAndDecidesEachDraftOnce() { + final OntologyChangeSet readable = draft(); + final OntologyChangeSet unreadable = draft(); + final OntologyChangeSet gone = draft(); + final List snapshots = + List.of(readable, unreadable, readable, gone, unreadable, readable, gone); + final Map loads = new HashMap<>(); + final Map scopeOf = new IdentityHashMap<>(); + final Authorizer authorizer = refusing(scopeOf, unreadable.getOntology().getId()); + + try (MockedConstruction ignored = + Mockito.mockConstruction( + ResourceContext.class, + (context, creation) -> scopeOf.put(context, creation.arguments().get(1)))) { + final List kept = + OntologyChangeSetReadAccess.readable( + authorizer, + CALLER, + snapshots, + id -> { + loads.merge(id, 1, Integer::sum); + if (id.equals(gone.getId())) { + throw new EntityNotFoundException("gone"); + } + return snapshots.stream().filter(s -> s.getId().equals(id)).findFirst().get(); + }); + + assertEquals(List.of(readable, readable, readable), kept); + } + assertEquals(Map.of(readable.getId(), 1, unreadable.getId(), 1, gone.getId(), 1), loads); + } + + private static Authorizer refusing(final Map scopeOf, final UUID ontologyId) { + final Authorizer authorizer = Mockito.mock(Authorizer.class); + Mockito.doAnswer( + call -> { + if (ontologyId.equals(scopeOf.get(call.getArgument(2)))) { + throw new AuthorizationException("denied"); + } + return null; + }) + .when(authorizer) + .authorize( + Mockito.any(SecurityContext.class), + Mockito.any(OperationContext.class), + Mockito.any(ResourceContextInterface.class)); + return authorizer; + } + private static OntologyChangeSet draft() { return new OntologyChangeSet() .withId(UUID.randomUUID()) From 5d31d6cb18f6b700e563497cb11c321ffe54c113 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 20:56:12 -0800 Subject: [PATCH 056/203] Bound the binding read of the counts to a few table rows for each class, and test that the statements do not grow with the classes --- .../2026-11-22-a-count-is-exact-or-absent.md | 6 ++ .../NativeOntologyDataGraphBindingScanIT.java | 4 +- .../tests/NativeOntologyDataGraphCountIT.java | 76 +++++++++++++++++-- .../jdbi3/OntologyConceptBindingDAO.java | 9 ++- .../jdbi3/OntologyConceptBindingStore.java | 20 +++-- .../service/ontology/OntologyCountRules.java | 7 +- 6 files changed, 101 insertions(+), 21 deletions(-) diff --git a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md index 7c419a27ab08..1b73313020c4 100644 --- a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md +++ b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md @@ -92,6 +92,12 @@ A profile taken by a workflow that runs outside the platform can use a partition neither the table nor the profile records. A count from such a profile covers that window. This is a known limit of reading stored profiles. +A class whose read reaches five table rows, its identity table and four more, may bind more, and is +read as far as that goes. +When the identity table of such a class holds no confirmed join for a relation, the relation is +`notDerivable` and not `noJoin` or `joinNotConfirmed`, because a table not read could hold the +join. + A class with a row filter, a sampled or partitioned table, or a key that no metric or enforced constraint proves unique has no count here. A query over the table is the way to count it, and that is not part of this record. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java index ae359c7da2d8..a1975482a547 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java @@ -146,7 +146,7 @@ void exactVisibleCountAndPreviewCursorSurviveMoreThanOneBindingPage(final TestNa } while (pageAfter != null); assertEquals(List.of(visible.getLast()), pageRemaining); assertEquals(10, emptyPagePages); - assertEquals(List.of(500L, 500L, 500L, 500L, 500L, 500L, 18L), observed.bindingRows()); + assertEquals(List.of(500L, 500L, 500L, 500L, 500L, 500L, 18L, 0L), observed.bindingRows()); assertEquals(500, observed.largestInList()); observed.assertBounded(); } finally { @@ -210,7 +210,7 @@ void bindingKeysetsAdvanceAcrossConceptsSharingTheSameAsset(final TestNamespace assertEquals(topic.getId(), cluster.getAssets().getFirst().getAsset().getId()); assertNull(cluster.getAfter()); } - assertEquals(List.of(500L, 1L), observed.bindingRows()); + assertEquals(List.of(500L, 1L, 0L), observed.bindingRows()); observed.assertBounded(); } finally { concepts.forEach( diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java index 117a95ab9a8f..d86d87b4e54d 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java @@ -15,6 +15,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.openmetadata.it.tests.NativeOntologyGraphScanProbe.fewestReads; import static org.openmetadata.it.tests.NativeOntologyPageFixtures.clusterPage; import static org.openmetadata.it.tests.NativeOntologyPageFixtures.graphPage; import static org.openmetadata.it.tests.OntologyBindingFixtures.assertionRequest; @@ -31,11 +33,13 @@ import static org.openmetadata.it.tests.OntologyMappingFixtures.put; import static org.openmetadata.it.tests.OntologyMappingFixtures.table; +import java.net.URI; import java.util.Comparator; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.RdfAccessFixtures; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; @@ -63,6 +67,8 @@ import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.service.Entity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The records of each class and the links of each relation on {@code GET /dataGraph} and on {@code @@ -71,12 +77,13 @@ */ @ExtendWith(TestNamespaceExtension.class) class NativeOntologyDataGraphCountIT extends BaseOntologyApprovalIT { + private static final Logger LOG = LoggerFactory.getLogger(NativeOntologyDataGraphCountIT.class); private static final long PROFILED_AT = 1_700_000_000_000L; private static final double MISLEADING_ROW_COUNT = 999d; @Test void anUnfilteredClassAndItsConfirmedRelationCountFromTheStoredProfiles(final TestNamespace ns) { - final World world = world(ns, OntologyJoinStatus.CONFIRMED, false, false); + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, false, false); final var expected = world.expected(exact(100), exact(50), exact(90), true, true); assertAllEndpoints(admin(), world, expected); @@ -84,7 +91,7 @@ void anUnfilteredClassAndItsConfirmedRelationCountFromTheStoredProfiles(final Te @Test void aFilteredClassAndTheRelationFromItCountNothing(final TestNamespace ns) { - final World world = world(ns, OntologyJoinStatus.CONFIRMED, true, false); + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, true, false); final var expected = world.expected( @@ -95,7 +102,7 @@ void aFilteredClassAndTheRelationFromItCountNothing(final TestNamespace ns) { @Test void aRelationHeldByALinkTableCountsNothingAndItsClassStillCountsItsRecords( final TestNamespace ns) { - final World world = world(ns, OntologyJoinStatus.CONFIRMED, false, true); + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, false, true); final var expected = world.expectedWithLinkTable(exact(100), exact(50), state(State.NOT_DERIVABLE)); @@ -104,7 +111,7 @@ void aRelationHeldByALinkTableCountsNothingAndItsClassStillCountsItsRecords( @Test void aJoinThatIsOnlyInferredIsNotConfirmed(final TestNamespace ns) { - final World world = world(ns, OntologyJoinStatus.INFERRED, false, false); + final World world = world(ns, "counts", OntologyJoinStatus.INFERRED, false, false); final var expected = world.expected(exact(100), exact(50), state(State.JOIN_NOT_CONFIRMED), true, true); @@ -113,7 +120,7 @@ void aJoinThatIsOnlyInferredIsNotConfirmed(final TestNamespace ns) { @Test void aReaderWithoutTheDataProfileRightSeesNoProfileInsteadOfACount(final TestNamespace ns) { - final World world = world(ns, OntologyJoinStatus.CONFIRMED, false, false); + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, false, false); try (var fixtures = new RdfAccessFixtures("countDenied" + ns.shortPrefix())) { final var denied = fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE); final OpenMetadataClient reader = @@ -133,7 +140,7 @@ void aReaderWithoutTheDataProfileRightSeesNoProfileInsteadOfACount(final TestNam @Test void aReaderWhoMayNotViewTheIdentityTableSeesItHiddenAndLearnsNothingMore( final TestNamespace ns) { - final World world = world(ns, OntologyJoinStatus.CONFIRMED, false, false); + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, false, false); final Table notes = table(world.schema(), ns.prefix("order_notes"), column("order_id", ColumnDataType.BIGINT)); put(admin(), world.order(), binding(notes, OntologyBindingRole.CONTRIBUTING, "order_id"), 1L); @@ -149,6 +156,60 @@ void aReaderWhoMayNotViewTheIdentityTableSeesItHiddenAndLearnsNothingMore( } } + @Test + void theStatementsOfAReadDoNotGrowWithTheClassesAndRelations(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Counts the embedded server's SQL statements"); + final World narrow = world(ns, "narrow", OntologyJoinStatus.CONFIRMED, false, false); + final World wide = world(ns, "wide", OntologyJoinStatus.CONFIRMED, false, false); + for (int index = 0; index < 8; index++) { + relatedClass(ns, wide, index); + } + + final int narrowReads = fewestReads(admin(), narrow.ontology()); + final int wideReads = fewestReads(admin(), wide.ontology()); + + LOG.info( + "Graph read SQL statements with counts: 2 classes={}, 10 classes={}", + narrowReads, + wideReads); + assertEquals(narrowReads, wideReads); + } + + /** A class over a table of its own, with a relation to the customers. */ + private static void relatedClass(final TestNamespace ns, final World world, final int index) { + final URI iri = URI.create("urn:Extra" + index); + final OntologyConcept extra = declareClass(world.ontology(), "Extra" + index, iri); + final OntologyProperty relation = + objectProperty(world.ontology(), "relatesTo" + index, extra, world.customer()); + admin() + .ontologyAxioms() + .create( + assertionRequest( + world.ontology(), iri, OntologyBindingFixtures.CUSTOMER, "extra" + index) + .withPropertyIri(relation.getIri())); + final Table extras = + table( + world.schema(), + ns.prefix("extra" + index), + column("id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + put( + admin(), + extra, + binding(extras, OntologyBindingRole.IDENTITY, "id") + .withColumns( + List.of( + column(relation, "customer_id") + .withJoin( + join( + world.customers(), + OntologyJoinStatus.CONFIRMED, + "customer_id", + "id")))), + 0L); + profile(extras, columnProfile("id", 10, 0, 10), columnProfile("customer_id", 10, 0, 5)); + } + private static void assertAllEndpoints( final OpenMetadataClient caller, final World world, final NativeOntologyDataGraph expected) { final NativeOntologyDataGraph graph = graph(caller, world.ontology(), "?limit=12"); @@ -174,10 +235,11 @@ private static NativeOntologyCount state(final State state) { /** Customers and orders, with a profile for each that covered the whole table. */ private static World world( final TestNamespace ns, + final String name, final OntologyJoinStatus status, final boolean filteredOrders, final boolean joinOnLinkTable) { - final Ontology ontology = createOntology(ns, "counts"); + final Ontology ontology = createOntology(ns, name); final OntologyConcept order = declareClass(ontology, "Order", OntologyBindingFixtures.ORDER); final OntologyConcept customer = declareClass(ontology, "Customer", OntologyBindingFixtures.CUSTOMER); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java index ecab302873b5..5c2c3b3474e7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java @@ -203,7 +203,8 @@ List listFirstTablesForConcepts( /** * For each concept, its identity table row first and then its other table rows in asset id - * order, up to {@code perConcept} rows, in one statement. + * order, up to {@code perConcept} rows, in one statement. The statement carries a limit of {@code + * perConcept} rows for each concept asked about, which it can never reach. */ @SqlQuery( "SELECT " @@ -216,10 +217,12 @@ List listFirstTablesForConcepts( + "' THEN 0 ELSE 1 END ASC, assetId ASC) AS bindingOrder " + "FROM ontology_concept_binding WHERE conceptId IN () " + "AND assetType = 'table') ranked " - + "WHERE bindingOrder <= :perConcept ORDER BY conceptId ASC, assetId ASC") + + "WHERE bindingOrder <= :perConcept ORDER BY conceptId ASC, assetId ASC LIMIT :limit") @RegisterRowMapper(BindingRowMapper.class) List listIdentityFirstTablesForConcepts( - @BindList("conceptIds") List conceptIds, @Bind("perConcept") int perConcept); + @BindList("conceptIds") List conceptIds, + @Bind("perConcept") int perConcept, + @Bind("limit") int limit); /** The identity table rows of these concepts. A concept holds at most one live identity table. */ @SqlQuery( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 3f928b42148c..2ba914a67d6d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -4,6 +4,7 @@ import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import java.net.URI; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -240,15 +241,22 @@ public List firstTables(final Collection conceptIds, final int /** * The identity table row of each concept, when it has one, then its other table rows in asset id - * order, up to {@code perConcept} rows in all. One statement for all the concepts. + * order, up to {@code perConcept} rows in all. One statement reads up to {@link + * #SCAN_PAGE_SIZE} rows, so the concepts go in groups that keep it there, and a page of + * concepts is one statement. */ public List identityFirstTables( final Collection conceptIds, final int perConcept) { - return conceptIds.isEmpty() - ? List.of() - : dao.ontologyConceptBindingDAO() - .listIdentityFirstTablesForConcepts( - conceptIds.stream().map(UUID::toString).distinct().toList(), perConcept); + final List ids = conceptIds.stream().map(UUID::toString).distinct().toList(); + final int group = Math.max(1, SCAN_PAGE_SIZE / perConcept); + final List rows = new ArrayList<>(); + for (int from = 0; from < ids.size(); from += group) { + final List chunk = ids.subList(from, Math.min(ids.size(), from + group)); + rows.addAll( + dao.ontologyConceptBindingDAO() + .listIdentityFirstTablesForConcepts(chunk, perConcept, chunk.size() * perConcept)); + } + return rows; } public List boundConcepts( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java index f751543f961a..3cfb5a28f5ba 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java @@ -50,10 +50,11 @@ final class OntologyCountRules { /** * The identity row first, then the other table rows of a class, at most {@value #ROWS_PER_CLASS} - * in all. The identity row alone makes the first read, so a class that binds more tables than - * this is read as far as it goes and is flagged {@link ClassRows#truncated()}. + * in all, so that the response of a page of classes is read with rows well inside one scan + * page. A class that binds more tables than that is read as far as it goes and is flagged + * {@link ClassRows#truncated()}. */ - static final int ROWS_PER_CLASS = OntologyMappingReader.MAX_CONTRIBUTING_TABLES + 2; + static final int ROWS_PER_CLASS = 5; /** * The engines that check a declared primary or unique key, so a duplicate row cannot exist From 6d44f4b2764a343e5bda1798ced17785f6b355c8 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 21:17:38 -0800 Subject: [PATCH 057/203] Check that earlier versions of a draft still hold its operations --- .../OntologyChangeSetEventDeliveryIT.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java index 3f892dd71bf6..7eb95f1fdb75 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java @@ -70,10 +70,27 @@ void aWebhookOnEveryResourceReceivesNoOperationsOfADraft(final TestNamespace ns) } assertTrue(OntologyDraftScene.read(scene).contains(scene.table().getId().toString())); assertTrue(OntologyDraftScene.read(scene).contains(OntologyDraftScene.VALUE)); - assertTrue(OntologyDraftScene.versions(scene).contains(scene.table().getId().toString())); + assertTrue(versionsHoldOperations(OntologyDraftScene.versions(scene), scene)); } } + /** A stored version is the content of the draft, so an earlier one still holds its operations. */ + private static boolean versionsHoldOperations( + final String versions, final OntologyDraftScene.Built scene) { + final List held = new java.util.ArrayList<>(); + JsonUtils.readTree(versions).path("versions").forEach(version -> held.add(version)); + return !held.isEmpty() + && held.stream() + .map(version -> version.isTextual() ? JsonUtils.readTree(version.asText()) : version) + .allMatch( + version -> + version.path("operations").size() > 0 + && version + .path("operations") + .toString() + .contains(scene.table().getId().toString())); + } + private static EventSubscription webhookOnEveryResource( final TestNamespace ns, final OpenMetadataClient creator, final RecordingReceiver receiver) { final CreateEventSubscription request = From 547f10f91dc54978a5203ea8ee07e1cdbac14538 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 21:37:24 -0800 Subject: [PATCH 058/203] Expect no operations in the stored events of a draft --- .../it/tests/OntologyChangeSetEvidenceIT.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java index 268268af7299..32e839e846cf 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java @@ -270,14 +270,10 @@ void noRecordedChangeAndNoStoredChangeEventCarriesTheEvidenceOfADraft(final Test final List events = storedEvents(draft, CREATED, UPDATED, APPLIED); for (final String event : events) { assertFalse(event.contains(customers.getId().toString()), event); - for (final JsonNode operation : storedOperations(event)) { - assertFalse(operation.has("evidence"), event); - assertFalse(operation.has("withheldEvidenceCount"), event); - } + assertTrue(storedOperations(event).isMissingNode(), event); } - for (final String type : List.of(CREATED, APPLIED)) { - final JsonNode operations = storedOperations(ofType(events, type).getFirst()); - assertEquals(supported.getId().toString(), operations.path(0).path("id").asText(), type); + for (final String type : List.of(CREATED, UPDATED, APPLIED)) { + assertFalse(ofType(events, type).isEmpty(), type); } assertEquals(named, applied.getOperations().getFirst().getEvidence()); assertEquals(named, read(admin(), draft).getOperations().getFirst().getEvidence()); From 637e99937cb9a0f5c91b86c415d2deced674c4ff Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 21:58:43 -0800 Subject: [PATCH 059/203] Count the links of a relation in the aggregate statement The aggregate request takes a measure. With linkCount and a relation it returns one number: the distinct pairs of a start record key and a related key along the confirmed join, where a related key counts when no part of it is null, whether or not a record holds it. The plan names the measure. Goldens and unit tests cover six mappings of a relation. --- ...tatements-start-from-the-identity-table.md | 44 +- .../ontology/OntologyConceptSqlGenerator.java | 71 +++- .../service/ontology/OntologySelectText.java | 5 + .../ontology/OntologyStatementService.java | 18 +- .../OntologyAggregateStatementTest.java | 156 +++++++ .../service/ontology/OntologyLinkShapes.java | 391 ++++++++++++++++++ .../ontology/OntologyMappingShapeModel.java | 15 +- .../ontology/OntologyMappingShapes.java | 51 ++- .../ontology/OntologyStatementGoldenTest.java | 4 +- .../ontology/OntologyStatementGoldens.java | 9 +- .../bigquery/linkColumn-links-forward.sql | 7 + .../bigquery/linkColumn-links-inverse.sql | 8 + .../linkCompositeKey-links-forward.sql | 8 + .../linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../linkFilteredStart-links-forward.sql | 8 + .../linkFilteredStart-links-inverse.sql | 9 + .../bigquery/linkLinkTable-links-forward.sql | 8 + .../bigquery/linkLinkTable-links-inverse.sql | 8 + .../clickhouse/linkColumn-links-forward.sql | 7 + .../clickhouse/linkColumn-links-inverse.sql | 8 + .../linkCompositeKey-links-forward.sql | 8 + .../linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../linkFilteredStart-links-forward.sql | 8 + .../linkFilteredStart-links-inverse.sql | 9 + .../linkLinkTable-links-forward.sql | 8 + .../linkLinkTable-links-inverse.sql | 8 + .../mysql/linkColumn-links-forward.sql | 7 + .../mysql/linkColumn-links-inverse.sql | 8 + .../mysql/linkCompositeKey-links-forward.sql | 8 + .../mysql/linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../mysql/linkFilteredStart-links-forward.sql | 8 + .../mysql/linkFilteredStart-links-inverse.sql | 9 + .../mysql/linkLinkTable-links-forward.sql | 8 + .../mysql/linkLinkTable-links-inverse.sql | 8 + .../postgres/linkColumn-links-forward.sql | 7 + .../postgres/linkColumn-links-inverse.sql | 8 + .../linkCompositeKey-links-forward.sql | 8 + .../linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../linkFilteredStart-links-forward.sql | 8 + .../linkFilteredStart-links-inverse.sql | 9 + .../postgres/linkLinkTable-links-forward.sql | 8 + .../postgres/linkLinkTable-links-inverse.sql | 8 + .../redshift/linkColumn-links-forward.sql | 7 + .../redshift/linkColumn-links-inverse.sql | 8 + .../linkCompositeKey-links-forward.sql | 8 + .../linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../linkFilteredStart-links-forward.sql | 8 + .../linkFilteredStart-links-inverse.sql | 9 + .../redshift/linkLinkTable-links-forward.sql | 8 + .../redshift/linkLinkTable-links-inverse.sql | 8 + .../snowflake/linkColumn-links-forward.sql | 7 + .../snowflake/linkColumn-links-inverse.sql | 8 + .../linkCompositeKey-links-forward.sql | 8 + .../linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../linkFilteredStart-links-forward.sql | 8 + .../linkFilteredStart-links-inverse.sql | 9 + .../snowflake/linkLinkTable-links-forward.sql | 8 + .../snowflake/linkLinkTable-links-inverse.sql | 8 + .../spark/linkColumn-links-forward.sql | 7 + .../spark/linkColumn-links-inverse.sql | 8 + .../spark/linkCompositeKey-links-forward.sql | 8 + .../spark/linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../spark/linkFilteredStart-links-forward.sql | 8 + .../spark/linkFilteredStart-links-inverse.sql | 9 + .../spark/linkLinkTable-links-forward.sql | 8 + .../spark/linkLinkTable-links-inverse.sql | 8 + .../trino/linkColumn-links-forward.sql | 7 + .../trino/linkColumn-links-inverse.sql | 8 + .../trino/linkCompositeKey-links-forward.sql | 8 + .../trino/linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../trino/linkFilteredStart-links-forward.sql | 8 + .../trino/linkFilteredStart-links-inverse.sql | 9 + .../trino/linkLinkTable-links-forward.sql | 8 + .../trino/linkLinkTable-links-inverse.sql | 8 + .../tsql/linkColumn-links-forward.sql | 7 + .../tsql/linkColumn-links-inverse.sql | 8 + .../tsql/linkCompositeKey-links-forward.sql | 8 + .../tsql/linkCompositeKey-links-inverse.sql | 9 + .../linkCompositeLinkTable-links-forward.sql | 9 + .../linkCompositeLinkTable-links-inverse.sql | 9 + .../linkFilteredLinkTable-links-forward.sql | 9 + .../linkFilteredLinkTable-links-inverse.sql | 8 + .../tsql/linkFilteredStart-links-forward.sql | 8 + .../tsql/linkFilteredStart-links-inverse.sql | 9 + .../tsql/linkLinkTable-links-forward.sql | 8 + .../tsql/linkLinkTable-links-inverse.sql | 8 + .../ontologyAggregateStatementRequest.json | 6 +- .../api/data/ontologyStatementPlan.json | 12 +- 120 files changed, 1650 insertions(+), 32 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md index ff930150e8f5..19f05161c85a 100644 --- a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -1,9 +1,9 @@ # A statement about the records of a class starts from its identity table - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial) +- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (the aggregate statement gains the link count of a relation) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyRecordStatementIT`, `OntologyStatementRefusalIT`, `OntologyStatementReleaseDeleteIT`, `OntologyStatementValueIT`, `OntologyConceptQueryIT` +- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyLinkCountIT`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyRecordStatementIT`, `OntologyStatementRefusalIT`, `OntologyStatementReleaseDeleteIT`, `OntologyStatementValueIT`, `OntologyConceptQueryIT` - **Related:** ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles and the subject key that a statement reads), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (amended by this record), ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension (three of its rules are replaced here), ADR:2026-11-21-a-class-has-at-most-one-display-name-property ## Context @@ -173,3 +173,43 @@ on it is a 404 when no working row is left, and a 409 that the class has no iden request still names a class that the release holds. Both are right, because bindings sit outside versions. A request for a deleted class that names an ontology which is itself deleted is a 404, checked before the right to the class, since the ontology comes from the working row. + +## Amendment v2: the aggregate statement counts the links of a relation + +A client that needs one number, how many links a relation has between the records of two classes, +had only the class count and the 8 records with the most links. The request of `/aggregate` +gains `measure`, one of `topRecords`, which is the default and the answer it always gave, and +`linkCount`. A measure belongs to a relation. `linkCount` needs a relation and a direction, as +`topRecords` does, and a class count that names any measure is a 400. The plan names the measure of +an aggregate over a relation, the binding revision of both classes, and one column of the kind +`count`. + +**The link count is the number of distinct pairs of a start record key and a related key along the +confirmed join.** The statement returns one row with one column. + +- A start record is a row of the identity table of the start class that passes its row filter and + has no null in any part of its subject key. +- A related key is the value of the columns that hold the join. A forward path reads it from the + table that holds the join, which is the start table or a link table. An inverse path reads it + from the subject key of the class that binds the relation, which is that class's identity table + when it holds the join, or the columns of the link table that pair with that key. A related key + counts when no part of it is null. +- A related key counts whether or not a record of the related class holds it. The statement never + joins the identity table of the related class to prove that a record exists, and the row filter + of the related class never applies. A stored profile counts a reference in the same way, so the + two counts agree on the same rows. The row filter of a link table applies, because it says which + rows of that table are links. +- Two rows that give one pair count once, so a link table that repeats a pair does not count it + twice. + +**The refusals are those of the records that relate to the most.** An inferred join or none is a +409, a table the reader may not view is a 403 that names the class, and the version rules are the +ones above. The count form has no `ORDER BY` and no row limit, and the plan gives `rowCap` 1. + +**A forward count and an inverse count of one relation can differ.** Forward, the start class holds +the join, so a reference to a key that no related row holds is counted. Inverse, the start class is +the one that a reference points to, so a reference to a key that no start record holds is not a pair +of a start record. A client that wants the links of the relation as a whole asks forward from the +class that binds it. + +Guard: `OntologyAggregateStatementTest`, `OntologyStatementGoldenTest` and `OntologyLinkCountIT`. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index 1865ad8e54f3..90f1254ac027 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -26,6 +26,7 @@ import java.util.function.Supplier; import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; import org.openmetadata.schema.api.data.OntologyStatementColumn; +import org.openmetadata.schema.api.data.OntologyStatementDirection; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.ontology.OntologyHopJoins.ColumnPair; @@ -68,6 +69,7 @@ public final class OntologyConceptSqlGenerator { + " table bindings"; private static final String FIRST = alias(0); private static final String COUNT = "COUNT(*) AS records"; + private static final String COUNT_LINKS = "COUNT(*) AS links"; private static final String INNER_JOIN = "JOIN"; private static final String LEFT_JOIN = "LEFT JOIN"; @@ -300,6 +302,56 @@ static RecordStatement top(final OntologyRelationPath path) { return draft.finished(TOP_RECORDS, false); } + /** + * The number of links of a relation in one row: the distinct pairs of a start record key and a + * related key along the join the path follows. A start record passes the row filter of its + * identity table and holds no null key part. A related key is the value of the columns that hold + * the join, so it counts when no part of it is null, whether or not a record of the related + * class holds it. The row filter of the related class never applies, and its identity table is + * read only when it holds the join itself. The statement has no {@code ORDER BY} and no row + * limit. + * + *

    A forward path reads the related key from the columns of the table that holds the join, + * the start table or the link table. An inverse path reads it from the key of the class that + * binds the relation: its identity table when that table holds the join, or the columns of the + * link table that pair with that key. The row filter of a link table applies, because it says + * which rows of that table are links. + */ + static RecordStatement links(final OntologyRelationPath path) { + final MappedTable identity = path.start().identity(); + final List joins = path.joins(); + final Joined last = joins.getLast(); + final boolean namesKeyOnly = + path.direction() == OntologyStatementDirection.FORWARD || joins.size() > 1; + final List read = namesKeyOnly ? joins.subList(0, joins.size() - 1) : joins; + final String relatedAlias = alias(read.size()); + final List> related = + namesKeyOnly + ? last.on().stream().map(JoinPair::previous).toList() + : last.table().keyPaths(); + final Draft draft = new Draft(identity); + draft.list.count(path.related()); + draft.select.selectAll().sql(COUNT_LINKS); + final OntologySelectText keys = draft.select.fromDistinct(draft.family.dialect()); + final List> start = identity.keyPaths(); + for (int part = 0; part < start.size(); part++) { + draft.sql.sql(part == 0 ? "" : ", ").column(FIRST, start.get(part)).sql(" AS k" + part); + } + for (int part = 0; part < related.size(); part++) { + draft.sql.sql(", ").column(relatedAlias, related.get(part)).sql(" AS r" + part); + } + chain(draft, keys, path.start(), read); + keyIsSet(keys, identity, FIRST); + rowFilter(keys, identity, FIRST); + related.forEach(part -> keys.where().column(relatedAlias, part).sql(" IS NOT NULL")); + final int filtered = namesKeyOnly ? read.size() : read.size() - 1; + for (int index = 0; index < filtered; index++) { + rowFilter(keys, read.get(index).table(), alias(index + 1)); + } + draft.select.closeDerived("k"); + return draft.finished(1, false); + } + /** * Text with no uppercase letter matches without regard to case. Text with an uppercase letter * matches as written, because the text reaches the statement only as the pattern that {@link @@ -341,12 +393,21 @@ private static void leftJoin( /** The start table, then one inner join for each table of the path. */ private static void chain(final Draft draft, final OntologyRelationPath path) { - draft.select.from(path.start().identity().fullyQualifiedName(), FIRST); - for (int index = 0; index < path.joins().size(); index++) { - final Joined joined = path.joins().get(index); - requireSameDatabase(path.start(), joined.table()); + chain(draft, draft.select, path.start(), path.joins()); + } + + /** The start table, then one inner join for each of {@code joins}, written by {@code select}. */ + private static void chain( + final Draft draft, + final OntologySelectText select, + final MappedClass start, + final List joins) { + select.from(start.identity().fullyQualifiedName(), FIRST); + for (int index = 0; index < joins.size(); index++) { + final Joined joined = joins.get(index); + requireSameDatabase(start, joined.table()); equalColumns( - draft.select.join(INNER_JOIN, joined.table().fullyQualifiedName(), alias(index + 1)), + select.join(INNER_JOIN, joined.table().fullyQualifiedName(), alias(index + 1)), joined.on(), alias(index), alias(index + 1)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java index b367f69235e5..f74bc889fa05 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java @@ -48,6 +48,11 @@ TypedStatement.Builder select(final int limit) { return sql.sql(limitsWithTop ? "SELECT TOP " + limit + " " : "SELECT "); } + /** {@code SELECT} with no row limit, ready for its list. */ + TypedStatement.Builder selectAll() { + return sql.sql("SELECT "); + } + /** * Opens a derived table after {@code FROM} and returns the writer of the SELECT inside it, whose * lines are indented. That SELECT is {@code DISTINCT} and carries no row limit. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java index 8b1040e3fecc..243deee42823 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java @@ -36,6 +36,7 @@ import org.openmetadata.schema.api.data.OntologyStatementDirection; import org.openmetadata.schema.api.data.OntologyStatementEngineFamily; import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementMeasure; import org.openmetadata.schema.api.data.OntologyStatementPlan; import org.openmetadata.schema.api.data.OntologyStatementRelation; import org.openmetadata.schema.api.data.OntologyStatementVersion; @@ -81,6 +82,8 @@ public final class OntologyStatementService { private static final String CLASS = "Class"; private static final String RELATION = "Relation"; + private static final String MEASURE_OF_A_RELATION = + "A measure belongs to a relation. A count of the class takes no measure"; private static final String RELATION_OR_COUNT = "An aggregate over a relation takes the relation and the direction together. A count of the" + " class takes neither, and no related class"; @@ -219,7 +222,8 @@ public OntologyStatementPlan expand( /** * The number of records of the class when the request names no relation. With a relation and a - * direction, the records of the class that relate to the most records along it. + * direction, the records of the class that relate to the most records along it, or with the + * measure {@code linkCount} the number of links of the relation. */ public OntologyStatementPlan aggregate( final Access access, final UUID classId, final OntologyAggregateStatementRequest request) { @@ -233,6 +237,9 @@ public OntologyStatementPlan aggregate( if (!overRelation && !overClass) { throw new BadRequestException(RELATION_OR_COUNT); } + if (overClass && asked.getMeasure() != null) { + throw new BadRequestException(MEASURE_OF_A_RELATION); + } try (final var ignored = FreshReadScope.enter()) { final Subject subject = subject(access, classId, asked.getVersion()); return overRelation ? top(access, subject, asked) : count(access, subject); @@ -256,8 +263,15 @@ private OntologyStatementPlan top( access, start, new Along(asked.getRelation(), asked.getDirection(), asked.getRelatedClass())); - return plan(OntologyStatementKind.AGGREGATE, OntologyConceptSqlGenerator.top(route.path())) + final boolean links = asked.getMeasure() == OntologyStatementMeasure.LINK_COUNT; + return plan( + OntologyStatementKind.AGGREGATE, + links + ? OntologyConceptSqlGenerator.links(route.path()) + : OntologyConceptSqlGenerator.top(route.path())) .withRelation(route.relation()) + .withMeasure( + links ? OntologyStatementMeasure.LINK_COUNT : OntologyStatementMeasure.TOP_RECORDS) .withVersion(start.version().read()) .withBindingRevisions(route.revisions()); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java index 0ee7af29d7a9..ef062169e048 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java @@ -134,6 +134,162 @@ void aRelationCountFollowsOnlyTheJoinThatExpandFollows() { refused.getMessage()); } + @Test + void aLinkCountOverAColumnCountsTheDistinctPairsOfAStartKeyAndTheColumnThatHoldsTheJoin() { + final RecordStatement links = + OntologyConceptSqlGenerator.links( + model(COLUMN_RELATION, "Mysql").path("Order", "placedBy", FORWARD)); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0\n" + + " FROM `shop`.`orders` t0\n" + + " WHERE t0.`id` IS NOT NULL\n" + + " AND t0.`customer_id` IS NOT NULL\n) k", + sql(links)); + assertEquals(List.of("0 count Customer"), plan(links)); + assertEquals(List.of("orders"), read(links)); + assertEquals(1, links.rowCap()); + assertFalse(links.extraRow()); + } + + @Test + void aLinkCountGoingBackJoinsTheClassThatHoldsTheColumnAndReadsItsKey() { + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t1.id AS r0\n" + + " FROM shop.customers t0\n" + + " JOIN shop.orders t1 ON t1.customer_id = t0.id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t1.id IS NOT NULL\n) k", + sql( + OntologyConceptSqlGenerator.links( + model(COLUMN_RELATION, POSTGRES).path("Customer", "placedBy", INVERSE)))); + } + + @Test + void aLinkCountNeverReadsTheTableOfTheRelatedClassWhenALinkTableHoldsTheJoin() { + final RecordStatement forward = + OntologyConceptSqlGenerator.links( + model(LINK_TABLE, POSTGRES).path("Order", "contains", FORWARD)); + final RecordStatement inverse = + OntologyConceptSqlGenerator.links( + model(LINK_TABLE, POSTGRES).path("Product", "contains", INVERSE)); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0\n" + + " FROM shop.orders t0\n" + + " JOIN shop.order_items t1 ON t1.order_id = t0.id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t1.product_sku IS NOT NULL\n) k", + sql(forward)); + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0\n" + + " FROM shop.products t0\n" + + " JOIN shop.order_items t1 ON t1.product_sku = t0.sku\n" + + " WHERE t0.sku IS NOT NULL\n" + + " AND t1.order_id IS NOT NULL\n) k", + sql(inverse)); + assertEquals(List.of("orders", "order_items"), read(forward)); + assertEquals(List.of("products", "order_items"), read(inverse)); + assertEquals(List.of("0 count Product"), plan(forward)); + assertEquals(List.of("0 count Order"), plan(inverse)); + } + + @Test + void aLinkCountKeepsTheRowFilterOfTheStartClassAndOfALinkTableButNotOfTheRelatedClass() { + final OntologyMappingShapeModel filtered = + OntologyExpandStatementTest.filteredLinkTable("Mssql"); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS r0\n" + + " FROM [shop].[orders] t0\n" + + " JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id]\n" + + " WHERE t0.[id] IS NOT NULL\n" + + " AND t0.[channel] = N'web'\n" + + " AND t1.[product_sku] IS NOT NULL\n" + + " AND t1.[quantity] > 0\n) k", + sql(OntologyConceptSqlGenerator.links(filtered.path("Order", "contains", FORWARD)))); + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.[sku] AS k0, t1.[order_id] AS r0\n" + + " FROM [shop].[products] t0\n" + + " JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku]\n" + + " WHERE t0.[sku] IS NOT NULL\n" + + " AND t0.[title] <> N'Drill'\n" + + " AND t1.[order_id] IS NOT NULL\n" + + " AND t1.[quantity] > 0\n) k", + sql(OntologyConceptSqlGenerator.links(filtered.path("Product", "contains", INVERSE)))); + } + + @Test + void aLinkCountOverATwoColumnJoinNeedsEachColumnToBeSet() { + final OntologyMappingShapeModel branches = + new OntologyMappingShapeModel(OntologyLinkShapes.COMPOSITE_KEY, POSTGRES); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t0.tenant AS r0, t0.branch AS r1\n" + + " FROM shop.employees t0\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t0.tenant IS NOT NULL\n" + + " AND t0.branch IS NOT NULL\n) k", + sql(OntologyConceptSqlGenerator.links(branches.path("Employee", "worksAt", FORWARD)))); + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.tenant_id AS k0, t0.branch_id AS k1, t1.id AS r0\n" + + " FROM shop.branches t0\n" + + " JOIN shop.employees t1 ON t1.tenant = t0.tenant_id AND t1.branch = t0.branch_id\n" + + " WHERE t0.tenant_id IS NOT NULL\n" + + " AND t0.branch_id IS NOT NULL\n" + + " AND t1.id IS NOT NULL\n) k", + sql(OntologyConceptSqlGenerator.links(branches.path("Branch", "worksAt", INVERSE)))); + } + + @Test + void aLinkCountOverALinkTableOfATwoColumnKeyReadsBothPairedColumns() { + final OntologyMappingShapeModel lines = + new OntologyMappingShapeModel(OntologyLinkShapes.COMPOSITE_LINK_TABLE, POSTGRES); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.sku AS k0, t1.tenant AS r0, t1.order_no AS r1\n" + + " FROM shop.products t0\n" + + " JOIN shop.order_lines t1 ON t1.sku = t0.sku\n" + + " WHERE t0.sku IS NOT NULL\n" + + " AND t1.tenant IS NOT NULL\n" + + " AND t1.order_no IS NOT NULL\n) k", + sql(OntologyConceptSqlGenerator.links(lines.path("Product", "contains", INVERSE)))); + } + + @Test + void aLinkCountIsRefusedLikeTheRecordsThatRelateToTheMost() { + final OntologyMappingShapeModel missing = model(LINK_TABLE, POSTGRES).delete("order_items"); + final OntologyMappingShapeModel hidden = model(COLUMN_RELATION, POSTGRES).hide("customers"); + + final ClientErrorException noJoin = + assertThrows( + ClientErrorException.class, + () -> OntologyConceptSqlGenerator.links(missing.path("Order", "contains", FORWARD))); + + assertEquals(409, noJoin.getResponse().getStatus()); + assertEquals( + "Relation https://example.org/linkTable#contains has no join from class" + + " https://example.org/linkTable#Order to the identity table of class" + + " https://example.org/linkTable#Product", + noJoin.getMessage()); + assertEquals( + "The identity table of class https://example.org/columnRelation#Customer is not visible" + + " to you", + assertThrows( + AuthorizationException.class, + () -> OntologyConceptSqlGenerator.links(hidden.path("Order", "placedBy", FORWARD))) + .getMessage()); + } + private static OntologyMappingShapeModel model(final Shape shape, final String serviceType) { return new OntologyMappingShapeModel(shape, serviceType); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java new file mode 100644 index 000000000000..7d15613a749e --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java @@ -0,0 +1,391 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.service.ontology.OntologyMappingShapes.columns; +import static org.openmetadata.service.ontology.OntologyMappingShapes.contributing; +import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; +import static org.openmetadata.service.ontology.OntologyMappingShapes.joined; +import static org.openmetadata.service.ontology.OntologyMappingShapes.relation; +import static org.openmetadata.service.ontology.OntologyMappingShapes.row; +import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; + +import java.util.List; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementMeasure; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Six mappings of one relation, each with the two link counts of its relation, one for each + * direction. Their tables hold the rows that a link count must treat each in its own way: a + * related key with a null part, a pair stored twice, a start row the row filter excludes, a key + * that no related row holds, and a link table that repeats a pair. Each count is a literal that a + * person worked out from the rows. + * + *

    These mappings are separate from {@link OntologyMappingShapes#all()} because their rows + * would change the rows that the other statements of those shapes return. + */ +public final class OntologyLinkShapes { + private static final List LINKS_TO_CUSTOMER = columns("count Customer"); + private static final List LINKS_TO_ORDER = columns("count Order"); + private static final List LINKS_TO_PRODUCT = columns("count Product"); + private static final List LINKS_TO_BRANCH = columns("count Branch"); + private static final List LINKS_TO_EMPLOYEE = columns("count Employee"); + private static final List LINKS_TO_ORGANIZATION = columns("count Organization"); + private static final List LINKS_TO_PERSON = columns("count Person"); + + private OntologyLinkShapes() {} + + /** + * 1. A relation held in a column of an unfiltered identity table. Order 3 is stored twice, order + * 4 names no customer, order 5 names a customer that no row holds, and one row has no id. + * + *

    Forward, the pairs are (1,1), (2,1), (3,2) and (5,9). Inverse, they are customer 1 with + * orders 1 and 2, and customer 2 with order 3, since customer 9 is no start record and the row + * with no id has no related key. + */ + public static final Shape COLUMN = + new Shape( + "linkColumn", + List.of( + table( + "customers", + List.of(integer("id"), text("name")), + row(1, "Ada Lovelace"), + row(2, "Grace Hopper"), + row(3, "Alan Turing")), + table( + "orders", + List.of(integer("id"), integer("customer_id")), + row(1, 1), + row(2, 1), + row(3, 2), + row(3, 2), + row(4, null), + row(5, 9), + row(null, 1))), + List.of("Order", "Customer"), + List.of(relation("placedBy", "Order", "Customer")), + List.of( + identity("Customer", "customers", List.of("id"), null), + identity( + "Order", + "orders", + List.of("id"), + null, + joined("placedBy", "customer_id", "customers", "id"))), + both("Order", "Customer", "placedBy", LINKS_TO_CUSTOMER, 4, LINKS_TO_ORDER, 3)); + + /** + * 2. Two classes over one table, each with a row filter. A person works for an organization, and + * the relation is held in the column {@code employer_id}. Person 1 is stored twice, person 3 has + * no employer, person 4 names an employer that no row holds, person 6 names a vendor that is no + * organization, and the vendor row 5 is no person. + * + *

    Forward, the pairs are (1,10), (2,10), (4,99) and (6,11). Inverse, only organization 10 is + * a start record, and the related key is the key of each row that names it, whatever its kind: + * persons 1 and 2 and vendor 5. + */ + public static final Shape FILTERED_START = + new Shape( + "linkFilteredStart", + List.of( + table( + "parties", + List.of(integer("id"), text("kind"), text("name"), integer("employer_id")), + row(1, "person", "Ada Lovelace", 10), + row(1, "person", "Ada Lovelace", 10), + row(2, "person", "Grace Hopper", 10), + row(3, "person", "Alan Turing", null), + row(4, "person", "Edsger Dijkstra", 99), + row(5, "vendor", "Initech", 10), + row(6, "person", "Barbara Liskov", 11), + row(10, "organization", "Acme", null), + row(11, "vendor", "Globex", null))), + List.of("Person", "Organization"), + List.of(relation("worksFor", "Person", "Organization")), + List.of( + identity( + "Person", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person"), + joined("worksFor", "employer_id", "parties", "id")), + identity( + "Organization", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "organization"))), + both("Person", "Organization", "worksFor", LINKS_TO_ORGANIZATION, 4, LINKS_TO_PERSON, 3)); + + /** + * 3. A relation held in two columns, with a key of two columns at its far end. Employee 4 has no + * tenant, employee 5 has no branch, employee 6 names a branch that no row holds, employee 1 is + * stored twice, and one row has no id. + * + *

    Forward, the pairs are (1,eu,1), (2,eu,1), (3,us,1) and (6,eu,7). Inverse, they are branch + * (eu,1) with employees 1 and 2, and branch (us,1) with employee 3. + */ + public static final Shape COMPOSITE_KEY = + new Shape( + "linkCompositeKey", + List.of( + table( + "branches", + List.of(text("tenant_id"), integer("branch_id"), text("name")), + row("eu", 1, "Berlin"), + row("eu", 2, "Paris"), + row("us", 1, "Austin")), + table( + "employees", + List.of(integer("id"), text("tenant"), integer("branch")), + row(1, "eu", 1), + row(1, "eu", 1), + row(2, "eu", 1), + row(3, "us", 1), + row(4, null, 1), + row(5, "eu", null), + row(6, "eu", 7), + row(null, "eu", 1))), + List.of("Employee", "Branch"), + List.of(relation("worksAt", "Employee", "Branch")), + List.of( + identity("Branch", "branches", List.of("tenant_id", "branch_id"), null), + identity( + "Employee", + "employees", + List.of("id"), + null, + twoColumnJoin( + "worksAt", + "branches", + List.of("tenant", "branch"), + List.of("tenant_id", "branch_id")))), + both("Employee", "Branch", "worksAt", LINKS_TO_BRANCH, 4, LINKS_TO_EMPLOYEE, 3)); + + /** + * 4. A relation held in a link table that repeats a pair. Order 1 holds product A-1 twice, one + * row has no order, one has no product, and order 3 names a product that no row holds. + * + *

    Forward, the pairs are (1,A-1), (1,B-2), (2,A-1) and (3,Z-9). Inverse, they are product A-1 + * with orders 1 and 2, and product B-2 with order 1. + */ + public static final Shape LINK_TABLE = + new Shape( + "linkLinkTable", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "store"), + row(3, "web")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt"), + row("C-3", "Crate"), + row("D-4", "Drill")), + table( + "order_items", + List.of(integer("order_id"), text("product_sku"), integer("quantity")), + row(1, "A-1", 2), + row(1, "A-1", 7), + row(1, "B-2", 1), + row(2, "A-1", 1), + row(null, "B-2", 1), + row(2, null, 3), + row(3, "Z-9", 1))), + List.of("Order", "Product"), + List.of(relation("contains", "Order", "Product")), + List.of( + identity("Order", "orders", List.of("id"), null), + identity("Product", "products", List.of("sku"), null), + contributing( + "Order", + "order_items", + List.of("order_id"), + joined("contains", "product_sku", "products", "sku"))), + both("Order", "Product", "contains", LINKS_TO_PRODUCT, 4, LINKS_TO_ORDER, 3)); + + /** + * 5. A link table whose class has a key of two columns, so the table pairs two columns with it. + * Line (eu,1,A-1) is stored twice, one line has no product, one names a product that no row + * holds, and one has no order number. + * + *

    Forward, the pairs are (eu,1,A-1), (eu,1,B-2), (eu,2,A-1) and (us,1,Q-0). Inverse, they + * are product A-1 with orders (eu,1) and (eu,2), and product B-2 with order (eu,1). + */ + public static final Shape COMPOSITE_LINK_TABLE = + new Shape( + "linkCompositeLinkTable", + List.of( + table( + "orders", + List.of(text("tenant"), integer("order_no"), text("channel")), + row("eu", 1, "web"), + row("eu", 2, "web"), + row("us", 1, "store")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt")), + table( + "order_lines", + List.of(text("tenant"), integer("order_no"), text("sku")), + row("eu", 1, "A-1"), + row("eu", 1, "A-1"), + row("eu", 1, "B-2"), + row("eu", 2, "A-1"), + row("us", 1, null), + row("us", 1, "Q-0"), + row("eu", null, "B-2"))), + List.of("Order", "Product"), + List.of(relation("contains", "Order", "Product")), + List.of( + identity("Order", "orders", List.of("tenant", "order_no"), null), + identity("Product", "products", List.of("sku"), null), + contributing( + "Order", + "order_lines", + List.of("tenant", "order_no"), + joined("contains", "sku", "products", "sku"))), + both("Order", "Product", "contains", LINKS_TO_PRODUCT, 4, LINKS_TO_ORDER, 3)); + + /** + * 6. A link table whose class holds a row filter. Order 2 is a store order that the filter + * excludes, and its line links product A-1. Order 3 holds Z-9 twice and one line with no product. + * + *

    Forward, the pairs are (1,A-1), (1,B-2) and (3,Z-9). Inverse, the filter of the order class + * does not apply, so they are product A-1 with orders 1 and 2, and product B-2 with order 1. + */ + public static final Shape FILTERED_LINK_TABLE = + new Shape( + "linkFilteredLinkTable", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "store"), + row(3, "web"), + row(4, "web")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt")), + table( + "order_items", + List.of(integer("order_id"), text("product_sku")), + row(1, "A-1"), + row(1, "B-2"), + row(2, "A-1"), + row(3, null), + row(3, "Z-9"), + row(3, "Z-9"))), + List.of("Order", "Product"), + List.of(relation("contains", "Order", "Product")), + List.of( + identity( + "Order", + "orders", + List.of("id"), + new FilterSpec("channel", OntologyRowFilterOperator.EQUALS, "web")), + identity("Product", "products", List.of("sku"), null), + contributing( + "Order", + "order_items", + List.of("order_id"), + joined("contains", "product_sku", "products", "sku"))), + both("Order", "Product", "contains", LINKS_TO_PRODUCT, 3, LINKS_TO_ORDER, 3)); + + public static List all() { + return List.of( + COLUMN, + FILTERED_START, + COMPOSITE_KEY, + LINK_TABLE, + COMPOSITE_LINK_TABLE, + FILTERED_LINK_TABLE); + } + + /** The link count of a relation from the class that binds it, and from the class it reaches. */ + private static List both( + final String subject, + final String object, + final String relation, + final List forwardColumns, + final int forward, + final List inverseColumns, + final int inverse) { + return List.of( + links( + "links-forward", + subject, + relation, + OntologyStatementDirection.FORWARD, + forwardColumns, + forward), + links( + "links-inverse", + object, + relation, + OntologyStatementDirection.INVERSE, + inverseColumns, + inverse)); + } + + private static Ask links( + final String name, + final String type, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final int count) { + return new Ask( + name, + OntologyStatementKind.AGGREGATE, + type, + null, + null, + relation, + direction, + columns, + List.of(List.of(String.valueOf(count))), + OntologyStatementMeasure.LINK_COUNT); + } + + private static ColumnBindingSpec twoColumnJoin( + final String property, + final String target, + final List child, + final List parent) { + return new ColumnBindingSpec( + property, + child.getFirst(), + new JoinSpec(target, OntologyJoinStatus.CONFIRMED, child, parent)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java index 92e605f5b667..cf6c44a0e91c 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java @@ -27,6 +27,7 @@ import java.util.stream.IntStream; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementMeasure; import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.Table; @@ -131,12 +132,20 @@ RecordStatement statement(final Ask ask) { mapped(ask.type()), contributing(ask.type()), ask.key()); case EXPAND -> OntologyConceptSqlGenerator.expand( path(ask.type(), ask.relation(), ask.direction()), ask.key()); - case AGGREGATE -> ask.relation() == null - ? OntologyConceptSqlGenerator.count(mapped(ask.type())) - : OntologyConceptSqlGenerator.top(path(ask.type(), ask.relation(), ask.direction())); + case AGGREGATE -> aggregate(ask); }; } + private RecordStatement aggregate(final Ask ask) { + if (ask.relation() == null) { + return OntologyConceptSqlGenerator.count(mapped(ask.type())); + } + final OntologyRelationPath path = path(ask.type(), ask.relation(), ask.direction()); + return ask.measure() == OntologyStatementMeasure.LINK_COUNT + ? OntologyConceptSqlGenerator.links(path) + : OntologyConceptSqlGenerator.top(path); + } + MappedClass mapped(final String type) { return new MappedClass( id(type), diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java index 660b64da7369..f16975bd38cb 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java @@ -24,6 +24,7 @@ import org.openmetadata.schema.api.data.OntologyStatementColumn; import org.openmetadata.schema.api.data.OntologyStatementDirection; import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementMeasure; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyJoinStatus; @@ -119,6 +120,7 @@ public record BindingSpec( * @param rows the rows the statement can return, each value as text. It returns all of them, or * as many as its row limit when there are more. Only the rows of a relation aggregate come * in a fixed order + * @param measure for an aggregate over a relation, what it counts, or null for the default */ public record Ask( String name, @@ -129,7 +131,27 @@ public record Ask( String relation, OntologyStatementDirection direction, List columns, - List> rows) {} + List> rows, + OntologyStatementMeasure measure) { + /** An ask that names no measure. */ + public Ask( + final String name, + final OntologyStatementKind kind, + final String type, + final String matchText, + final List key, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final List> rows) { + this(name, kind, type, matchText, key, relation, direction, columns, rows, null); + } + + /** The same ask with another measure. */ + public Ask withMeasure(final OntologyStatementMeasure counted) { + return new Ask(name, kind, type, matchText, key, relation, direction, columns, rows, counted); + } + } public record Shape( String name, @@ -631,47 +653,46 @@ private static List> orders() { return List.copyOf(rows); } - private static ColumnSpec integer(final String name) { + static ColumnSpec integer(final String name) { return new ColumnSpec(name, ColumnDataType.INT); } - private static ColumnSpec text(final String name) { + static ColumnSpec text(final String name) { return new ColumnSpec(name, ColumnDataType.VARCHAR); } - private static ColumnSpec decimal(final String name) { + static ColumnSpec decimal(final String name) { return new ColumnSpec(name, ColumnDataType.DECIMAL); } @SafeVarargs - private static TableSpec table( + static TableSpec table( final String name, final List columns, final List... rows) { return new TableSpec(name, columns, List.of(rows)); } /** A row that may hold nulls, which {@code List.of} refuses. */ - private static List row(final Object... values) { + static List row(final Object... values) { return Arrays.asList(values); } - private static List texts(final String... values) { + static List texts(final String... values) { return Arrays.asList(values); } - private static PropertySpec data( - final String name, final boolean displayName, final String domain) { + static PropertySpec data(final String name, final boolean displayName, final String domain) { return new PropertySpec(name, displayName, domain, null); } - private static PropertySpec relation(final String name, final String domain, final String range) { + static PropertySpec relation(final String name, final String domain, final String range) { return new PropertySpec(name, false, domain, range); } - private static ColumnBindingSpec bound(final String property, final String column) { + static ColumnBindingSpec bound(final String property, final String column) { return new ColumnBindingSpec(property, column, null); } - private static ColumnBindingSpec joined( + static ColumnBindingSpec joined( final String property, final String column, final String target, final String parent) { return new ColumnBindingSpec( property, @@ -679,7 +700,7 @@ private static ColumnBindingSpec joined( new JoinSpec(target, OntologyJoinStatus.CONFIRMED, List.of(column), List.of(parent))); } - private static BindingSpec identity( + static BindingSpec identity( final String type, final String table, final List key, @@ -689,7 +710,7 @@ private static BindingSpec identity( type, table, OntologyBindingRole.IDENTITY, key, filter, List.of(columns)); } - private static BindingSpec contributing( + static BindingSpec contributing( final String type, final String table, final List key, @@ -699,7 +720,7 @@ private static BindingSpec contributing( } /** The lines of a column plan, each with its index in front. */ - private static List columns(final String... held) { + static List columns(final String... held) { return IntStream.range(0, held.length).mapToObj(index -> index + " " + held[index]).toList(); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java index 5568bc390185..8725bd7f497b 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java @@ -31,12 +31,12 @@ /** * Holds every statement about records to the SQL text that a person read and committed: nine - * engine families, six mapping shapes and each statement that applies to a shape. The test reads + * engine families, twelve mapping shapes (six that hold the other statements and six that hold the link counts of a relation) and each statement that applies to a shape. The test reads * the files and never writes one. */ class OntologyStatementGoldenTest { private static final int FAMILIES = 9; - private static final int STATEMENTS_OF_THE_SHAPES = 33; + private static final int STATEMENTS_OF_THE_SHAPES = 45; static List goldens() { return OntologyStatementGoldens.all(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java index 373df6c6beec..7b4ed8e45ab6 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java @@ -18,6 +18,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.stream.Stream; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.RecordStatement; import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; @@ -67,13 +68,19 @@ public String toString() { static List all() { final List goldens = new ArrayList<>(); for (final SqlEngineFamily family : SERVICE_TYPES.keySet()) { - for (final Shape shape : OntologyMappingShapes.all()) { + for (final Shape shape : shapes()) { shape.asks().forEach(ask -> goldens.add(new Golden(family, shape, ask))); } } return goldens; } + /** The six mapping shapes, then the six that hold the link counts of a relation. */ + static List shapes() { + return Stream.concat(OntologyMappingShapes.all().stream(), OntologyLinkShapes.all().stream()) + .toList(); + } + private static Map serviceTypes() { final Map types = new LinkedHashMap<>(); types.put(SqlEngineFamily.POSTGRES, "Postgres"); diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-forward.sql new file mode 100644 index 000000000000..13a17d79a77b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..cd6c832f55c4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..faef582e1560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`tenant` AS r0, t0.`branch` AS r1 + FROM `shop`.`employees` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`tenant` IS NOT NULL + AND t0.`branch` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..43ef1a73aab6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`branch_id` AS k1, t1.`id` AS r0 + FROM `shop`.`branches` t0 + JOIN `shop`.`employees` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`branch` = t0.`branch_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`branch_id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3e260b770043 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant` AS k0, t0.`order_no` AS k1, t1.`sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_lines` t1 ON t1.`tenant` = t0.`tenant` AND t1.`order_no` = t0.`order_no` + WHERE t0.`tenant` IS NOT NULL + AND t0.`order_no` IS NOT NULL + AND t1.`sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..dbfb7a5e2363 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`tenant` AS r0, t1.`order_no` AS r1 + FROM `shop`.`products` t0 + JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`tenant` IS NOT NULL + AND t1.`order_no` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..fb0ce7737a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..ab8d2db3e65a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`order_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..e7735bb0ef52 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`employer_id` AS r0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`employer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..7bea0db92ebf --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`parties` t0 + JOIN `shop`.`parties` t1 ON t1.`employer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..b24465e4fb7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..ab8d2db3e65a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`order_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-forward.sql new file mode 100644 index 000000000000..13a17d79a77b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..cd6c832f55c4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..faef582e1560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`tenant` AS r0, t0.`branch` AS r1 + FROM `shop`.`employees` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`tenant` IS NOT NULL + AND t0.`branch` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..43ef1a73aab6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`branch_id` AS k1, t1.`id` AS r0 + FROM `shop`.`branches` t0 + JOIN `shop`.`employees` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`branch` = t0.`branch_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`branch_id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3e260b770043 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant` AS k0, t0.`order_no` AS k1, t1.`sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_lines` t1 ON t1.`tenant` = t0.`tenant` AND t1.`order_no` = t0.`order_no` + WHERE t0.`tenant` IS NOT NULL + AND t0.`order_no` IS NOT NULL + AND t1.`sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..dbfb7a5e2363 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`tenant` AS r0, t1.`order_no` AS r1 + FROM `shop`.`products` t0 + JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`tenant` IS NOT NULL + AND t1.`order_no` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..fb0ce7737a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..ab8d2db3e65a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`order_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..e7735bb0ef52 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`employer_id` AS r0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`employer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..7bea0db92ebf --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`parties` t0 + JOIN `shop`.`parties` t1 ON t1.`employer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..b24465e4fb7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..ab8d2db3e65a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`order_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-forward.sql new file mode 100644 index 000000000000..13a17d79a77b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..cd6c832f55c4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..faef582e1560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`tenant` AS r0, t0.`branch` AS r1 + FROM `shop`.`employees` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`tenant` IS NOT NULL + AND t0.`branch` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..43ef1a73aab6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`branch_id` AS k1, t1.`id` AS r0 + FROM `shop`.`branches` t0 + JOIN `shop`.`employees` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`branch` = t0.`branch_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`branch_id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3e260b770043 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant` AS k0, t0.`order_no` AS k1, t1.`sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_lines` t1 ON t1.`tenant` = t0.`tenant` AND t1.`order_no` = t0.`order_no` + WHERE t0.`tenant` IS NOT NULL + AND t0.`order_no` IS NOT NULL + AND t1.`sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..dbfb7a5e2363 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`tenant` AS r0, t1.`order_no` AS r1 + FROM `shop`.`products` t0 + JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`tenant` IS NOT NULL + AND t1.`order_no` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..fb0ce7737a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..ab8d2db3e65a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`order_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..e7735bb0ef52 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`employer_id` AS r0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`employer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..7bea0db92ebf --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`parties` t0 + JOIN `shop`.`parties` t1 ON t1.`employer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..b24465e4fb7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..ab8d2db3e65a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`order_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-forward.sql new file mode 100644 index 000000000000..18badcb9bec0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS r0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..95a1714b7024 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.customers t0 + JOIN shop.orders t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..eda40abc3f8d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.tenant AS r0, t0.branch AS r1 + FROM shop.employees t0 + WHERE t0.id IS NOT NULL + AND t0.tenant IS NOT NULL + AND t0.branch IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..c623bc9cb3dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.branch_id AS k1, t1.id AS r0 + FROM shop.branches t0 + JOIN shop.employees t1 ON t1.tenant = t0.tenant_id AND t1.branch = t0.branch_id + WHERE t0.tenant_id IS NOT NULL + AND t0.branch_id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..395b8fd7390e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant AS k0, t0.order_no AS k1, t1.sku AS r0 + FROM shop.orders t0 + JOIN shop.order_lines t1 ON t1.tenant = t0.tenant AND t1.order_no = t0.order_no + WHERE t0.tenant IS NOT NULL + AND t0.order_no IS NOT NULL + AND t1.sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..17a05ff8a056 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.tenant AS r0, t1.order_no AS r1 + FROM shop.products t0 + JOIN shop.order_lines t1 ON t1.sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.tenant IS NOT NULL + AND t1.order_no IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..3bbdf68b2348 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..0468e7f6288d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.order_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..c7195344bb2e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.employer_id AS r0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.employer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..59af4ab12b0a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.parties t0 + JOIN shop.parties t1 ON t1.employer_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..afefbe446c11 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..0468e7f6288d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.order_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-forward.sql new file mode 100644 index 000000000000..18badcb9bec0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS r0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..95a1714b7024 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.customers t0 + JOIN shop.orders t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..eda40abc3f8d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.tenant AS r0, t0.branch AS r1 + FROM shop.employees t0 + WHERE t0.id IS NOT NULL + AND t0.tenant IS NOT NULL + AND t0.branch IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..c623bc9cb3dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.branch_id AS k1, t1.id AS r0 + FROM shop.branches t0 + JOIN shop.employees t1 ON t1.tenant = t0.tenant_id AND t1.branch = t0.branch_id + WHERE t0.tenant_id IS NOT NULL + AND t0.branch_id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..395b8fd7390e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant AS k0, t0.order_no AS k1, t1.sku AS r0 + FROM shop.orders t0 + JOIN shop.order_lines t1 ON t1.tenant = t0.tenant AND t1.order_no = t0.order_no + WHERE t0.tenant IS NOT NULL + AND t0.order_no IS NOT NULL + AND t1.sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..17a05ff8a056 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.tenant AS r0, t1.order_no AS r1 + FROM shop.products t0 + JOIN shop.order_lines t1 ON t1.sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.tenant IS NOT NULL + AND t1.order_no IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..3bbdf68b2348 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..0468e7f6288d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.order_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..c7195344bb2e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.employer_id AS r0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.employer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..59af4ab12b0a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.parties t0 + JOIN shop.parties t1 ON t1.employer_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..afefbe446c11 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..0468e7f6288d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.order_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-forward.sql new file mode 100644 index 000000000000..0dd502d3c1d6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t0."customer_id" AS r0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + AND t0."customer_id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..a7b3a037a5ef --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."id" AS r0 + FROM "shop"."customers" t0 + JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..643758cb531d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t0."tenant" AS r0, t0."branch" AS r1 + FROM "shop"."employees" t0 + WHERE t0."id" IS NOT NULL + AND t0."tenant" IS NOT NULL + AND t0."branch" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..aaa7063ff81d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."branch_id" AS k1, t1."id" AS r0 + FROM "shop"."branches" t0 + JOIN "shop"."employees" t1 ON t1."tenant" = t0."tenant_id" AND t1."branch" = t0."branch_id" + WHERE t0."tenant_id" IS NOT NULL + AND t0."branch_id" IS NOT NULL + AND t1."id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..7326af5b863d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."tenant" AS k0, t0."order_no" AS k1, t1."sku" AS r0 + FROM "shop"."orders" t0 + JOIN "shop"."order_lines" t1 ON t1."tenant" = t0."tenant" AND t1."order_no" = t0."order_no" + WHERE t0."tenant" IS NOT NULL + AND t0."order_no" IS NOT NULL + AND t1."sku" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..29ce809fba1f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."sku" AS k0, t1."tenant" AS r0, t1."order_no" AS r1 + FROM "shop"."products" t0 + JOIN "shop"."order_lines" t1 ON t1."sku" = t0."sku" + WHERE t0."sku" IS NOT NULL + AND t1."tenant" IS NOT NULL + AND t1."order_no" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..c9c816141b6e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."product_sku" AS r0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t0."channel" = 'web' + AND t1."product_sku" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..108d51a6b39b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."sku" AS k0, t1."order_id" AS r0 + FROM "shop"."products" t0 + JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" + WHERE t0."sku" IS NOT NULL + AND t1."order_id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..55f8de72484b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t0."employer_id" AS r0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + AND t0."employer_id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..4e94f15a2810 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."id" AS r0 + FROM "shop"."parties" t0 + JOIN "shop"."parties" t1 ON t1."employer_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'organization' + AND t1."id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..8c8356037a43 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."product_sku" AS r0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."product_sku" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..108d51a6b39b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."sku" AS k0, t1."order_id" AS r0 + FROM "shop"."products" t0 + JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" + WHERE t0."sku" IS NOT NULL + AND t1."order_id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-forward.sql new file mode 100644 index 000000000000..13a17d79a77b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..cd6c832f55c4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..faef582e1560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`tenant` AS r0, t0.`branch` AS r1 + FROM `shop`.`employees` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`tenant` IS NOT NULL + AND t0.`branch` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..43ef1a73aab6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`branch_id` AS k1, t1.`id` AS r0 + FROM `shop`.`branches` t0 + JOIN `shop`.`employees` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`branch` = t0.`branch_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`branch_id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3e260b770043 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant` AS k0, t0.`order_no` AS k1, t1.`sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_lines` t1 ON t1.`tenant` = t0.`tenant` AND t1.`order_no` = t0.`order_no` + WHERE t0.`tenant` IS NOT NULL + AND t0.`order_no` IS NOT NULL + AND t1.`sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..dbfb7a5e2363 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`tenant` AS r0, t1.`order_no` AS r1 + FROM `shop`.`products` t0 + JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`tenant` IS NOT NULL + AND t1.`order_no` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..fb0ce7737a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..ab8d2db3e65a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`order_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..e7735bb0ef52 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`employer_id` AS r0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`employer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..7bea0db92ebf --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`parties` t0 + JOIN `shop`.`parties` t1 ON t1.`employer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..b24465e4fb7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..ab8d2db3e65a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + WHERE t0.`sku` IS NOT NULL + AND t1.`order_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-forward.sql new file mode 100644 index 000000000000..18badcb9bec0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS r0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..95a1714b7024 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.customers t0 + JOIN shop.orders t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..eda40abc3f8d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.tenant AS r0, t0.branch AS r1 + FROM shop.employees t0 + WHERE t0.id IS NOT NULL + AND t0.tenant IS NOT NULL + AND t0.branch IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..c623bc9cb3dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.branch_id AS k1, t1.id AS r0 + FROM shop.branches t0 + JOIN shop.employees t1 ON t1.tenant = t0.tenant_id AND t1.branch = t0.branch_id + WHERE t0.tenant_id IS NOT NULL + AND t0.branch_id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..395b8fd7390e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant AS k0, t0.order_no AS k1, t1.sku AS r0 + FROM shop.orders t0 + JOIN shop.order_lines t1 ON t1.tenant = t0.tenant AND t1.order_no = t0.order_no + WHERE t0.tenant IS NOT NULL + AND t0.order_no IS NOT NULL + AND t1.sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..17a05ff8a056 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.tenant AS r0, t1.order_no AS r1 + FROM shop.products t0 + JOIN shop.order_lines t1 ON t1.sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.tenant IS NOT NULL + AND t1.order_no IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..3bbdf68b2348 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..0468e7f6288d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.order_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..c7195344bb2e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.employer_id AS r0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.employer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..59af4ab12b0a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.parties t0 + JOIN shop.parties t1 ON t1.employer_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..afefbe446c11 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..0468e7f6288d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + WHERE t0.sku IS NOT NULL + AND t1.order_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-forward.sql new file mode 100644 index 000000000000..8d31667a016a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[customer_id] AS r0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..1c0f0536d6bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[id] AS r0 + FROM [shop].[customers] t0 + JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..18fe2a0ed957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[tenant] AS r0, t0.[branch] AS r1 + FROM [shop].[employees] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[tenant] IS NOT NULL + AND t0.[branch] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..b93d727e39ea --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[branch_id] AS k1, t1.[id] AS r0 + FROM [shop].[branches] t0 + JOIN [shop].[employees] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[branch] = t0.[branch_id] + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[branch_id] IS NOT NULL + AND t1.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3d668bdd932b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[tenant] AS k0, t0.[order_no] AS k1, t1.[sku] AS r0 + FROM [shop].[orders] t0 + JOIN [shop].[order_lines] t1 ON t1.[tenant] = t0.[tenant] AND t1.[order_no] = t0.[order_no] + WHERE t0.[tenant] IS NOT NULL + AND t0.[order_no] IS NOT NULL + AND t1.[sku] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..1d2ccc11c98b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[sku] AS k0, t1.[tenant] AS r0, t1.[order_no] AS r1 + FROM [shop].[products] t0 + JOIN [shop].[order_lines] t1 ON t1.[sku] = t0.[sku] + WHERE t0.[sku] IS NOT NULL + AND t1.[tenant] IS NOT NULL + AND t1.[order_no] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..68401480bfdf --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS r0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t0.[channel] = N'web' + AND t1.[product_sku] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bf71f76ea7ed --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[sku] AS k0, t1.[order_id] AS r0 + FROM [shop].[products] t0 + JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] + WHERE t0.[sku] IS NOT NULL + AND t1.[order_id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..7a9fb558617f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[employer_id] AS r0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + AND t0.[employer_id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..e4e9639710f4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[id] AS r0 + FROM [shop].[parties] t0 + JOIN [shop].[parties] t1 ON t1.[employer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'organization' + AND t1.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..0b3c2df4d9b2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS r0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[product_sku] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bf71f76ea7ed --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[sku] AS k0, t1.[order_id] AS r0 + FROM [shop].[products] t0 + JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] + WHERE t0.[sku] IS NOT NULL + AND t1.[order_id] IS NOT NULL +) k diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json index d505824b3078..d4c87d95abb3 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json @@ -2,7 +2,7 @@ "$id": "https://open-metadata.org/schema/api/data/ontologyAggregateStatementRequest.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "OntologyAggregateStatementRequest", - "description": "Asks for a counting statement. Without a relation it counts the records of the class. With a relation and a direction it returns the 8 records of the class that relate to the most records along that relation, each with its count.", + "description": "Asks for a counting statement. Without a relation it counts the records of the class. With a relation and a direction it returns, by default, the 8 records of the class that relate to the most records along that relation, each with its count. With the measure `linkCount` it returns one number, the distinct pairs of a record of the class and a related key along the confirmed join.", "type": "object", "javaType": "org.openmetadata.schema.api.data.OntologyAggregateStatementRequest", "properties": { @@ -16,6 +16,10 @@ "direction": { "$ref": "ontologyStatementPlan.json#/definitions/direction" }, + "measure": { + "description": "What to count along the relation. Only a request that names a relation and a direction takes one, and a request that names none counts `topRecords`.", + "$ref": "ontologyStatementPlan.json#/definitions/measure" + }, "relatedClass": { "description": "Id of the class at the far end of the relation. Leave it out when the relation names one class on that side, its range for `forward` and its domain for `inverse`.", "$ref": "../../type/basic.json#/definitions/uuid" diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json index 0f1187a82d3b..77429cd2b399 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json @@ -24,6 +24,12 @@ "type": "array", "items": { "description": "A string, a number or a boolean." } }, + "measure": { + "description": "What an aggregate over a relation counts. `topRecords` returns the 8 records of the class that relate to the most records along the relation, each with its count. `linkCount` returns one number: the distinct pairs of a record of the class and a related key along the confirmed join. A related key counts when no part of it is null, whether or not a record holds it, as a stored profile counts a reference. A request that names none asks for `topRecords`.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementMeasure", + "enum": ["topRecords", "linkCount"] + }, "statementKind": { "description": "What a statement asks. `find` lists records of a class. `expand` lists the records that one record relates to. `open` reads every bound column of one record. `aggregate` counts.", "type": "string", @@ -185,8 +191,12 @@ "default": [] }, "relation": { "$ref": "#/definitions/relation" }, + "measure": { + "description": "What an aggregate over a relation counts. Absent on every other statement, including the count of a class.", + "$ref": "#/definitions/measure" + }, "rowCap": { - "description": "The most rows a reader takes from the result. `find` and `expand` take 25, `open` takes 100, a relation count takes 8 and a class count takes 1.", + "description": "The most rows a reader takes from the result. `find` and `expand` take 25, `open` takes 100, a relation count takes 8, and a class count and a link count take 1.", "type": "integer", "minimum": 1 }, From 16b989b0226395b2f4a0ed0fb09f00d5b021813c Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 22:05:25 -0800 Subject: [PATCH 060/203] Test the link count of a relation over six mappings on MySQL and Postgres --- .../it/tests/OntologyLinkCountIT.java | 348 ++++++++++++++++++ .../it/tests/OntologyShapeFixture.java | 3 +- 2 files changed, 350 insertions(+), 1 deletion(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java new file mode 100644 index 000000000000..d85258a65db4 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java @@ -0,0 +1,348 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.schema.api.data.OntologyStatementDirection.FORWARD; +import static org.openmetadata.schema.api.data.OntologyStatementMeasure.LINK_COUNT; +import static org.openmetadata.schema.api.data.OntologyStatementMeasure.TOP_RECORDS; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.columnPlan; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.function.Executable; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementRelation; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyLinkShapes; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Asks the aggregate endpoint for the number of links of a relation, over each of six mappings of + * a relation with the tables created in the database this suite runs on, and runs the statement + * that comes back. A statement must be the golden text of its engine family, and the number it + * returns must be the one that a person worked out from the rows. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyLinkCountIT extends BaseOntologyApprovalIT { + private static final String ORDER = "https://example.org/columnRelation#Order"; + private static final String CUSTOMER = "https://example.org/columnRelation#Customer"; + private static final String PLACED_BY = "https://example.org/columnRelation#placedBy"; + private static final String MEASURE_OF_A_RELATION = + "A measure belongs to a relation. A count of the class takes no measure"; + private static final String RELATION_OR_COUNT = + "An aggregate over a relation takes the relation and the direction together. A count of the" + + " class takes neither, and no related class"; + + @Test + void aRelationHeldInAColumnCountsEachDistinctPairWithAKeyOnBothSides(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.COLUMN)); + } + + @Test + void aStartRowThatTheRowFilterExcludesIsNeverCountedAndTheRelatedFilterNeverApplies( + final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.FILTERED_START)); + } + + @Test + void aRelationHeldInTwoColumnsCountsAPairOnlyWhenNeitherColumnIsNull(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.COMPOSITE_KEY)); + } + + @Test + void aLinkTableThatRepeatsAPairCountsItOnce(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.LINK_TABLE)); + } + + @Test + void aLinkTableOverATwoColumnKeyCountsEachPairOnce(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.COMPOSITE_LINK_TABLE)); + } + + @Test + void aLinkTableOfAFilteredClassCountsOnlyTheLinksOfTheRecordsThatItKeeps(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("3")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.FILTERED_LINK_TABLE)); + } + + @Test + void aRequestWithNoMeasureStillGivesTheRecordsThatRelateToTheMost(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "defaultMeasure"); + final Ask top = COLUMN_RELATION.ask("aggregate-inverse"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, COLUMN_RELATION).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + + final OntologyStatementPlan byDefault = fixture.ask(admin(), top, null); + final OntologyStatementPlan named = fixture.ask(admin(), top.withMeasure(TOP_RECORDS), null); + + assertEquals(fixture.golden(top), byDefault.getSql() + "\n"); + assertEquals(byDefault, named); + assertEquals(TOP_RECORDS, byDefault.getMeasure()); + assertEquals(8, byDefault.getRowCap()); + assertNull( + fixture.ask(admin(), COLUMN_RELATION.ask("count"), null).getMeasure(), + "A class count names no measure"); + } + } + + @Test + void aMeasureBelongsToARelation(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "measureOfAClass"); + final Ask count = COLUMN_RELATION.ask("count"); + final Ask forward = COLUMN_RELATION.ask("aggregate-forward").withMeasure(LINK_COUNT); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + + assertRefused( + 400, + MEASURE_OF_A_RELATION, + () -> fixture.ask(admin(), count.withMeasure(LINK_COUNT), DRAFT)); + assertRefused( + 400, + MEASURE_OF_A_RELATION, + () -> fixture.ask(admin(), count.withMeasure(TOP_RECORDS), DRAFT)); + assertRefused( + 400, RELATION_OR_COUNT, () -> fixture.ask(admin(), withoutDirection(forward), DRAFT)); + assertEquals( + OntologyStatementKind.AGGREGATE, fixture.ask(admin(), forward, DRAFT).getStatement()); + } + } + + @Test + void aLinkCountIsRefusedLikeTheRecordsThatRelateToTheMost(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "linkRefusals"); + final BindingSpec orders = COLUMN_RELATION.binding("Order", "orders"); + final List both = + List.of( + COLUMN_RELATION.ask("aggregate-forward").withMeasure(LINK_COUNT), + COLUMN_RELATION.ask("aggregate-inverse").withMeasure(LINK_COUNT)); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bind(COLUMN_RELATION.binding("Customer", "customers")); + + fixture.bind(withColumns(orders, List.of(orders.columns().getFirst()))); + both.forEach( + ask -> + assertRefused( + 409, + "Relation " + + PLACED_BY + + " has no join from class " + + ORDER + + " to the identity table of class " + + CUSTOMER, + () -> fixture.ask(admin(), ask, DRAFT))); + fixture.bind( + withColumns( + orders, + List.of( + orders.columns().getFirst(), + new ColumnBindingSpec( + "placedBy", + "customer_id", + new JoinSpec( + "customers", + OntologyJoinStatus.INFERRED, + List.of("customer_id"), + List.of("id")))))); + both.forEach( + ask -> + assertRefused( + 409, + "The join of relation " + + PLACED_BY + + " from class " + + ORDER + + " to class " + + CUSTOMER + + " is not confirmed", + () -> fixture.ask(admin(), ask, DRAFT))); + fixture.bind(orders); + both.forEach( + ask -> + assertEquals( + OntologyStatementKind.AGGREGATE, + fixture.ask(admin(), ask, DRAFT).getStatement())); + } + } + + @Test + void aReaderWhoMayNotViewAnIdentityTableIsRefusedByClassAndNeverByTable(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "linkHidden"); + final Ask forward = COLUMN_RELATION.ask("aggregate-forward").withMeasure(LINK_COUNT); + final Ask inverse = COLUMN_RELATION.ask("aggregate-inverse").withMeasure(LINK_COUNT); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var first = new RdfAccessFixtures("linkCustomers" + ns.shortPrefix()); + var second = new RdfAccessFixtures("linkOrders" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient seesCustomers = ownerReader(first, Entity.TABLE); + fixture.ownedBy(seesCustomers, "customers"); + final OpenMetadataClient seesOrders = ownerReader(second, Entity.TABLE); + fixture.ownedBy(seesOrders, "orders"); + + assertRefused( + 403, + "The identity table of class " + ORDER + " is not visible to you", + () -> fixture.ask(seesCustomers, forward, null)); + assertRefused( + 403, + "The identity table of class " + CUSTOMER + " is not visible to you", + () -> fixture.ask(seesOrders, inverse, null)); + assertEquals( + OntologyStatementKind.AGGREGATE, fixture.ask(admin(), forward, null).getStatement()); + } + } + + @Test + void aReaderWhoMayNotViewTheLinkTableOfARelationIsRefusedWithoutItBeingNamed( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "linkHiddenTable"); + final Ask forward = LINK_TABLE.ask("aggregate-forward").withMeasure(LINK_COUNT); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("linkItems" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.TABLE); + fixture.ownedBy(reader, "orders", "products"); + + assertRefused( + 403, + "The table that links class https://example.org/linkTable#Order to class" + + " https://example.org/linkTable#Product for relation" + + " https://example.org/linkTable#contains is not visible to you", + () -> fixture.ask(reader, forward, null)); + } + } + + /** + * Binds the shape over real tables, activates a release and asks the link count of each + * direction as a request that names no version. + * + * @return the rows of each ask, forward first + */ + private static List>> links(final TestNamespace ns, final Shape shape) { + final Ontology ontology = createOntology(ns, shape.name()); + final List>> rows = new ArrayList<>(); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, shape).withRows()) { + fixture.bindAll(); + final OntologyRelease release = current(activate(ns, ontology)); + assertAll( + shape.asks().stream() + .map(ask -> (Executable) () -> rows.add(answered(fixture, shape, ask, release)))); + } + return List.copyOf(rows); + } + + private static List> answered( + final OntologyShapeFixture fixture, + final Shape shape, + final Ask ask, + final OntologyRelease release) { + final OntologyStatementPlan plan = fixture.ask(admin(), ask, null); + final String name = shape.name() + " " + ask.name(); + + assertEquals(fixture.golden(ask), plan.getSql() + "\n", name + " sql"); + assertEquals(plan.getSql(), plan.getEscapedSql(), name + " escapedSql"); + assertFalse(plan.getSql().contains("ORDER BY"), name + " has an order"); + assertFalse(plan.getSql().contains("LIMIT"), name + " has a limit"); + assertFalse(plan.getSql().contains("TOP"), name + " has a limit"); + assertEquals(OntologyStatementKind.AGGREGATE, plan.getStatement(), name + " statement"); + assertEquals(LINK_COUNT, plan.getMeasure(), name + " measure"); + assertEquals(fixture.family(), plan.getFamily().value(), name + " family"); + assertEquals(fixture.tablesOf(ask), plan.getTables(), name + " tables"); + assertEquals(ask.columns(), columnPlan(plan.getColumns()), name + " columns"); + assertEquals(1, plan.getRowCap(), name + " rowCap"); + assertFalse(plan.getExtraRow(), name + " extraRow"); + assertEquals(relationOf(shape, ask), plan.getRelation(), name + " relation"); + assertEquals( + List.of(fixture.revisionOf(ask.type()), fixture.revisionOf(relatedTo(shape, ask))), + plan.getBindingRevisions(), + name + " revisions"); + assertEquals(release.getId(), plan.getVersion().getReleaseId(), name + " release"); + final List> rows = OntologyShapeFixture.run(plan.getSql()); + assertEquals(ask.rows(), rows, name + " rows"); + return rows; + } + + private static OntologyStatementRelation relationOf(final Shape shape, final Ask ask) { + return new OntologyStatementRelation() + .withPropertyIri(shape.iri(ask.relation())) + .withDirection(ask.direction()) + .withRelatedClassIri(shape.iri(relatedTo(shape, ask))); + } + + /** The class at the far end of the relation: its range forward and its domain going back. */ + private static String relatedTo(final Shape shape, final Ask ask) { + final PropertySpec relation = shape.property(ask.relation()); + return ask.direction() == FORWARD ? relation.range() : relation.domain(); + } + + private static Ask withoutDirection(final Ask ask) { + return new Ask( + ask.name(), + ask.kind(), + ask.type(), + ask.matchText(), + ask.key(), + ask.relation(), + null, + ask.columns(), + ask.rows(), + ask.measure()); + } + + private static BindingSpec withColumns( + final BindingSpec spec, final List columns) { + return new BindingSpec( + spec.type(), spec.table(), spec.role(), spec.key(), spec.filter(), columns); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java index 5aa22ccdf5f5..0aeac7490834 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java @@ -343,7 +343,8 @@ private Object request(final Ask ask, final OntologyStatementVersion version) { case AGGREGATE -> new OntologyAggregateStatementRequest() .withVersion(version) .withRelation(relation) - .withDirection(ask.direction()); + .withDirection(ask.direction()) + .withMeasure(ask.measure()); }; } From dd3a9bcdafb6cb7823754a740f22852a266522bc Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 23:01:04 -0800 Subject: [PATCH 061/203] Read a class cut by the first binding read again so its join state does not depend on its table count, and count no distinct values taken after a transform --- .../jdbi3/OntologyConceptBindingDAO.java | 41 +++- .../jdbi3/OntologyConceptBindingStore.java | 27 ++- .../service/ontology/OntologyCountReader.java | 76 +++++- .../service/ontology/OntologyCountRules.java | 190 +++++++++++++-- .../ontology/OntologyCountRulesTest.java | 225 ++++++++++++++++-- 5 files changed, 501 insertions(+), 58 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java index 5c2c3b3474e7..b1aaa8329b5a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java @@ -201,25 +201,48 @@ List listForConceptsAfter( List listFirstTablesForConcepts( @BindList("conceptIds") List conceptIds, @Bind("perConcept") int perConcept); + String IDENTITY_FIRST_RANKED = + " FROM (SELECT " + + COLUMNS + + ", ROW_NUMBER() OVER (PARTITION BY conceptId ORDER BY " + + "CASE WHEN bindingRole = '" + + IDENTITY_ROLE + + "' THEN 0 ELSE 1 END ASC, assetId ASC) AS bindingOrder " + + "FROM ontology_concept_binding WHERE conceptId IN () " + + "AND assetType = 'table'"; + String RANKED_PAGE = + ") ranked WHERE bindingOrder <= :perConcept " + + "ORDER BY conceptId ASC, assetId ASC LIMIT :limit"; + /** * For each concept, its identity table row first and then its other table rows in asset id * order, up to {@code perConcept} rows, in one statement. The statement carries a limit of {@code * perConcept} rows for each concept asked about, which it can never reach. */ + @SqlQuery("SELECT " + COLUMNS + IDENTITY_FIRST_RANKED + RANKED_PAGE) + @RegisterRowMapper(BindingRowMapper.class) + List listIdentityFirstTablesForConcepts( + @BindList("conceptIds") List conceptIds, + @Bind("perConcept") int perConcept, + @Bind("limit") int limit); + + /** + * For each concept, its identity table row first and then its contributing table rows in asset + * id order, up to {@code perConcept} rows, in one statement: the rows that can hold a join. + * Unassigned rows are left out, so they never take a place from a contributing row. + */ @SqlQuery( "SELECT " + COLUMNS - + " FROM (SELECT " - + COLUMNS - + ", ROW_NUMBER() OVER (PARTITION BY conceptId ORDER BY " - + "CASE WHEN bindingRole = '" + + IDENTITY_FIRST_RANKED + + " AND bindingRole IN ('" + IDENTITY_ROLE - + "' THEN 0 ELSE 1 END ASC, assetId ASC) AS bindingOrder " - + "FROM ontology_concept_binding WHERE conceptId IN () " - + "AND assetType = 'table') ranked " - + "WHERE bindingOrder <= :perConcept ORDER BY conceptId ASC, assetId ASC LIMIT :limit") + + "', '" + + CONTRIBUTING_ROLE + + "')" + + RANKED_PAGE) @RegisterRowMapper(BindingRowMapper.class) - List listIdentityFirstTablesForConcepts( + List listJoinHoldersForConcepts( @BindList("conceptIds") List conceptIds, @Bind("perConcept") int perConcept, @Bind("limit") int limit); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 2ba914a67d6d..8d654b5b545e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -247,14 +247,35 @@ public List firstTables(final Collection conceptIds, final int */ public List identityFirstTables( final Collection conceptIds, final int perConcept) { + return grouped( + conceptIds, + perConcept, + dao.ontologyConceptBindingDAO()::listIdentityFirstTablesForConcepts); + } + + /** + * The identity table row of each concept, when it has one, then its contributing table rows in + * asset id order, up to {@code perConcept} rows in all, grouped as {@link #identityFirstTables}. + */ + public List joinHolderTables( + final Collection conceptIds, final int perConcept) { + return grouped( + conceptIds, perConcept, dao.ontologyConceptBindingDAO()::listJoinHoldersForConcepts); + } + + @FunctionalInterface + private interface RankedRead { + List read(List conceptIds, int perConcept, int limit); + } + + private static List grouped( + final Collection conceptIds, final int perConcept, final RankedRead read) { final List ids = conceptIds.stream().map(UUID::toString).distinct().toList(); final int group = Math.max(1, SCAN_PAGE_SIZE / perConcept); final List rows = new ArrayList<>(); for (int from = 0; from < ids.size(); from += group) { final List chunk = ids.subList(from, Math.min(ids.size(), from + group)); - rows.addAll( - dao.ontologyConceptBindingDAO() - .listIdentityFirstTablesForConcepts(chunk, perConcept, chunk.size() * perConcept)); + rows.addAll(read.read(chunk, perConcept, chunk.size() * perConcept)); } return rows; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java index b24ce75fdca9..703245a42542 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java @@ -13,9 +13,14 @@ package org.openmetadata.service.ontology; +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyCountRules.JOIN_HOLDERS_PER_CLASS; +import static org.openmetadata.service.ontology.OntologyCountRules.ROWS_PER_CLASS; + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -96,8 +101,15 @@ Counts read(final Access access, final Collection classes, final List rows = classRows(all); - final Facts facts = facts(access, rows.values()); + final Map firstRows = + classRows(all, store.identityFirstTables(all, ROWS_PER_CLASS), ROWS_PER_CLASS); + final Facts first = facts(access, firstRows.values()); + final Set checked = new HashSet<>(); + final Set deleted = new HashSet<>(); + markDeleted(firstRows.values(), checked, deleted); + final Map rows = readInFull(firstRows, relations, first.withDeleted(deleted)); + markDeleted(rows.values(), checked, deleted); + final Facts facts = first.withDeleted(deleted); final Map records = new LinkedHashMap<>(); for (final UUID id : classes) { final var count = OntologyCountRules.records(rows.get(id), facts); @@ -115,11 +127,61 @@ Counts read(final Access access, final Collection classes, final List classRows(final Collection ids) { + /** + * The classes whose rows hold no confirmed join onto the table of a relation they hold and that + * were cut by the first read, read again as the statements of the mapping read them: the + * identity row and up to {@link OntologyCountRules#JOIN_HOLDERS_PER_CLASS} - 1 contributing + * rows, in one more statement for each group of classes that keeps it within one scan page. A + * page where no class is cut runs no more statement. + */ + private Map readInFull( + final Map rows, final List relations, final Facts facts) { + final Set cut = new LinkedHashSet<>(); + for (final Relation relation : relations) { + if (OntologyCountRules.needsAFullRead(relation, rows, facts)) { + cut.add(relation.subject()); + } + } + if (cut.isEmpty()) { + return rows; + } + final Map wide = new LinkedHashMap<>(rows); + wide.putAll( + classRows( + cut, store.joinHolderTables(cut, JOIN_HOLDERS_PER_CLASS), JOIN_HOLDERS_PER_CLASS)); + return wide; + } + + /** + * Adds to {@code deleted} the contributing tables, among the rows that hold a join and are not + * yet {@code checked}, that do not exist. One statement for all of them, and none when no such + * row holds a join. + */ + private void markDeleted( + final Collection classes, final Set checked, final Set deleted) { + final List holding = + classes.stream() + .flatMap(rows -> rows.rows().stream()) + .filter(row -> row.role() == OntologyBindingRole.CONTRIBUTING) + .filter(row -> listOrEmpty(row.columns()).stream().anyMatch(c -> c.getJoin() != null)) + .filter(row -> !checked.contains(row.assetId())) + .toList(); + if (holding.isEmpty()) { + return; + } + final Set live = store.liveAssets(holding).keySet(); + for (final BindingRow row : holding) { + checked.add(row.assetId()); + if (!live.contains(row.assetId())) { + deleted.add(row.assetId()); + } + } + } + + private static Map classRows( + final Collection ids, final List read, final int perClass) { final Map> byClass = new HashMap<>(); - store - .identityFirstTables(ids, OntologyCountRules.ROWS_PER_CLASS) - .forEach(row -> byClass.computeIfAbsent(row.conceptId(), id -> new ArrayList<>()).add(row)); + read.forEach(row -> byClass.computeIfAbsent(row.conceptId(), id -> new ArrayList<>()).add(row)); final Map rows = new LinkedHashMap<>(); for (final UUID id : ids) { final List own = byClass.getOrDefault(id, List.of()); @@ -128,7 +190,7 @@ private Map classRows(final Collection ids) { own.stream().filter(row -> row.role() == OntologyBindingRole.IDENTITY), own.stream().filter(row -> row.role() != OntologyBindingRole.IDENTITY)) .toList(); - rows.put(id, new ClassRows(id, ordered, own.size() >= OntologyCountRules.ROWS_PER_CLASS)); + rows.put(id, new ClassRows(id, ordered, own.size() >= perClass)); } return rows; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java index 3cfb5a28f5ba..84b46562c575 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java @@ -17,6 +17,7 @@ import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -28,6 +29,7 @@ import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.ColumnProfile; import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyColumnBinding; @@ -50,12 +52,19 @@ final class OntologyCountRules { /** * The identity row first, then the other table rows of a class, at most {@value #ROWS_PER_CLASS} - * in all, so that the response of a page of classes is read with rows well inside one scan - * page. A class that binds more tables than that is read as far as it goes and is flagged - * {@link ClassRows#truncated()}. + * in all, so that the response of a page of classes is read with rows well inside one scan page. + * A class that holds a relation onto a table and whose rows hold no confirmed join onto it is + * read again in full, as {@link #JOIN_HOLDERS_PER_CLASS} rows, so that its state is the one the + * statements of the mapping give. */ static final int ROWS_PER_CLASS = 5; + /** + * The identity row and the contributing rows that the statements of the mapping read, one more + * than they accept, so that a class over the limit is told from a class at it. + */ + static final int JOIN_HOLDERS_PER_CLASS = OntologyMappingReader.MAX_CONTRIBUTING_TABLES + 2; + /** * The engines that check a declared primary or unique key, so a duplicate row cannot exist * beside one. Snowflake, BigQuery, Redshift, Databricks, Unity Catalog, Synapse and Fabric store @@ -77,27 +86,94 @@ final class OntologyCountRules { "Db2", "SQLite"); + private static final Set SQL_SERVER_TRUNCATED_TEXT = + EnumSet.of(ColumnDataType.TEXT, ColumnDataType.MEDIUMTEXT, ColumnDataType.NTEXT); + + private static final Set SQL_SERVER_TRUNCATED_BINARY = + EnumSet.of(ColumnDataType.IMAGE); + + private static final Set ORACLE_LENGTH_COUNTED = + EnumSet.of( + ColumnDataType.BYTES, + ColumnDataType.BYTEA, + ColumnDataType.BINARY, + ColumnDataType.VARBINARY, + ColumnDataType.BLOB); + + /** + * The column types whose distinct values the profiler counts after a transform, by service type, + * so that {@code distinctCount} can be below the number of distinct values. The profiler's + * {@code DistinctCount} is {@code count(distinct(CountFn(col)))}, and {@code CountFn} + * ({@code ingestion/src/metadata/profiler/orm/functions/count.py}) compiles to: + * + *
      + *
    • on the {@code mssql} dialect, which Mssql, AzureSQL, Synapse and MicrosoftFabric all + * use ({@code mssql+pyodbc}), {@code cast(col as [nvarchar])} for a column of the + * SQLAlchemy type {@code TEXT} or {@code NVARCHAR}, which are the types TEXT, MEDIUMTEXT + * and NTEXT (XML is a {@code TEXT} subclass, and the profiler computes no metric for it). + * A cast with no length keeps 30 characters, so two values that share their first 30 + * characters count once; + *
    • on the same dialect, {@code cast(col as [varbinary])} for the type IMAGE, which keeps 30 + * bytes, so two values that share their first 30 bytes count once; + *
    • on the {@code oracle} dialect, {@code DBMS_LOB.GETLENGTH(col)} for the {@code + * HexByteString} types, which are BYTES, BYTEA, BINARY, VARBINARY and BLOB, so the count + * is the number of distinct lengths. + *
    + * + * No other dialect function of {@code CountFn} exists, and no other metric function in {@code + * profiler/metrics/static} or {@code profiler/orm/functions} transforms a value before it is + * counted. {@code valuesCount} is {@code count(CountFn(col))} and {@code nullCount} is a sum of + * {@code col IS NULL}: a cast or a length of a null is null and of a value is never null, so + * neither changes with a transform, and a link count, which reads only those two and tests + * {@code distinctCount == valuesCount} (a count too low can only fail that test), is not + * affected. + */ + private static final Map> TRANSFORMED_BEFORE_DISTINCT_COUNT = + Map.of( + "Mssql", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), + "AzureSQL", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), + "Synapse", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), + "MicrosoftFabric", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), + "Oracle", ORACLE_LENGTH_COUNTED); + private static final double WHOLE_PERCENTAGE = 100d; private OntologyCountRules() {} + private static Set union( + final Set first, final Set second) { + final Set all = EnumSet.copyOf(first); + all.addAll(second); + return Set.copyOf(all); + } + /** * The table bindings of one class, as {@link * org.openmetadata.service.jdbi3.OntologyConceptBindingStore#identityFirstTables} reads them. * * @param rows the identity row first when the class has one, then other table rows, hidden and * deleted tables included - * @param truncated true when the read stopped at its cap, so the class may bind more tables + * @param truncated true when {@code rows} may lack a table that the statements of the mapping + * read: a class that is read as {@link #ROWS_PER_CLASS} rows and whose rows hold no + * confirmed join is read again in full, and after that it is truncated only when it binds + * more contributing tables than a statement accepts, so that none is run */ record ClassRows(UUID id, List rows, boolean truncated) { BindingRow identity() { return rows.stream().filter(OntologyCountRules::isIdentity).findFirst().orElse(null); } - /** The identity row, then the contributing rows: the rows that can hold a join. */ - List holders() { + /** + * The identity row, then the contributing rows: the rows that can hold a join. A table that + * does not exist holds none. + */ + List holders(final Set deleted) { return rows.stream() - .filter(row -> isIdentity(row) || row.role() == OntologyBindingRole.CONTRIBUTING) + .filter( + row -> + isIdentity(row) + || row.role() == OntologyBindingRole.CONTRIBUTING + && !deleted.contains(row.assetId())) .toList(); } } @@ -113,12 +189,26 @@ record Relation(UUID subject, UUID object, UUID propertyId) {} * @param tableProfiles the latest stored profile of a table, by table id * @param columnProfiles the latest stored profile of a column, by the column's fully qualified * name + * @param deleted the ids of the contributing tables that hold a join and do not exist */ record Facts( Map tables, Set profileViewable, Map tableProfiles, - Map columnProfiles) {} + Map columnProfiles, + Set deleted) { + Facts( + final Map tables, + final Set profileViewable, + final Map tableProfiles, + final Map columnProfiles) { + this(tables, profileViewable, tableProfiles, columnProfiles, Set.of()); + } + + Facts withDeleted(final Set deleted) { + return new Facts(tables, profileViewable, tableProfiles, columnProfiles, deleted); + } + } /** The records of a class, or null when the class binds no table. */ static NativeOntologyCount records(final ClassRows binding, final Facts facts) { @@ -140,33 +230,74 @@ static NativeOntologyCount records(final ClassRows binding, final Facts facts) { */ static NativeOntologyCount links( final Relation relation, final Map classes, final Facts facts) { + final Probe probe = probe(relation, classes, facts); + if (probe.settled() != null || probe.lookup() == null) { + return probe.settled(); + } + final ClassRows subject = classes.get(relation.subject()); + return switch (probe.lookup()) { + case Lookup.Missing ignored -> subject.truncated() ? notDerivable() : state(State.NO_JOIN); + case Lookup.Unconfirmed ignored -> subject.truncated() + ? notDerivable() + : state(State.JOIN_NOT_CONFIRMED); + case Lookup.Confirmed found -> linkCount(probe.source(), probe.target(), found.stored()); + }; + } + + /** + * True when the class that binds {@code relation} is cut, so that the rows read hold no + * confirmed join onto the target and the tables left unread could hold one. Its state depends on + * those tables, so the class is read in full before its links are stated. + */ + static boolean needsAFullRead( + final Relation relation, final Map classes, final Facts facts) { + final Probe probe = probe(relation, classes, facts); + return probe.lookup() != null + && classes.get(relation.subject()).truncated() + && !(probe.lookup() instanceof Lookup.Confirmed); + } + + /** + * Everything the links of a relation are decided by before the join is looked up. + * + * @param settled the count that those facts already give, or null when the join decides + * @param lookup what the subject's rows store for the relation, or null when {@code settled} + * decides + */ + private record Probe( + NativeOntologyCount settled, Source source, BindingRow target, Lookup lookup) { + static Probe settled(final NativeOntologyCount count) { + return new Probe(count, null, null, null); + } + } + + private static Probe probe( + final Relation relation, final Map classes, final Facts facts) { final ClassRows subject = classes.get(relation.subject()); if (subject == null || subject.rows().isEmpty()) { - return null; + return Probe.settled(null); } final Source source = source(subject, facts); if (source.refusal() != null) { - return source.refusal(); + return Probe.settled(source.refusal()); } final ClassRows object = classes.get(relation.object()); final BindingRow target = object == null ? null : object.identity(); if (object == null || relation.propertyId() == null) { - return notDerivable(); + return Probe.settled(notDerivable()); } if (target == null) { - return state(State.NO_JOIN); + return Probe.settled(state(State.NO_JOIN)); } if (!facts.tables().containsKey(target.assetId())) { - return state(State.IDENTITY_TABLE_HIDDEN); - } - return switch (OntologyRelationPath.lookup( - relation.propertyId(), subject.holders(), target.assetId())) { - case Lookup.Missing ignored -> subject.truncated() ? notDerivable() : state(State.NO_JOIN); - case Lookup.Unconfirmed ignored -> subject.truncated() - ? notDerivable() - : state(State.JOIN_NOT_CONFIRMED); - case Lookup.Confirmed found -> linkCount(source, target, found.stored()); - }; + return Probe.settled(state(State.IDENTITY_TABLE_HIDDEN)); + } + return new Probe( + null, + source, + target, + OntologyRelationPath.lookup( + relation.propertyId(), subject.holders(facts.deleted()), target.assetId())); } /** The column paths whose profiles a class's counts can read: its key and the children of joins. */ @@ -184,7 +315,9 @@ private static NativeOntologyCount recordCount(final Source source) { final List> key = source.row().subjectKey(); if (key.size() == 1) { final Metrics metrics = source.metrics(key.getFirst()); - return metrics == null ? notDerivable() : exact(metrics.distinct(), source); + return metrics == null || source.distinctIsTransformed(key.getFirst()) + ? notDerivable() + : exact(metrics.distinct(), source); } final List metrics = new ArrayList<>(); for (final List path : key) { @@ -387,6 +520,17 @@ boolean hasNoNulls(final List path) { || enforcesKeys() && inPrimaryKey(column)); } + /** The profiler counted this column's distinct values after a transform on this engine. */ + boolean distinctIsTransformed(final List path) { + final Column column = OntologyBindingRules.resolveColumn(table, path); + return column != null + && column.getDataType() != null + && table.getServiceType() != null + && TRANSFORMED_BEFORE_DISTINCT_COUNT + .getOrDefault(table.getServiceType().value(), Set.of()) + .contains(column.getDataType()); + } + private boolean enforcesKeys() { return table.getServiceType() != null && ENGINES_THAT_ENFORCE_KEYS.contains(table.getServiceType().value()); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java index 1448a266822b..6da3fc9e2ec1 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java @@ -25,8 +25,12 @@ import java.util.Set; import java.util.UUID; import java.util.stream.IntStream; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.openmetadata.schema.api.data.NativeOntologyCount; import org.openmetadata.schema.api.data.NativeOntologyCount.State; @@ -34,6 +38,7 @@ import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.ColumnProfile; import org.openmetadata.schema.type.OntologyBindingAssetType; import org.openmetadata.schema.type.OntologyBindingRole; @@ -444,13 +449,166 @@ void aRelationThatNoViewablePropertyNamesGivesNoLinks() { } @Test - void aClassThatBindsMoreTablesThanWereReadStatesNoJoinOnlyWhenItSawEveryTable() { + void aClassThatBindsMoreContributingTablesThanAStatementAcceptsGivesNoJoinState() { final var world = new World(); world.joinChildren = List.of(); world.truncated = true; assertState(State.NOT_DERIVABLE, world.links()); } + @ParameterizedTest + @ValueSource(ints = {0, 4, 10, 16, 31}) + void aClassWithOtherTablesAndAnInferredJoinOnItsIdentityTableIsNotConfirmed(final int others) { + final var world = new World(); + world.joinStatus = OntologyJoinStatus.INFERRED; + world.otherTables = others; + assertState(State.JOIN_NOT_CONFIRMED, world.links()); + assertExact(100, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(ints = {0, 4, 10, 16, 31}) + void aClassWithOtherTablesAndNoJoinHasNoJoin(final int others) { + final var world = new World(); + world.joinChildren = List.of(); + world.otherTables = others; + assertState(State.NO_JOIN, world.links()); + } + + @ParameterizedTest + @ValueSource(ints = {4, 10, 16, 31}) + void aClassWithOtherTablesAndAConfirmedJoinOnAContributingTableGivesNoLinks(final int others) { + final var world = new World(); + world.joinOnContributingTable = true; + world.otherTables = others; + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aJoinOnADeletedContributingTableHoldsNoJoin() { + final var world = new World(); + world.joinOnContributingTable = true; + world.deleted.add(LINKS_TABLE); + assertState(State.NO_JOIN, world.links()); + } + + @Test + void aConfirmedJoinOnADeletedContributingTableLeavesTheInferredJoinOfTheIdentityTable() { + final var world = new World(); + world.joinOnContributingTable = true; + world.identityJoinStatus = OntologyJoinStatus.INFERRED; + assertState(State.NOT_DERIVABLE, world.links()); + world.deleted.add(LINKS_TABLE); + assertState(State.JOIN_NOT_CONFIRMED, world.links()); + } + + @Test + void aCutClassWithNoConfirmedJoinNeedsAFullRead() { + final var world = new World(); + world.joinChildren = List.of(); + world.truncated = true; + assertEquals( + true, OntologyCountRules.needsAFullRead(world.relation(), world.classes(), world.facts())); + } + + @Test + void aCutClassWhoseRowsHoldAConfirmedJoinNeedsNoFullRead() { + final var world = new World(); + world.truncated = true; + assertEquals( + false, OntologyCountRules.needsAFullRead(world.relation(), world.classes(), world.facts())); + } + + @Test + void aClassThatWasNotCutNeedsNoFullRead() { + final var world = new World(); + world.joinChildren = List.of(); + assertEquals( + false, OntologyCountRules.needsAFullRead(world.relation(), world.classes(), world.facts())); + } + + @Test + void aCutClassWhoseIdentityTableGivesNoCountNeedsNoFullRead() { + final var world = new World(); + world.joinChildren = List.of(); + world.truncated = true; + world.tableProfiles.remove(ORDERS_TABLE); + assertEquals( + false, OntologyCountRules.needsAFullRead(world.relation(), world.classes(), world.facts())); + } + + static Stream transformedPairs() { + final var sqlServer = + List.of( + ColumnDataType.TEXT, + ColumnDataType.MEDIUMTEXT, + ColumnDataType.NTEXT, + ColumnDataType.IMAGE); + final var oracle = + List.of( + ColumnDataType.BYTES, + ColumnDataType.BYTEA, + ColumnDataType.BINARY, + ColumnDataType.VARBINARY, + ColumnDataType.BLOB); + return Stream.concat( + Stream.of("Mssql", "AzureSQL", "Synapse", "MicrosoftFabric") + .flatMap(engine -> sqlServer.stream().map(type -> Arguments.of(engine, type))), + oracle.stream().map(type -> Arguments.of("Oracle", type))); + } + + @ParameterizedTest + @MethodSource("transformedPairs") + void aOneColumnKeyOfATypeTheProfilerTransformsBeforeCountingGivesNoRecords( + final String engine, final ColumnDataType type) { + final var world = new World().engine(engine); + world.columnType("id", type); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(strings = {"Mssql", "AzureSQL", "Synapse", "MicrosoftFabric", "Oracle"}) + void theSameKeyAsAVarcharOnTheSameEngineCountsItsDistinctValues(final String engine) { + final var world = new World().engine(engine); + world.columnType("id", ColumnDataType.VARCHAR); + assertExact(100, world.records(ORDER)); + } + + @ParameterizedTest + @CsvSource({ + "Postgres,TEXT", + "Mysql,TEXT", + "Mssql,BYTES", + "Mssql,VARBINARY", + "Mssql,BLOB", + "Oracle,TEXT", + "Oracle,IMAGE", + "Oracle,LONGBLOB", + "Snowflake,BYTES" + }) + void aTypeTheProfilerDoesNotTransformOnThatEngineStillCountsItsDistinctValues( + final String engine, final ColumnDataType type) { + final var world = new World().engine(engine); + world.columnType("id", type); + assertExact(100, world.records(ORDER)); + } + + @Test + void aTransformedKeyStillGivesLinksBecauseTheyReadOnlyValuesAndNulls() { + final var world = new World().engine("Mssql"); + world.columnType("id", ColumnDataType.TEXT); + assertExact(100, world.links()); + world.metrics("id", 100, 0, 99); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aTransformedColumnOfAKeyOfSeveralColumnsStillCountsItsValues() { + final var world = World.twoColumnKey("Oracle"); + world.columnType("tenant", ColumnDataType.BLOB); + assertExact(100, world.records(ORDER)); + } + private static OntologyRowFilter filter() { return new OntologyRowFilter() .withColumn(List.of("status")) @@ -494,6 +652,9 @@ private static final class World { OntologyRowFilter objectFilter; boolean joinOnContributingTable; boolean truncated; + int otherTables; + OntologyJoinStatus identityJoinStatus; + final Set deleted = new HashSet<>(); List subjectRows; World() { @@ -581,13 +742,23 @@ NativeOntologyCount links() { return linksAmong(classes()); } + Relation relation() { + return new Relation(ORDER, CUSTOMER, PLACED_BY); + } + + void columnType(final String name, final ColumnDataType type) { + table.getColumns().stream() + .filter(column -> column.getName().equals(name)) + .forEach(column -> column.setDataType(type)); + } + NativeOntologyCount linksAmong(final Map classes) { return OntologyCountRules.links(new Relation(ORDER, CUSTOMER, PLACED_BY), classes, facts()); } Facts facts() { table.withTableConstraints(tableConstraints); - return new Facts(tables, profileViewable, tableProfiles, columnProfiles); + return new Facts(tables, profileViewable, tableProfiles, columnProfiles, deleted); } Map classes() { @@ -605,30 +776,52 @@ Map classes() { } private List orderRows() { - final var join = List.of(joinColumn()); + final var rows = new ArrayList(); if (joinOnContributingTable) { - return List.of( - row(ORDER, ORDERS_TABLE, subjectRole, subjectKey, subjectFilter, List.of()), - row(ORDER, LINKS_TABLE, OntologyBindingRole.CONTRIBUTING, subjectKey, null, join)); + final var identityJoin = + identityJoinStatus == null + ? List.of() + : List.of(joinColumn(identityJoinStatus)); + rows.add(row(ORDER, ORDERS_TABLE, subjectRole, subjectKey, subjectFilter, identityJoin)); + rows.add( + row( + ORDER, + LINKS_TABLE, + OntologyBindingRole.CONTRIBUTING, + subjectKey, + null, + List.of(joinColumn(joinStatus)))); + } else { + rows.add( + row( + ORDER, + ORDERS_TABLE, + subjectRole, + subjectKey, + subjectFilter, + joinChildren.isEmpty() ? List.of() : List.of(joinColumn(joinStatus)))); + } + for (int index = 0; index < otherTables; index++) { + rows.add( + row( + ORDER, + new UUID(2, index + 1), + OntologyBindingRole.CONTRIBUTING, + subjectKey, + null, + List.of())); } - return List.of( - row( - ORDER, - ORDERS_TABLE, - subjectRole, - subjectKey, - subjectFilter, - joinChildren.isEmpty() ? List.of() : join)); + return rows; } - private OntologyColumnBinding joinColumn() { + private OntologyColumnBinding joinColumn(final OntologyJoinStatus status) { return new OntologyColumnBinding() .withPropertyId(PLACED_BY) .withColumnPath(List.of(joinChildren.isEmpty() ? "customer_id" : joinChildren.getFirst())) .withJoin( new OntologyColumnJoin() .withTargetAssetId(CUSTOMERS_TABLE) - .withStatus(joinStatus) + .withStatus(status) .withOn( IntStream.range(0, joinChildren.size()) .mapToObj( From 02af11203bf7ead7ac9bb8c2789b2572f44344fa Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 23:01:09 -0800 Subject: [PATCH 062/203] Test the bound and the order of the binding read, the second read, and run the statement counts alone --- .../2026-11-22-a-count-is-exact-or-absent.md | 44 +- .../NativeOntologyDataGraphCountBoundIT.java | 413 ++++++++++++++++++ .../tests/NativeOntologyDataGraphCountIT.java | 2 + .../tests/NativeOntologyGraphScanProbe.java | 16 + 4 files changed, 463 insertions(+), 12 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java diff --git a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md index 1b73313020c4..f97d7e0182e9 100644 --- a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md +++ b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md @@ -1,9 +1,9 @@ # A record or link count comes from the stored profiles when they are exact, and is absent when they are not - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (a class cut by the first read is read again, a deleted table holds no join, a distinct count taken after a transform is not exact) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCountRulesTest`, `NativeOntologyDataGraphCountIT` +- **Guard:** `OntologyCountRulesTest`, `NativeOntologyDataGraphCountIT`, `NativeOntologyDataGraphCountBoundIT` - **Related:** ADR:2026-11-21-graph-table-assets-carry-latest-profile-facts (the profile facts this record does not reuse), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, subject key and joins that a count reads), ADR:2026-11-22-record-statements-start-from-the-identity-table (the identity table and the join that a count follows) ## Context @@ -62,13 +62,28 @@ primary key on an engine that checks it. **Records of a class** need an identity binding with no row filter on a table the reader may view and may view the data profile of. A key of one column counts `distinctCount` of that column when -its metrics covered the table. A key of several columns needs the key to be unique, every key +its metrics covered the table and the profiler did not count its distinct values after a transform +(next paragraph). A key of several columns needs the key to be unique, every key column's metrics to have covered the table and at most one key column to hold nulls. The count is `valuesCount` of that column, or of any key column when none holds nulls. +**A distinct count taken after a transform is not exact.** The profiler counts +`count(distinct(CountFn(column)))`, and `CountFn` changes the value first for some column types. On +SQL Server, Azure SQL, Synapse and Fabric (one `mssql` dialect) a `TEXT`, `MEDIUMTEXT` or `NTEXT` +column is cast to `nvarchar` with no length, which keeps 30 characters, and an `IMAGE` column is +cast to `varbinary` with no length, which keeps 30 bytes, so two values that share that prefix +count once. On Oracle a `BYTES`, `BYTEA`, `BINARY`, `VARBINARY` or `BLOB` column is counted as +`DBMS_LOB.GETLENGTH(column)`, so the count is the number of distinct lengths. The records of a key +of one column of such a type on such an engine are `notDerivable`. The list is in +`OntologyCountRules`, with the profiler functions it comes from. `valuesCount` and `nullCount` are +not changed by any transform, because a cast or a length of a null is null and of a value is never +null, so a link count, which reads those two and asks `distinctCount` to equal `valuesCount`, and a +count of a key of several columns, which reads `valuesCount`, are as exact as before. + **Links of a relation** need the join that `OntologyRelationPath.lookup` finds for the relation onto the identity table of the related class, confirmed and held by the identity binding of the -first class. A join held by a contributing table gives no count. The join's parent columns are the +first class. A join held by a contributing table gives no count, and a contributing table that does not exist +holds no join, as in the statements of the mapping. The join's parent columns are the related class's subject key in order. Neither identity binding has a row filter. The key of the first class is unique and holds no nulls. The metrics of every child column covered the whole table and at most one holds nulls. The count is `valuesCount` of that child column, or of any child @@ -77,11 +92,22 @@ the related table still counts. The reader needs the data profile right on the f and the right to view the related class's table. **The counts are read again for each response, with one read for each kind.** One statement reads -the binding rows of all classes of the response, with the identity row of each class first. The +the binding rows of all classes of the response, with the identity row of each class first and at +most five rows for each class. The identity tables come from one batch read with their columns, constraints, partition and profiler configuration. One statement reads their latest table profiles, and one reads the latest column profiles of their key columns and join columns. A page of 60 classes and 500 edges runs those four -reads and no query for a class or an edge. Nothing is stored and nothing is cached. The counts are +reads and no query for a class or an edge. + +A class whose first read reached five rows may bind more tables, and a table not read could hold +the join of a relation. When a relation's first class is cut that way, its identity table gives a +count and the rows read hold no confirmed join for the relation, the class is read again as the +statements of the mapping read it: its identity row and its contributing rows, at most 33, in one +statement for each group of 14 such classes, so that no scan maps more than 500 rows. A page where +no class is cut runs no such statement. A page of 60 classes of which every one is cut runs five. +A class over the 32 contributing tables that a statement accepts has no state for its join and its +links are `notDerivable`. Because of this read, the state of `links` never depends on how many +tables the first class binds. Nothing is stored and nothing is cached. The counts are not part of `contextDigest`, so a count changing between two pages never refuses a cursor. ## Consequences @@ -92,12 +118,6 @@ A profile taken by a workflow that runs outside the platform can use a partition neither the table nor the profile records. A count from such a profile covers that window. This is a known limit of reading stored profiles. -A class whose read reaches five table rows, its identity table and four more, may bind more, and is -read as far as that goes. -When the identity table of such a class holds no confirmed join for a relation, the relation is -`notDerivable` and not `noJoin` or `joinNotConfirmed`, because a table not read could hold the -join. - A class with a row filter, a sampled or partitioned table, or a key that no metric or enforced constraint proves unique has no count here. A query over the table is the way to count it, and that is not part of this record. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java new file mode 100644 index 000000000000..b9f63111091e --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java @@ -0,0 +1,413 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.clusterPage; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.graphPage; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertionRequest; +import static org.openmetadata.it.tests.OntologyBindingFixtures.graph; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.OssTestServer; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateTableProfile; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.api.data.NativeOntologyCount.State; +import org.openmetadata.schema.api.data.NativeOntologyDataGraphPage; +import org.openmetadata.schema.api.data.NativeOntologyLoadedPrefix; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * What the data graph says about a class that binds more tables than one read of its bindings + * keeps. A class with a hub of table rows still counts its records and the relations onto it. A + * relation from a class with other tables states the join the statements of the mapping would + * find, whatever the number of its tables, and a page of such classes runs a fixed number of + * statements, each scan of bindings well inside one scan page. + */ +@Isolated("Counts SQL statements while serving the native data graph over HTTP") +@ExtendWith(TestNamespaceExtension.class) +class NativeOntologyDataGraphCountBoundIT extends BaseOntologyApprovalIT { + private static final Logger LOG = + LoggerFactory.getLogger(NativeOntologyDataGraphCountBoundIT.class); + private static final long PROFILED_AT = 1_700_000_000_000L; + private static final int SPOKES = 59; + private static final int OTHER_ROWS_PER_SPOKE = 4; + + /** What the statements of the mapping accept, which a class over it is refused for. */ + private static final int MAX_CONTRIBUTING_TABLES = 32; + + /** One scan page of 500 rows holds the identity row and 33 contributing rows of 14 classes. */ + private static final int CLASSES_READ_BY_ONE_STATEMENT = 500 / (MAX_CONTRIBUTING_TABLES + 2); + + private static final String HOLDER_STATEMENT = "bindingrole in ("; + + @Test + void aHubOfTableRowsKeepsItsRecordsAndEveryRelationOntoItKeepsItsLinks(final TestNamespace ns) { + final Star star = star(ns, "hub", OntologyJoinStatus.CONFIRMED, 0); + insertFakeRows(star.hub(), 400, 0); + + final var observed = new NativeOntologyGraphScanProbe.ScanObservation(); + final Loaded all = observed.watch(() -> loadAll(star.ontology())); + + assertEquals(exact(77), all.records().get(star.hub().getId())); + for (int index = 0; index < SPOKES; index++) { + final UUID spoke = star.spokes().get(index).getId(); + assertEquals(exact(1000 + index), all.records().get(spoke)); + assertEquals(exact(10 + index), all.links().get(spoke)); + } + assertEquals(SPOKES, all.links().size()); + assertEquals( + 0, + observed.bindingSql().stream().filter(sql -> sql.contains(HOLDER_STATEMENT)).count(), + "No class is cut with no confirmed join, so no class is read again"); + observed.assertBounded(); + } + + @Test + void aPageOfClassesThatAreAllCutIsReadAgainInAFixedNumberOfStatements(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Counts the embedded server's SQL statements"); + final Star whole = star(ns, "none", OntologyJoinStatus.CONFIRMED, 0); + final Star cut = star(ns, "cut", OntologyJoinStatus.INFERRED, OTHER_ROWS_PER_SPOKE); + insertFakeRows(whole.hub(), 400, 0); + + final Loaded wholeAll = loadAll(whole.ontology()); + final var wholePage = new NativeOntologyGraphScanProbe.ScanObservation(); + wholePage.watch(() -> lastPage(whole.ontology(), wholeAll)); + final Loaded cutAll = loadAll(cut.ontology()); + final var cutPage = new NativeOntologyGraphScanProbe.ScanObservation(); + final var page = cutPage.watch(() -> lastPage(cut.ontology(), cutAll)); + + final long wholeReads = holderStatements(wholePage); + final long cutReads = holderStatements(cutPage); + LOG.info( + "Last page of {} classes: no class cut {} SELECT statements and {} second reads; every" + + " class cut {} SELECT statements and {} second reads, binding scans mapped {}", + SPOKES + 1, + wholePage.selects(), + wholeReads, + cutPage.selects(), + cutReads, + cutPage.bindingRows()); + assertEquals(0, wholeReads); + assertEquals( + Math.ceilDiv(SPOKES, CLASSES_READ_BY_ONE_STATEMENT), + cutReads, + "Every cut class is read again, in groups that fit one scan page"); + assertEquals(wholePage.selects() + cutReads, cutPage.selects()); + cutPage.assertBounded(); + wholePage.assertBounded(); + assertEquals(SPOKES, page.getTopology().getEdges().size()); + page.getTopology() + .getEdges() + .forEach(edge -> assertEquals(state(State.JOIN_NOT_CONFIRMED), edge.getLinks())); + } + + @Test + void aClassWithOtherTablesAndOnlyAnInferredJoinOnItsIdentityTableIsNotConfirmed( + final TestNamespace ns) { + final Pair pair = pair(ns, "inferred", OntologyJoinStatus.INFERRED); + bindOtherTables(ns, pair, 6); + + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + } + + @Test + void aClassWithOtherTablesAndNoJoinHasNoJoin(final TestNamespace ns) { + final Pair pair = pair(ns, "nojoin", null); + bindOtherTables(ns, pair, 6); + + assertEquals(state(State.NO_JOIN), links(pair)); + } + + @Test + void aConfirmedJoinOnADeletedContributingTableLeavesTheInferredJoinOfTheIdentityTable( + final TestNamespace ns) { + final Pair pair = pair(ns, "deleted", OntologyJoinStatus.INFERRED); + bindOtherTables(ns, pair, 6); + insertFakeRow( + pair.spoke(), + new UUID(0, 99), + List.of( + column(pair.relation(), "hub_id") + .withJoin(join(pair.hubTable(), OntologyJoinStatus.CONFIRMED, "hub_id", "id")))); + + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + } + + @Test + void aClassOverTheContributingTableLimitGivesNoJoinState(final TestNamespace ns) { + final Pair pair = pair(ns, "overlimit", OntologyJoinStatus.INFERRED); + insertFakeRows(pair.spoke(), MAX_CONTRIBUTING_TABLES + 1, 0); + + assertEquals(state(State.NOT_DERIVABLE), links(pair)); + } + + @Test + void aClassAtTheContributingTableLimitStillStatesItsJoin(final TestNamespace ns) { + final Pair pair = pair(ns, "atlimit", OntologyJoinStatus.INFERRED); + insertFakeRows(pair.spoke(), MAX_CONTRIBUTING_TABLES, 0); + + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + } + + private static long holderStatements( + final NativeOntologyGraphScanProbe.ScanObservation observed) { + return observed.bindingSql().stream().filter(sql -> sql.contains(HOLDER_STATEMENT)).count(); + } + + private static NativeOntologyCount links(final Pair pair) { + final var graph = graph(admin(), pair.ontology(), ""); + assertEquals(1, graph.getEdges().size()); + return graph.getEdges().getFirst().getLinks(); + } + + private static NativeOntologyCount exact(final long value) { + return new NativeOntologyCount() + .withState(State.EXACT) + .withValue(value) + .withProfiledAt(PROFILED_AT); + } + + private static NativeOntologyCount state(final State state) { + return new NativeOntologyCount().withState(state); + } + + /** A hub class and classes that each hold a join onto the hub's identity table. */ + private record Star(Ontology ontology, OntologyConcept hub, List spokes) {} + + private static Star star( + final TestNamespace ns, + final String name, + final OntologyJoinStatus status, + final int otherRows) { + final Ontology ontology = createOntology(ns, name); + final DatabaseSchema schema = OntologyMappingFixtures.schema(ns); + final OntologyConcept hub = declareClass(ontology, "Hub", URI.create("urn:Hub")); + final Table hubTable = + table(schema, ns.prefix(name + "hub"), column("id", ColumnDataType.BIGINT)); + put(admin(), hub, binding(hubTable, OntologyBindingRole.IDENTITY, "id"), 0L); + profile(hubTable, columnProfile("id", 77, 0, 77)); + final List spokes = new ArrayList<>(); + for (int index = 0; index < SPOKES; index++) { + final URI iri = URI.create("urn:C" + index); + final OntologyConcept spoke = declareClass(ontology, "C" + index, iri); + final OntologyProperty relation = objectProperty(ontology, "r" + index, spoke, hub); + admin() + .ontologyAxioms() + .create( + assertionRequest(ontology, iri, URI.create("urn:Hub"), "ax" + index) + .withPropertyIri(relation.getIri())); + final Table spokeTable = + table( + schema, + ns.prefix(name + "c" + index), + column("id", ColumnDataType.BIGINT), + column("hub_id", ColumnDataType.BIGINT)); + put( + admin(), + spoke, + binding(spokeTable, OntologyBindingRole.IDENTITY, "id") + .withColumns( + List.of( + column(relation, "hub_id").withJoin(join(hubTable, status, "hub_id", "id")))), + 0L); + profile( + spokeTable, + columnProfile("id", 1000 + index, 0, 1000 + index), + columnProfile("hub_id", 10 + index, 0, 3)); + insertFakeRows(spoke, otherRows, 0); + spokes.add(spoke); + } + return new Star(ontology, hub, spokes); + } + + /** One class related to a hub class, over an identity table of its own. */ + private record Pair( + Ontology ontology, + OntologyConcept spoke, + Table hubTable, + Table spokeTable, + OntologyProperty relation, + DatabaseSchema schema) {} + + private static Pair pair( + final TestNamespace ns, final String name, final OntologyJoinStatus join) { + final Ontology ontology = createOntology(ns, name); + final DatabaseSchema schema = OntologyMappingFixtures.schema(ns); + final OntologyConcept hub = declareClass(ontology, "Hub", URI.create("urn:Hub")); + final OntologyConcept spoke = declareClass(ontology, "Spoke", URI.create("urn:Spoke")); + final Table hubTable = + table(schema, ns.prefix(name + "hub"), column("id", ColumnDataType.BIGINT)); + final Table spokeTable = + table( + schema, + ns.prefix(name + "spoke"), + column("id", ColumnDataType.BIGINT), + column("hub_id", ColumnDataType.BIGINT)); + final OntologyProperty relation = objectProperty(ontology, "toHub", spoke, hub); + admin() + .ontologyAxioms() + .create( + assertionRequest(ontology, URI.create("urn:Spoke"), URI.create("urn:Hub"), "axT") + .withPropertyIri(relation.getIri())); + put(admin(), hub, binding(hubTable, OntologyBindingRole.IDENTITY, "id"), 0L); + final var identity = binding(spokeTable, OntologyBindingRole.IDENTITY, "id"); + put( + admin(), + spoke, + join == null + ? identity + : identity.withColumns( + List.of(column(relation, "hub_id").withJoin(join(hubTable, join, "hub_id", "id")))), + 0L); + profile(hubTable, columnProfile("id", 5, 0, 5)); + profile(spokeTable, columnProfile("id", 9, 0, 9), columnProfile("hub_id", 9, 0, 5)); + return new Pair(ontology, spoke, hubTable, spokeTable, relation, schema); + } + + /** Real contributing tables, bound after the identity table. */ + private static void bindOtherTables(final TestNamespace ns, final Pair pair, final int count) { + for (int index = 0; index < count; index++) { + final Table other = + table( + pair.schema(), + ns.prefix( + "o" + Integer.toHexString(pair.ontology().getName().hashCode()) + "x" + index), + column("id", ColumnDataType.BIGINT)); + put( + admin(), + pair.spoke(), + binding(other, OntologyBindingRole.CONTRIBUTING, "id"), + index + 1L); + } + } + + private static ColumnProfile columnProfile( + final String name, final double values, final double nulls, final double distinct) { + return new ColumnProfile() + .withName(name) + .withTimestamp(PROFILED_AT) + .withValuesCount(values) + .withNullCount(nulls) + .withDistinctCount(distinct); + } + + private static void profile(final Table table, final ColumnProfile... columns) { + admin() + .getHttpClient() + .execute( + HttpMethod.PUT, + "/v1/tables/" + table.getId() + "/tableProfile", + new CreateTableProfile() + .withTableProfile(new TableProfile().withTimestamp(PROFILED_AT).withRowCount(999d)) + .withColumnProfile(List.of(columns)), + Table.class); + } + + /** Contributing rows to tables that do not exist, ids ascending from {@code base}. */ + private static void insertFakeRows( + final OntologyConcept concept, final int count, final long base) { + for (int index = 1; index <= count; index++) { + insertFakeRow(concept, new UUID(0, base + index), List.of()); + } + } + + private static void insertFakeRow( + final OntologyConcept concept, final UUID id, final List columns) { + Entity.getJdbi() + .useHandle( + handle -> + handle + .createUpdate( + "INSERT INTO ontology_concept_binding " + + "(conceptId, assetId, assetType, assetFqnHash, columnBindings, " + + "bindingRole) VALUES (:conceptId, :assetId, 'table', :hash, " + + ":columns, 'contributing')") + .bind("conceptId", concept.getId().toString()) + .bind("assetId", id.toString()) + .bind("hash", "fake-" + concept.getId() + id) + .bind("columns", JsonUtils.pojoToJson(columns)) + .execute()); + } + + private record Loaded( + List loaded, + Map records, + Map links, + List beforeLast, + int lastOffset) {} + + private static Loaded loadAll(final Ontology ontology) { + final OpenMetadataClient client = admin(); + List loaded = List.of(); + List beforeLast = List.of(); + final Map records = new LinkedHashMap<>(); + final Map links = new LinkedHashMap<>(); + Integer offset = 0; + int lastOffset = 0; + while (offset != null) { + beforeLast = loaded; + lastOffset = offset; + final var response = graphPage(client, ontology, loaded, clusterPage(offset, 12)); + response + .getClusters() + .forEach(cluster -> records.put(cluster.getConcept().getId(), cluster.getRecords())); + response + .getTopology() + .getEdges() + .forEach(edge -> links.put(edge.getFromConceptId(), edge.getLinks())); + loaded = response.getLoaded(); + offset = response.getNextClusterOffset(); + } + return new Loaded(loaded, records, links, beforeLast, lastOffset); + } + + private static NativeOntologyDataGraphPage lastPage(final Ontology ontology, final Loaded all) { + return graphPage(admin(), ontology, all.beforeLast(), clusterPage(all.lastOffset(), 12)); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java index d86d87b4e54d..b1c9946095ee 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java @@ -39,6 +39,7 @@ import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.RdfAccessFixtures; import org.openmetadata.it.util.TestNamespace; @@ -75,6 +76,7 @@ * POST /dataGraph/pages}, read from the stored profiles of identity tables. Every case compares * the whole graph, with each entity reference cut down to the id, type and name that identify it. */ +@Isolated("Counts SQL statements while serving the native data graph over HTTP") @ExtendWith(TestNamespaceExtension.class) class NativeOntologyDataGraphCountIT extends BaseOntologyApprovalIT { private static final Logger LOG = LoggerFactory.getLogger(NativeOntologyDataGraphCountIT.class); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyGraphScanProbe.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyGraphScanProbe.java index 946790c759c1..e57da1919e16 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyGraphScanProbe.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyGraphScanProbe.java @@ -256,6 +256,8 @@ static final class ScanObservation { private static final int PAGE = 500; private final List bindingRows = new CopyOnWriteArrayList<>(); private final List axiomRows = new CopyOnWriteArrayList<>(); + private final List bindingSql = new CopyOnWriteArrayList<>(); + private final AtomicInteger selects = new AtomicInteger(); private final AtomicInteger largestInList = new AtomicInteger(); private final AtomicBoolean boundedRows = new AtomicBoolean(true); @@ -281,6 +283,16 @@ List axiomRows() { return List.copyOf(axiomRows); } + /** The lower-cased text of each binding scan statement, in the order they ran. */ + List bindingSql() { + return List.copyOf(bindingSql); + } + + /** Every SELECT statement of the observed requests. */ + int selects() { + return selects.get(); + } + int largestInList() { return largestInList.get(); } @@ -290,12 +302,16 @@ private boolean record(final StatementContext statement) { if (!sql.contains("select")) { return false; } + selects.incrementAndGet(); final var lists = IN_LIST.matcher(sql); while (lists.find()) { largestInList.accumulateAndGet(lists.group(1).split(",").length, Math::max); } final var rows = scanRows(sql); if (rows != null) { + if (rows == bindingRows) { + bindingSql.add(sql); + } boundedRows.compareAndSet(true, sql.contains(" limit ")); statement.addCleanable( () -> { From 6cb34feb9f91c0765a52ac9b1e6945903c4970dd Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 22 Nov 2026 23:29:24 -0800 Subject: [PATCH 063/203] Insert the test's binding rows with a jsonb cast on Postgres --- .../it/tests/NativeOntologyDataGraphCountBoundIT.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java index b9f63111091e..d302717976ee 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java @@ -36,6 +36,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; @@ -59,6 +60,7 @@ import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.locator.ConnectionType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -367,7 +369,8 @@ private static void insertFakeRow( "INSERT INTO ontology_concept_binding " + "(conceptId, assetId, assetType, assetFqnHash, columnBindings, " + "bindingRole) VALUES (:conceptId, :assetId, 'table', :hash, " - + ":columns, 'contributing')") + + columnsParameter() + + ", 'contributing')") .bind("conceptId", concept.getId().toString()) .bind("assetId", id.toString()) .bind("hash", "fake-" + concept.getId() + id) @@ -375,6 +378,12 @@ private static void insertFakeRow( .execute()); } + private static String columnsParameter() { + return TestSuiteBootstrap.getConnectionType() == ConnectionType.POSTGRES + ? "(:columns :: jsonb)" + : ":columns"; + } + private record Loaded( List loaded, Map records, From 7f700cc7a30cf52c816bed3e8b14ff8f828f808f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 00:41:22 -0800 Subject: [PATCH 064/203] Count an inverse link from a record of the class that binds the relation --- ...tatements-start-from-the-identity-table.md | 40 +++++----- .../it/tests/OntologyLinkCountIT.java | 16 +++- .../ontology/OntologyConceptSqlGenerator.java | 29 ++++---- .../OntologyAggregateStatementTest.java | 74 ++++++++++++++++--- .../service/ontology/OntologyLinkShapes.java | 74 ++++++++++++++++--- .../ontology/OntologyStatementGoldenTest.java | 2 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../linkFilteredStart-links-inverse.sql | 1 + .../bigquery/linkLinkTable-links-inverse.sql | 5 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../linkFilteredStart-links-inverse.sql | 1 + .../linkLinkTable-links-inverse.sql | 5 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../mysql/linkFilteredStart-links-inverse.sql | 1 + .../mysql/linkLinkTable-links-inverse.sql | 5 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../linkFilteredStart-links-inverse.sql | 1 + .../postgres/linkLinkTable-links-inverse.sql | 5 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../linkFilteredStart-links-inverse.sql | 1 + .../redshift/linkLinkTable-links-inverse.sql | 5 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../linkFilteredStart-links-inverse.sql | 1 + .../snowflake/linkLinkTable-links-inverse.sql | 5 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../spark/linkFilteredStart-links-inverse.sql | 1 + .../spark/linkLinkTable-links-inverse.sql | 5 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../trino/linkFilteredStart-links-inverse.sql | 1 + .../trino/linkLinkTable-links-inverse.sql | 5 +- .../linkCompositeLinkTable-links-inverse.sql | 7 +- ...linkFilteredContributing-links-forward.sql | 10 +++ ...linkFilteredContributing-links-inverse.sql | 11 +++ .../linkFilteredLinkTable-links-inverse.sql | 6 +- .../tsql/linkFilteredStart-links-inverse.sql | 1 + .../tsql/linkLinkTable-links-inverse.sql | 5 +- .../ontologyAggregateStatementRequest.json | 2 +- .../api/data/ontologyStatementPlan.json | 2 +- 62 files changed, 473 insertions(+), 126 deletions(-) create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-inverse.sql diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md index 19f05161c85a..0e1af4a8379a 100644 --- a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -184,21 +184,21 @@ gains `measure`, one of `topRecords`, which is the default and the answer it alw an aggregate over a relation, the binding revision of both classes, and one column of the kind `count`. -**The link count is the number of distinct pairs of a start record key and a related key along the -confirmed join.** The statement returns one row with one column. - -- A start record is a row of the identity table of the start class that passes its row filter and - has no null in any part of its subject key. -- A related key is the value of the columns that hold the join. A forward path reads it from the - table that holds the join, which is the start table or a link table. An inverse path reads it - from the subject key of the class that binds the relation, which is that class's identity table - when it holds the join, or the columns of the link table that pair with that key. A related key - counts when no part of it is null. -- A related key counts whether or not a record of the related class holds it. The statement never - joins the identity table of the related class to prove that a record exists, and the row filter - of the related class never applies. A stored profile counts a reference in the same way, so the - two counts agree on the same rows. The row filter of a link table applies, because it says which - rows of that table are links. +**The link count is the number of distinct links of the relation.** The statement returns one row +with one column. + +- A link is a pair of a record of the class that binds the relation and an object key with no null + part. The record passes the row filter of the binding class and has a whole key. Over a link + table or another contributing table, the row of that table joins the record on the subject key + and passes the table's own row filter. +- The object need not be a record. A key that no row of the object class holds still counts. +- Forward from the binding class, the count is every link. The statement starts at the identity + table of the binding class and reads the object key from the columns that hold the join. +- Inverse from the other class, the count is the links whose object is a record of the start class. + The statement starts at the identity table of the start class and joins the identity table of the + binding class, through the link table when one holds the join. It applies the row filter and the + whole-key rule of the binding class, and the row filter of the link table. +- The row filter of the object class applies only when the count starts from it. - Two rows that give one pair count once, so a link table that repeats a pair does not count it twice. @@ -206,10 +206,10 @@ confirmed join.** The statement returns one row with one column. 409, a table the reader may not view is a 403 that names the class, and the version rules are the ones above. The count form has no `ORDER BY` and no row limit, and the plan gives `rowCap` 1. -**A forward count and an inverse count of one relation can differ.** Forward, the start class holds -the join, so a reference to a key that no related row holds is counted. Inverse, the start class is -the one that a reference points to, so a reference to a key that no start record holds is not a pair -of a start record. A client that wants the links of the relation as a whole asks forward from the -class that binds it. +**A forward count and an inverse count of one relation can differ.** They differ by the links whose +object key is no record of the object class: forward counts them, and inverse never does, because +the start class is the object class. A stored profile counts a reference in the same way as the +forward count, so the agreement with the stored-profile count holds for the forward count only. A +client that wants the links of the relation as a whole asks forward from the class that binds it. Guard: `OntologyAggregateStatementTest`, `OntologyStatementGoldenTest` and `OntologyLinkCountIT`. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java index d85258a65db4..3e0a71abc26a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java @@ -53,7 +53,7 @@ import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; /** - * Asks the aggregate endpoint for the number of links of a relation, over each of six mappings of + * Asks the aggregate endpoint for the number of links of a relation, over each of seven mappings of * a relation with the tables created in the database this suite runs on, and runs the statement * that comes back. A statement must be the golden text of its engine family, and the number it * returns must be the one that a person worked out from the rows. @@ -77,10 +77,10 @@ void aRelationHeldInAColumnCountsEachDistinctPairWithAKeyOnBothSides(final TestN } @Test - void aStartRowThatTheRowFilterExcludesIsNeverCountedAndTheRelatedFilterNeverApplies( + void aLinkCountsOnlyARecordThatPassesTheRowFilterOfTheClassThatBindsTheRelation( final TestNamespace ns) { assertEquals( - List.of(List.of(List.of("4")), List.of(List.of("3"))), + List.of(List.of(List.of("4")), List.of(List.of("2"))), links(ns, OntologyLinkShapes.FILTERED_START)); } @@ -108,10 +108,18 @@ void aLinkTableOverATwoColumnKeyCountsEachPairOnce(final TestNamespace ns) { @Test void aLinkTableOfAFilteredClassCountsOnlyTheLinksOfTheRecordsThatItKeeps(final TestNamespace ns) { assertEquals( - List.of(List.of(List.of("3")), List.of(List.of("3"))), + List.of(List.of(List.of("3")), List.of(List.of("2"))), links(ns, OntologyLinkShapes.FILTERED_LINK_TABLE)); } + @Test + void aTableThatHoldsARelationWithARowFilterOfItsOwnCountsOnlyTheRowsItKeeps( + final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("2")), List.of(List.of("1"))), + links(ns, OntologyLinkShapes.FILTERED_CONTRIBUTING)); + } + @Test void aRequestWithNoMeasureStillGivesTheRecordsThatRelateToTheMost(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "defaultMeasure"); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index 90f1254ac027..5b98933baa22 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -303,26 +303,25 @@ static RecordStatement top(final OntologyRelationPath path) { } /** - * The number of links of a relation in one row: the distinct pairs of a start record key and a - * related key along the join the path follows. A start record passes the row filter of its - * identity table and holds no null key part. A related key is the value of the columns that hold - * the join, so it counts when no part of it is null, whether or not a record of the related - * class holds it. The row filter of the related class never applies, and its identity table is - * read only when it holds the join itself. The statement has no {@code ORDER BY} and no row - * limit. + * The number of links of a relation in one row. A link is a pair of a record of the class that + * binds the relation and an object key with no null part. The record passes the row filter of + * its identity table and has a whole key. Over a link table or another contributing table, the + * row of that table joins the record on the subject key and passes the table's own row filter. + * The object need not be a record. The statement has no {@code ORDER BY} and no row limit. * - *

    A forward path reads the related key from the columns of the table that holds the join, - * the start table or the link table. An inverse path reads it from the key of the class that - * binds the relation: its identity table when that table holds the join, or the columns of the - * link table that pair with that key. The row filter of a link table applies, because it says - * which rows of that table are links. + *

    Forward from the binding class, the count is every link: the statement starts at the + * binding class's identity table and reads the object key from the columns that hold the join. + * Inverse from the other class, the count is the links whose object is a record of the start + * class: the statement starts at the start class's identity table, joins the binding class's + * identity table, through the link table when one holds the join, and applies that table's row + * filter and whole-key rule. The row filter of the object class applies only when the count + * starts from it. */ static RecordStatement links(final OntologyRelationPath path) { final MappedTable identity = path.start().identity(); final List joins = path.joins(); final Joined last = joins.getLast(); - final boolean namesKeyOnly = - path.direction() == OntologyStatementDirection.FORWARD || joins.size() > 1; + final boolean namesKeyOnly = path.direction() == OntologyStatementDirection.FORWARD; final List read = namesKeyOnly ? joins.subList(0, joins.size() - 1) : joins; final String relatedAlias = alias(read.size()); final List> related = @@ -344,7 +343,7 @@ static RecordStatement links(final OntologyRelationPath path) { keyIsSet(keys, identity, FIRST); rowFilter(keys, identity, FIRST); related.forEach(part -> keys.where().column(relatedAlias, part).sql(" IS NOT NULL")); - final int filtered = namesKeyOnly ? read.size() : read.size() - 1; + final int filtered = read.size(); for (int index = 0; index < filtered; index++) { rowFilter(keys, read.get(index).table(), alias(index + 1)); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java index ef062169e048..a8aaf2d0379c 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java @@ -168,7 +168,7 @@ void aLinkCountGoingBackJoinsTheClassThatHoldsTheColumnAndReadsItsKey() { } @Test - void aLinkCountNeverReadsTheTableOfTheRelatedClassWhenALinkTableHoldsTheJoin() { + void aLinkCountGoingBackOverALinkTableJoinsTheIdentityTableOfTheClassThatBindsTheRelation() { final RecordStatement forward = OntologyConceptSqlGenerator.links( model(LINK_TABLE, POSTGRES).path("Order", "contains", FORWARD)); @@ -186,20 +186,22 @@ void aLinkCountNeverReadsTheTableOfTheRelatedClassWhenALinkTableHoldsTheJoin() { sql(forward)); assertEquals( "SELECT COUNT(*) AS links\nFROM (\n" - + " SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0\n" + + " SELECT DISTINCT t0.sku AS k0, t2.id AS r0\n" + " FROM shop.products t0\n" + " JOIN shop.order_items t1 ON t1.product_sku = t0.sku\n" + + " JOIN shop.orders t2 ON t2.id = t1.order_id\n" + " WHERE t0.sku IS NOT NULL\n" - + " AND t1.order_id IS NOT NULL\n) k", + + " AND t2.id IS NOT NULL\n) k", sql(inverse)); assertEquals(List.of("orders", "order_items"), read(forward)); - assertEquals(List.of("products", "order_items"), read(inverse)); + assertEquals(List.of("products", "order_items", "orders"), read(inverse)); assertEquals(List.of("0 count Product"), plan(forward)); assertEquals(List.of("0 count Order"), plan(inverse)); } @Test - void aLinkCountKeepsTheRowFilterOfTheStartClassAndOfALinkTableButNotOfTheRelatedClass() { + void + aLinkCountKeepsTheRowFilterOfTheClassThatBindsTheRelationAndOfALinkTableAndNeverOfTheObjectClass() { final OntologyMappingShapeModel filtered = OntologyExpandStatementTest.filteredLinkTable("Mssql"); @@ -215,16 +217,63 @@ void aLinkCountKeepsTheRowFilterOfTheStartClassAndOfALinkTableButNotOfTheRelated sql(OntologyConceptSqlGenerator.links(filtered.path("Order", "contains", FORWARD)))); assertEquals( "SELECT COUNT(*) AS links\nFROM (\n" - + " SELECT DISTINCT t0.[sku] AS k0, t1.[order_id] AS r0\n" + + " SELECT DISTINCT t0.[sku] AS k0, t2.[id] AS r0\n" + " FROM [shop].[products] t0\n" + " JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku]\n" + + " JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id]\n" + " WHERE t0.[sku] IS NOT NULL\n" + " AND t0.[title] <> N'Drill'\n" - + " AND t1.[order_id] IS NOT NULL\n" - + " AND t1.[quantity] > 0\n) k", + + " AND t2.[id] IS NOT NULL\n" + + " AND t1.[quantity] > 0\n" + + " AND t2.[channel] = N'web'\n) k", sql(OntologyConceptSqlGenerator.links(filtered.path("Product", "contains", INVERSE)))); } + @Test + void aLinkCountGoingBackOverAFilteredColumnKeepsTheRowFilterOfBothClasses() { + final OntologyMappingShapeModel parties = + new OntologyMappingShapeModel(OntologyLinkShapes.FILTERED_START, POSTGRES); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t1.id AS r0\n" + + " FROM shop.parties t0\n" + + " JOIN shop.parties t1 ON t1.employer_id = t0.id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t0.kind = 'organization'\n" + + " AND t1.id IS NOT NULL\n" + + " AND t1.kind = 'person'\n) k", + sql(OntologyConceptSqlGenerator.links(parties.path("Organization", "worksFor", INVERSE)))); + } + + @Test + void aLinkCountOverATableThatIsNoLinkTableKeepsItsRowFilterInBothDirections() { + final OntologyMappingShapeModel details = + new OntologyMappingShapeModel(OntologyLinkShapes.FILTERED_CONTRIBUTING, POSTGRES); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t1.customer_id AS r0\n" + + " FROM shop.orders t0\n" + + " JOIN shop.order_details t1 ON t1.order_id = t0.id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t0.channel = 'web'\n" + + " AND t1.customer_id IS NOT NULL\n" + + " AND t1.region = 'eu'\n) k", + sql(OntologyConceptSqlGenerator.links(details.path("Order", "placedBy", FORWARD)))); + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t2.id AS r0\n" + + " FROM shop.customers t0\n" + + " JOIN shop.order_details t1 ON t1.customer_id = t0.id\n" + + " JOIN shop.orders t2 ON t2.id = t1.order_id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t2.id IS NOT NULL\n" + + " AND t1.region = 'eu'\n" + + " AND t2.channel = 'web'\n) k", + sql(OntologyConceptSqlGenerator.links(details.path("Customer", "placedBy", INVERSE)))); + } + @Test void aLinkCountOverATwoColumnJoinNeedsEachColumnToBeSet() { final OntologyMappingShapeModel branches = @@ -250,18 +299,19 @@ void aLinkCountOverATwoColumnJoinNeedsEachColumnToBeSet() { } @Test - void aLinkCountOverALinkTableOfATwoColumnKeyReadsBothPairedColumns() { + void aLinkCountOverALinkTableOfATwoColumnKeyJoinsTheOrderOnBothPairedColumns() { final OntologyMappingShapeModel lines = new OntologyMappingShapeModel(OntologyLinkShapes.COMPOSITE_LINK_TABLE, POSTGRES); assertEquals( "SELECT COUNT(*) AS links\nFROM (\n" - + " SELECT DISTINCT t0.sku AS k0, t1.tenant AS r0, t1.order_no AS r1\n" + + " SELECT DISTINCT t0.sku AS k0, t2.tenant AS r0, t2.order_no AS r1\n" + " FROM shop.products t0\n" + " JOIN shop.order_lines t1 ON t1.sku = t0.sku\n" + + " JOIN shop.orders t2 ON t2.tenant = t1.tenant AND t2.order_no = t1.order_no\n" + " WHERE t0.sku IS NOT NULL\n" - + " AND t1.tenant IS NOT NULL\n" - + " AND t1.order_no IS NOT NULL\n) k", + + " AND t2.tenant IS NOT NULL\n" + + " AND t2.order_no IS NOT NULL\n) k", sql(OntologyConceptSqlGenerator.links(lines.path("Product", "contains", INVERSE)))); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java index 7d15613a749e..61a736ae42d0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java @@ -13,8 +13,10 @@ package org.openmetadata.service.ontology; +import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; import static org.openmetadata.service.ontology.OntologyMappingShapes.columns; import static org.openmetadata.service.ontology.OntologyMappingShapes.contributing; +import static org.openmetadata.service.ontology.OntologyMappingShapes.data; import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; import static org.openmetadata.service.ontology.OntologyMappingShapes.joined; @@ -27,16 +29,18 @@ import org.openmetadata.schema.api.data.OntologyStatementDirection; import org.openmetadata.schema.api.data.OntologyStatementKind; import org.openmetadata.schema.api.data.OntologyStatementMeasure; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyJoinStatus; import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; /** - * Six mappings of one relation, each with the two link counts of its relation, one for each + * Seven mappings of one relation, each with the two link counts of its relation, one for each * direction. Their tables hold the rows that a link count must treat each in its own way: a * related key with a null part, a pair stored twice, a start row the row filter excludes, a key * that no related row holds, and a link table that repeats a pair. Each count is a literal that a @@ -103,8 +107,8 @@ private OntologyLinkShapes() {} * organization, and the vendor row 5 is no person. * *

    Forward, the pairs are (1,10), (2,10), (4,99) and (6,11). Inverse, only organization 10 is - * a start record, and the related key is the key of each row that names it, whatever its kind: - * persons 1 and 2 and vendor 5. + * a start record, and a link is a pair with a person, so persons 1 and 2 count and vendor 5, + * which the person filter excludes, does not. */ public static final Shape FILTERED_START = new Shape( @@ -136,7 +140,7 @@ private OntologyLinkShapes() {} "parties", List.of("id"), new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "organization"))), - both("Person", "Organization", "worksFor", LINKS_TO_ORGANIZATION, 4, LINKS_TO_PERSON, 3)); + both("Person", "Organization", "worksFor", LINKS_TO_ORGANIZATION, 4, LINKS_TO_PERSON, 2)); /** * 3. A relation held in two columns, with a key of two columns at its far end. Employee 4 has no @@ -216,7 +220,8 @@ private OntologyLinkShapes() {} row(2, "A-1", 1), row(null, "B-2", 1), row(2, null, 3), - row(3, "Z-9", 1))), + row(3, "Z-9", 1), + row(7, "A-1", 1))), List.of("Order", "Product"), List.of(relation("contains", "Order", "Product")), List.of( @@ -278,8 +283,8 @@ private OntologyLinkShapes() {} * 6. A link table whose class holds a row filter. Order 2 is a store order that the filter * excludes, and its line links product A-1. Order 3 holds Z-9 twice and one line with no product. * - *

    Forward, the pairs are (1,A-1), (1,B-2) and (3,Z-9). Inverse, the filter of the order class - * does not apply, so they are product A-1 with orders 1 and 2, and product B-2 with order 1. + *

    Forward, the pairs are (1,A-1), (1,B-2) and (3,Z-9). Inverse, the pairs are product A-1 with + * order 1 and product B-2 with order 1, because order 2 is no record of the filtered class. */ public static final Shape FILTERED_LINK_TABLE = new Shape( @@ -320,7 +325,57 @@ private OntologyLinkShapes() {} "order_items", List.of("order_id"), joined("contains", "product_sku", "products", "sku"))), - both("Order", "Product", "contains", LINKS_TO_PRODUCT, 3, LINKS_TO_ORDER, 3)); + both("Order", "Product", "contains", LINKS_TO_PRODUCT, 3, LINKS_TO_ORDER, 2)); + + /** + * 7. A relation held by a table that is no link table: it carries a data column and a row filter + * of its own, over a class that holds a row filter. Detail (1,us) is a web order that the detail + * filter excludes, order 2 is a store order, order 9 has no order row, and order 3 names no + * customer once and customer 30, which no row holds, once. + * + *

    Forward, the pairs are (1,10) and (3,30). Inverse, they are customer 10 with order 1, since + * order 2 is a store order, order 9 is no order, and customer 30 is no start record. + */ + public static final Shape FILTERED_CONTRIBUTING = + new Shape( + "linkFilteredContributing", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "store"), + row(3, "web")), + table("customers", List.of(integer("id")), row(10), row(20)), + table( + "order_details", + List.of( + integer("order_id"), text("region"), text("note"), integer("customer_id")), + row(1, "eu", "a", 10), + row(1, "us", "b", 20), + row(2, "eu", "c", 10), + row(3, "eu", "d", null), + row(9, "eu", "e", 20), + row(3, "eu", "f", 30))), + List.of("Order", "Customer"), + List.of(relation("placedBy", "Order", "Customer"), data("note", false, "Order")), + List.of( + identity( + "Order", + "orders", + List.of("id"), + new FilterSpec("channel", OntologyRowFilterOperator.EQUALS, "web")), + identity("Customer", "customers", List.of("id"), null), + new BindingSpec( + "Order", + "order_details", + OntologyBindingRole.CONTRIBUTING, + List.of("order_id"), + new FilterSpec("region", OntologyRowFilterOperator.EQUALS, "eu"), + List.of( + bound("note", "note"), + joined("placedBy", "customer_id", "customers", "id")))), + both("Order", "Customer", "placedBy", LINKS_TO_CUSTOMER, 2, LINKS_TO_ORDER, 1)); public static List all() { return List.of( @@ -329,7 +384,8 @@ public static List all() { COMPOSITE_KEY, LINK_TABLE, COMPOSITE_LINK_TABLE, - FILTERED_LINK_TABLE); + FILTERED_LINK_TABLE, + FILTERED_CONTRIBUTING); } /** The link count of a relation from the class that binds it, and from the class it reaches. */ diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java index 8725bd7f497b..14d172d23832 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java @@ -36,7 +36,7 @@ */ class OntologyStatementGoldenTest { private static final int FAMILIES = 9; - private static final int STATEMENTS_OF_THE_SHAPES = 45; + private static final int STATEMENTS_OF_THE_SHAPES = 47; static List goldens() { return OntologyStatementGoldens.all(); diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql index dbfb7a5e2363..32a510750339 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`tenant` AS r0, t1.`order_no` AS r1 + SELECT DISTINCT t0.`sku` AS k0, t2.`tenant` AS r0, t2.`order_no` AS r1 FROM `shop`.`products` t0 JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`tenant` = t1.`tenant` AND t2.`order_no` = t1.`order_no` WHERE t0.`sku` IS NOT NULL - AND t1.`tenant` IS NOT NULL - AND t1.`order_no` IS NOT NULL + AND t2.`tenant` IS NOT NULL + AND t2.`order_no` IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..2ccc475cdf3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`customer_id` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_details` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`customer_id` IS NOT NULL + AND t1.`region` = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..ab9f9b5d58f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t2.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`order_details` t1 ON t1.`customer_id` = t0.`id` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t1.`region` = 'eu' + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql index ab8d2db3e65a..9da24a70a942 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 FROM `shop`.`products` t0 JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` IS NOT NULL - AND t1.`order_id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t2.`channel` = 'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql index 7bea0db92ebf..b90722e8b0de 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0.`id` IS NOT NULL AND t0.`kind` = 'organization' AND t1.`id` IS NOT NULL + AND t1.`kind` = 'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql index ab8d2db3e65a..bf793e25aa17 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 FROM `shop`.`products` t0 JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` IS NOT NULL - AND t1.`order_id` IS NOT NULL + AND t2.`id` IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql index dbfb7a5e2363..32a510750339 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`tenant` AS r0, t1.`order_no` AS r1 + SELECT DISTINCT t0.`sku` AS k0, t2.`tenant` AS r0, t2.`order_no` AS r1 FROM `shop`.`products` t0 JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`tenant` = t1.`tenant` AND t2.`order_no` = t1.`order_no` WHERE t0.`sku` IS NOT NULL - AND t1.`tenant` IS NOT NULL - AND t1.`order_no` IS NOT NULL + AND t2.`tenant` IS NOT NULL + AND t2.`order_no` IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..2ccc475cdf3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`customer_id` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_details` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`customer_id` IS NOT NULL + AND t1.`region` = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..ab9f9b5d58f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t2.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`order_details` t1 ON t1.`customer_id` = t0.`id` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t1.`region` = 'eu' + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql index ab8d2db3e65a..9da24a70a942 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 FROM `shop`.`products` t0 JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` IS NOT NULL - AND t1.`order_id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t2.`channel` = 'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql index 7bea0db92ebf..b90722e8b0de 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0.`id` IS NOT NULL AND t0.`kind` = 'organization' AND t1.`id` IS NOT NULL + AND t1.`kind` = 'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql index ab8d2db3e65a..bf793e25aa17 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 FROM `shop`.`products` t0 JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` IS NOT NULL - AND t1.`order_id` IS NOT NULL + AND t2.`id` IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql index dbfb7a5e2363..32a510750339 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`tenant` AS r0, t1.`order_no` AS r1 + SELECT DISTINCT t0.`sku` AS k0, t2.`tenant` AS r0, t2.`order_no` AS r1 FROM `shop`.`products` t0 JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`tenant` = t1.`tenant` AND t2.`order_no` = t1.`order_no` WHERE t0.`sku` IS NOT NULL - AND t1.`tenant` IS NOT NULL - AND t1.`order_no` IS NOT NULL + AND t2.`tenant` IS NOT NULL + AND t2.`order_no` IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..2ccc475cdf3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`customer_id` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_details` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`customer_id` IS NOT NULL + AND t1.`region` = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..ab9f9b5d58f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t2.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`order_details` t1 ON t1.`customer_id` = t0.`id` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t1.`region` = 'eu' + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql index ab8d2db3e65a..9da24a70a942 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 FROM `shop`.`products` t0 JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` IS NOT NULL - AND t1.`order_id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t2.`channel` = 'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql index 7bea0db92ebf..b90722e8b0de 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0.`id` IS NOT NULL AND t0.`kind` = 'organization' AND t1.`id` IS NOT NULL + AND t1.`kind` = 'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql index ab8d2db3e65a..bf793e25aa17 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 FROM `shop`.`products` t0 JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` IS NOT NULL - AND t1.`order_id` IS NOT NULL + AND t2.`id` IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql index 17a05ff8a056..144625529daa 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.tenant AS r0, t1.order_no AS r1 + SELECT DISTINCT t0.sku AS k0, t2.tenant AS r0, t2.order_no AS r1 FROM shop.products t0 JOIN shop.order_lines t1 ON t1.sku = t0.sku + JOIN shop.orders t2 ON t2.tenant = t1.tenant AND t2.order_no = t1.order_no WHERE t0.sku IS NOT NULL - AND t1.tenant IS NOT NULL - AND t1.order_no IS NOT NULL + AND t2.tenant IS NOT NULL + AND t2.order_no IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..a41f5e5db0be --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.customer_id AS r0 + FROM shop.orders t0 + JOIN shop.order_details t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.customer_id IS NOT NULL + AND t1.region = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..76152b181633 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t2.id AS r0 + FROM shop.customers t0 + JOIN shop.order_details t1 ON t1.customer_id = t0.id + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.id IS NOT NULL + AND t2.id IS NOT NULL + AND t1.region = 'eu' + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql index 0468e7f6288d..bcfdb0e8b82c 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 FROM shop.products t0 JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku IS NOT NULL - AND t1.order_id IS NOT NULL + AND t2.id IS NOT NULL + AND t2.channel = 'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql index 59af4ab12b0a..4ec96ff96e16 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0.id IS NOT NULL AND t0.kind = 'organization' AND t1.id IS NOT NULL + AND t1.kind = 'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql index 0468e7f6288d..05a4b13d3306 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 FROM shop.products t0 JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku IS NOT NULL - AND t1.order_id IS NOT NULL + AND t2.id IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql index 17a05ff8a056..144625529daa 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.tenant AS r0, t1.order_no AS r1 + SELECT DISTINCT t0.sku AS k0, t2.tenant AS r0, t2.order_no AS r1 FROM shop.products t0 JOIN shop.order_lines t1 ON t1.sku = t0.sku + JOIN shop.orders t2 ON t2.tenant = t1.tenant AND t2.order_no = t1.order_no WHERE t0.sku IS NOT NULL - AND t1.tenant IS NOT NULL - AND t1.order_no IS NOT NULL + AND t2.tenant IS NOT NULL + AND t2.order_no IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..a41f5e5db0be --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.customer_id AS r0 + FROM shop.orders t0 + JOIN shop.order_details t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.customer_id IS NOT NULL + AND t1.region = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..76152b181633 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t2.id AS r0 + FROM shop.customers t0 + JOIN shop.order_details t1 ON t1.customer_id = t0.id + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.id IS NOT NULL + AND t2.id IS NOT NULL + AND t1.region = 'eu' + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql index 0468e7f6288d..bcfdb0e8b82c 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 FROM shop.products t0 JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku IS NOT NULL - AND t1.order_id IS NOT NULL + AND t2.id IS NOT NULL + AND t2.channel = 'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql index 59af4ab12b0a..4ec96ff96e16 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0.id IS NOT NULL AND t0.kind = 'organization' AND t1.id IS NOT NULL + AND t1.kind = 'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql index 0468e7f6288d..05a4b13d3306 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 FROM shop.products t0 JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku IS NOT NULL - AND t1.order_id IS NOT NULL + AND t2.id IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql index 29ce809fba1f..77dbb5c3f8f1 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0."sku" AS k0, t1."tenant" AS r0, t1."order_no" AS r1 + SELECT DISTINCT t0."sku" AS k0, t2."tenant" AS r0, t2."order_no" AS r1 FROM "shop"."products" t0 JOIN "shop"."order_lines" t1 ON t1."sku" = t0."sku" + JOIN "shop"."orders" t2 ON t2."tenant" = t1."tenant" AND t2."order_no" = t1."order_no" WHERE t0."sku" IS NOT NULL - AND t1."tenant" IS NOT NULL - AND t1."order_no" IS NOT NULL + AND t2."tenant" IS NOT NULL + AND t2."order_no" IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..3dff3943ff49 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."customer_id" AS r0 + FROM "shop"."orders" t0 + JOIN "shop"."order_details" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t0."channel" = 'web' + AND t1."customer_id" IS NOT NULL + AND t1."region" = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..e4d45a965974 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t2."id" AS r0 + FROM "shop"."customers" t0 + JOIN "shop"."order_details" t1 ON t1."customer_id" = t0."id" + JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" + WHERE t0."id" IS NOT NULL + AND t2."id" IS NOT NULL + AND t1."region" = 'eu' + AND t2."channel" = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql index 108d51a6b39b..86070ee987fb 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0."sku" AS k0, t1."order_id" AS r0 + SELECT DISTINCT t0."sku" AS k0, t2."id" AS r0 FROM "shop"."products" t0 JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" + JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" WHERE t0."sku" IS NOT NULL - AND t1."order_id" IS NOT NULL + AND t2."id" IS NOT NULL + AND t2."channel" = 'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql index 4e94f15a2810..46cde6f2cf8a 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0."id" IS NOT NULL AND t0."kind" = 'organization' AND t1."id" IS NOT NULL + AND t1."kind" = 'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql index 108d51a6b39b..0e5a88e96cc3 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0."sku" AS k0, t1."order_id" AS r0 + SELECT DISTINCT t0."sku" AS k0, t2."id" AS r0 FROM "shop"."products" t0 JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" + JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" WHERE t0."sku" IS NOT NULL - AND t1."order_id" IS NOT NULL + AND t2."id" IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql index dbfb7a5e2363..32a510750339 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`tenant` AS r0, t1.`order_no` AS r1 + SELECT DISTINCT t0.`sku` AS k0, t2.`tenant` AS r0, t2.`order_no` AS r1 FROM `shop`.`products` t0 JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`tenant` = t1.`tenant` AND t2.`order_no` = t1.`order_no` WHERE t0.`sku` IS NOT NULL - AND t1.`tenant` IS NOT NULL - AND t1.`order_no` IS NOT NULL + AND t2.`tenant` IS NOT NULL + AND t2.`order_no` IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..2ccc475cdf3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`customer_id` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_details` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`customer_id` IS NOT NULL + AND t1.`region` = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..ab9f9b5d58f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t2.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`order_details` t1 ON t1.`customer_id` = t0.`id` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t1.`region` = 'eu' + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql index ab8d2db3e65a..9da24a70a942 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 FROM `shop`.`products` t0 JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` IS NOT NULL - AND t1.`order_id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t2.`channel` = 'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql index 7bea0db92ebf..b90722e8b0de 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0.`id` IS NOT NULL AND t0.`kind` = 'organization' AND t1.`id` IS NOT NULL + AND t1.`kind` = 'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql index ab8d2db3e65a..bf793e25aa17 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.`sku` AS k0, t1.`order_id` AS r0 + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 FROM `shop`.`products` t0 JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` IS NOT NULL - AND t1.`order_id` IS NOT NULL + AND t2.`id` IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql index 17a05ff8a056..144625529daa 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.tenant AS r0, t1.order_no AS r1 + SELECT DISTINCT t0.sku AS k0, t2.tenant AS r0, t2.order_no AS r1 FROM shop.products t0 JOIN shop.order_lines t1 ON t1.sku = t0.sku + JOIN shop.orders t2 ON t2.tenant = t1.tenant AND t2.order_no = t1.order_no WHERE t0.sku IS NOT NULL - AND t1.tenant IS NOT NULL - AND t1.order_no IS NOT NULL + AND t2.tenant IS NOT NULL + AND t2.order_no IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..a41f5e5db0be --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.customer_id AS r0 + FROM shop.orders t0 + JOIN shop.order_details t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.customer_id IS NOT NULL + AND t1.region = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..76152b181633 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t2.id AS r0 + FROM shop.customers t0 + JOIN shop.order_details t1 ON t1.customer_id = t0.id + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.id IS NOT NULL + AND t2.id IS NOT NULL + AND t1.region = 'eu' + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql index 0468e7f6288d..bcfdb0e8b82c 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 FROM shop.products t0 JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku IS NOT NULL - AND t1.order_id IS NOT NULL + AND t2.id IS NOT NULL + AND t2.channel = 'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql index 59af4ab12b0a..4ec96ff96e16 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0.id IS NOT NULL AND t0.kind = 'organization' AND t1.id IS NOT NULL + AND t1.kind = 'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql index 0468e7f6288d..05a4b13d3306 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.sku AS k0, t1.order_id AS r0 + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 FROM shop.products t0 JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku IS NOT NULL - AND t1.order_id IS NOT NULL + AND t2.id IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql index 1d2ccc11c98b..288ff2be41cb 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql @@ -1,9 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.[sku] AS k0, t1.[tenant] AS r0, t1.[order_no] AS r1 + SELECT DISTINCT t0.[sku] AS k0, t2.[tenant] AS r0, t2.[order_no] AS r1 FROM [shop].[products] t0 JOIN [shop].[order_lines] t1 ON t1.[sku] = t0.[sku] + JOIN [shop].[orders] t2 ON t2.[tenant] = t1.[tenant] AND t2.[order_no] = t1.[order_no] WHERE t0.[sku] IS NOT NULL - AND t1.[tenant] IS NOT NULL - AND t1.[order_no] IS NOT NULL + AND t2.[tenant] IS NOT NULL + AND t2.[order_no] IS NOT NULL ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..fa921333170c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[customer_id] AS r0 + FROM [shop].[orders] t0 + JOIN [shop].[order_details] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t0.[channel] = N'web' + AND t1.[customer_id] IS NOT NULL + AND t1.[region] = N'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..fa9e69cec1b2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t2.[id] AS r0 + FROM [shop].[customers] t0 + JOIN [shop].[order_details] t1 ON t1.[customer_id] = t0.[id] + JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] + WHERE t0.[id] IS NOT NULL + AND t2.[id] IS NOT NULL + AND t1.[region] = N'eu' + AND t2.[channel] = N'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql index bf71f76ea7ed..3400531214c5 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql @@ -1,8 +1,10 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.[sku] AS k0, t1.[order_id] AS r0 + SELECT DISTINCT t0.[sku] AS k0, t2.[id] AS r0 FROM [shop].[products] t0 JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] + JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] WHERE t0.[sku] IS NOT NULL - AND t1.[order_id] IS NOT NULL + AND t2.[id] IS NOT NULL + AND t2.[channel] = N'web' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql index e4e9639710f4..55386e061958 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql @@ -6,4 +6,5 @@ FROM ( WHERE t0.[id] IS NOT NULL AND t0.[kind] = N'organization' AND t1.[id] IS NOT NULL + AND t1.[kind] = N'person' ) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql index bf71f76ea7ed..c8a2364eb54a 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql @@ -1,8 +1,9 @@ SELECT COUNT(*) AS links FROM ( - SELECT DISTINCT t0.[sku] AS k0, t1.[order_id] AS r0 + SELECT DISTINCT t0.[sku] AS k0, t2.[id] AS r0 FROM [shop].[products] t0 JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] + JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] WHERE t0.[sku] IS NOT NULL - AND t1.[order_id] IS NOT NULL + AND t2.[id] IS NOT NULL ) k diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json index d4c87d95abb3..43f2a08e16fb 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json @@ -2,7 +2,7 @@ "$id": "https://open-metadata.org/schema/api/data/ontologyAggregateStatementRequest.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "OntologyAggregateStatementRequest", - "description": "Asks for a counting statement. Without a relation it counts the records of the class. With a relation and a direction it returns, by default, the 8 records of the class that relate to the most records along that relation, each with its count. With the measure `linkCount` it returns one number, the distinct pairs of a record of the class and a related key along the confirmed join.", + "description": "Asks for a counting statement. Without a relation it counts the records of the class. With a relation and a direction it returns, by default, the 8 records of the class that relate to the most records along that relation, each with its count. With the measure `linkCount` it returns one number, the links of the relation. A link is a pair of a record of the class that binds the relation and an object key with no null part. Forward from the binding class the count is every link. Inverse from the other class it is the links whose object is a record of the class asked, and the row filter of the object class applies only when the count starts from it.", "type": "object", "javaType": "org.openmetadata.schema.api.data.OntologyAggregateStatementRequest", "properties": { diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json index 77429cd2b399..b85202801416 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json @@ -25,7 +25,7 @@ "items": { "description": "A string, a number or a boolean." } }, "measure": { - "description": "What an aggregate over a relation counts. `topRecords` returns the 8 records of the class that relate to the most records along the relation, each with its count. `linkCount` returns one number: the distinct pairs of a record of the class and a related key along the confirmed join. A related key counts when no part of it is null, whether or not a record holds it, as a stored profile counts a reference. A request that names none asks for `topRecords`.", + "description": "What an aggregate over a relation counts. `topRecords` returns the 8 records of the class that relate to the most records along the relation, each with its count. `linkCount` returns one number, the links of the relation. A link is a pair of a record of the class that binds the relation and an object key with no null part. Forward from the binding class the count is every link. Inverse from the other class it is the links whose object is a record of the start class, and the object need not be a record when the count starts from the binding class. A request that names none asks for `topRecords`.", "type": "string", "javaType": "org.openmetadata.schema.api.data.OntologyStatementMeasure", "enum": ["topRecords", "linkCount"] From ac816de69c1c83e74c803006aef38659ea1633e9 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 07:35:14 -0800 Subject: [PATCH 065/203] Give no exact count from a table profiled through a dataframe or from catalog statistics --- .../service/ontology/OntologyCountRules.java | 101 ++++++++++++++++-- .../ontology/OntologyCountRulesTest.java | 48 +++++++++ 2 files changed, 141 insertions(+), 8 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java index 84b46562c575..94cdea987b20 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java @@ -122,11 +122,11 @@ final class OntologyCountRules { * * No other dialect function of {@code CountFn} exists, and no other metric function in {@code * profiler/metrics/static} or {@code profiler/orm/functions} transforms a value before it is - * counted. {@code valuesCount} is {@code count(CountFn(col))} and {@code nullCount} is a sum of - * {@code col IS NULL}: a cast or a length of a null is null and of a value is never null, so - * neither changes with a transform, and a link count, which reads only those two and tests - * {@code distinctCount == valuesCount} (a count too low can only fail that test), is not - * affected. + * counted. On the SQL path {@code valuesCount} is {@code count(CountFn(col))} and {@code + * nullCount} is a sum of {@code col IS NULL}: a cast or a length of a null is null and of a value + * is never null, so neither changes with a transform, and a link count, which reads only those + * two and tests {@code distinctCount == valuesCount} (a count too low can only fail that test), + * is not affected there. The dataframe path is different ({@link #PROFILED_FROM_DATAFRAMES}). */ private static final Map> TRANSFORMED_BEFORE_DISTINCT_COUNT = Map.of( @@ -136,10 +136,81 @@ final class OntologyCountRules { "MicrosoftFabric", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), "Oracle", ORACLE_LENGTH_COUNTED); + /** + * The service types whose tables are profiled through a dataframe, so that a column's metrics + * are not counted over the rows as stored. The profiler interface of each reads the table in + * chunks and casts every chunk to the column types of the catalog before any metric + * ({@code PandasProfilerInterface._type_casted_dataset}, {@code + * ingestion/src/metadata/profiler/interface/pandas/profiler_interface.py:121-141}, with the + * mapping in {@code utils/datalake/datalake_utils.py:337-350}). A null in a string column becomes + * the text {@code 'None'} or {@code 'nan'}, in a bytes column {@code b'None'}, and in a boolean + * column {@code True}, so {@code nullCount} falls to 0 and {@code valuesCount} and {@code + * distinctCount} count the nulls. The service types, with the profiler that each names: + * + *

      + *
    • {@code Datalake}: {@code profiler_class=PandasProfilerInterface}, {@code + * ingestion/source/database/datalake/service_spec.py:14}; the class is declared at {@code + * profiler/interface/pandas/profiler_interface.py:61}; + *
    • {@code BurstIQ}: {@code profiler_class=BurstIQProfilerInterface}, {@code + * ingestion/source/database/burstiq/service_spec.py:16}; the class extends {@code + * PandasProfilerInterface} at {@code + * profiler/interface/pandas/burstiq/profiler_interface.py:49}. + *
    + * + * No other service type names a profiler that extends {@code PandasProfilerInterface}. The NoSQL + * service types (Cassandra, DynamoDB, MongoDB) compute no distinct, values or null count at all, + * so they store no column profile to read. + */ + private static final Set PROFILED_FROM_DATAFRAMES = Set.of("Datalake", "BurstIQ"); + + /** + * The service types whose profiler can take a column's {@code distinctCount} and {@code + * nullCount} from the engine's catalog statistics instead of counting them. The stored profile + * does not say which path made it, a pipeline's {@code useStatistics} can change after a run, + * and a run can come from outside a pipeline, so no table of these service types gives an exact + * count. Every profiler that reads catalog statistics extends {@code ProfilerWithStatistics} + * ({@code profiler/interface/sqlalchemy/stored_statistics_profiler.py:49}), which replaces the + * counts when {@code useStatistics} is set (lines 69 and 104), and implements the {@code + * StoredStatisticsSource} of its engine (line 37). Two do: + * + *
      + *
    • {@code Trino}: {@code profiler_class=TrinoProfilerInterface}, {@code + * ingestion/source/database/trino/service_spec.py:18}, declared at {@code + * profiler/interface/sqlalchemy/trino/profiler_interface.py:37}. {@code distinctCount} is + * {@code SHOW STATS} {@code distinct_values_count} ({@code + * ingestion/source/database/trino/profiler/system_tables_profiler.py:80}) and {@code + * nullCount} is {@code int(row_count * nulls_fraction)} (lines 166-168); + *
    • {@code StarRocks}: {@code profiler_class=StarRocksProfilerInterface}, {@code + * ingestion/source/database/starrocks/service_spec.py:28}, declared at {@code + * profiler/interface/sqlalchemy/starrocks/profiler_interface.py:33}. {@code distinctCount} + * is {@code HLL_CARDINALITY(ndv)}, a HyperLogLog estimate ({@code + * ingestion/source/database/starrocks/profiler/system_tables_profiler.py:82}). + *
    + * + * No other profiler or sampler computes a distinct, values or null count other than over the rows + * it read: the approximate functions of the dialects are percentiles ({@code + * profiler/orm/functions/median.py}), and a sampled or windowed read is recorded by the profile's + * sample, the table's partition and the profiler configuration, which the rule already reads. + */ + private static final Set PROFILED_FROM_STATISTICS = Set.of("Trino", "StarRocks"); + private static final double WHOLE_PERCENTAGE = 100d; private OntologyCountRules() {} + /** + * False for a table whose service type profiles through a dataframe or from catalog statistics: + * none of the counts of its profiles is exact. + */ + private static boolean countsOverTheRows(final Table table) { + if (table.getServiceType() == null) { + return true; + } + final String serviceType = table.getServiceType().value(); + return !PROFILED_FROM_DATAFRAMES.contains(serviceType) + && !PROFILED_FROM_STATISTICS.contains(serviceType); + } + private static Set union( final Set first, final Set second) { final Set all = EnumSet.copyOf(first); @@ -240,7 +311,11 @@ static NativeOntologyCount links( case Lookup.Unconfirmed ignored -> subject.truncated() ? notDerivable() : state(State.JOIN_NOT_CONFIRMED); - case Lookup.Confirmed found -> linkCount(probe.source(), probe.target(), found.stored()); + case Lookup.Confirmed found -> linkCount( + probe.source(), + probe.target(), + found.stored(), + facts.tables().get(probe.target().assetId())); }; } @@ -339,7 +414,10 @@ private static NativeOntologyCount valueOfAtMostOneNullable( } private static NativeOntologyCount linkCount( - final Source source, final BindingRow target, final OntologyRelationPath.StoredJoin stored) { + final Source source, + final BindingRow target, + final OntologyRelationPath.StoredJoin stored, + final Table targetTable) { final List> key = source.row().subjectKey(); final List on = listOrEmpty(stored.join().getOn()); final boolean joined = @@ -350,6 +428,7 @@ private static NativeOntologyCount linkCount( .toList() .equals(target.subjectKey()); if (!joined + || !countsOverTheRows(targetTable) || source.row().rowFilter() != null || target.rowFilter() != null || nullOrEmpty(key) @@ -443,8 +522,14 @@ static Source refused(final NativeOntologyCount refusal) { return new Source(null, null, null, null, refusal); } - /** The metrics of the column at {@code path}, or null when they did not cover the table. */ + /** + * The metrics of the column at {@code path}, or null when they did not cover the table or the + * table's service type gives no exact count. + */ Metrics metrics(final List path) { + if (!countsOverTheRows(table)) { + return null; + } final Column column = OntologyBindingRules.resolveColumn(table, path); final ColumnProfile stored = column == null || column.getFullyQualifiedName() == null diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java index 6da3fc9e2ec1..4e155c603210 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java @@ -609,6 +609,49 @@ void aTransformedColumnOfAKeyOfSeveralColumnsStillCountsItsValues() { assertExact(100, world.records(ORDER)); } + // Dataframe profilers (Datalake, BurstIQ) cast every chunk before counting, and statistics + // profilers (Trino, StarRocks) can estimate, so a table of these service types gives no exact + // count. + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) + void aOneColumnKeyOnAServiceTypeThatGivesNoExactCountHasNoRecords(final String engine) { + final var world = new World().engine(engine); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) + void aKeyOfSeveralColumnsOnAServiceTypeThatGivesNoExactCountHasNoRecords(final String engine) { + final var world = World.twoColumnKey(engine); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) + void aRelationWhoseChildColumnIsOnAServiceTypeThatGivesNoExactCountHasNoLinks( + final String engine) { + final var world = new World().engine(engine); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) + void aRelationOntoAKeyOnAServiceTypeThatGivesNoExactCountHasNoLinks(final String engine) { + final var world = new World().targetEngine(engine); + assertExact(100, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @ParameterizedTest + @ValueSource( + strings = {"Postgres", "Mysql", "Snowflake", "BigQuery", "Redshift", "Databricks", "Hive"}) + void aServiceTypeThatCountsOverTheRowsGivesRecordsAndLinks(final String engine) { + final var world = new World().engine(engine).targetEngine(engine); + assertExact(100, world.records(ORDER)); + assertExact(100, world.links()); + } + private static OntologyRowFilter filter() { return new OntologyRowFilter() .withColumn(List.of("status")) @@ -707,6 +750,11 @@ World engine(final String engine) { return this; } + World targetEngine(final String engine) { + customers.withServiceType(DatabaseServiceType.fromValue(engine)); + return this; + } + void metrics( final String column, final double values, final double nulls, final double distinct) { columnProfiles.put( From c2158aaeef4ee31b015f44b1960ae96ed55a2342 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 07:41:59 -0800 Subject: [PATCH 066/203] Regenerate the UI's TypeScript types for the link count measure --- .../data/ontologyAggregateStatementRequest.ts | 31 +++++++++++++++++-- .../api/data/ontologyStatementPlan.ts | 28 +++++++++++++++-- 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts index 9667635434f2..74f6d03c327c 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts @@ -12,11 +12,21 @@ */ /** * Asks for a counting statement. Without a relation it counts the records of the class. - * With a relation and a direction it returns the 8 records of the class that relate to the - * most records along that relation, each with its count. + * With a relation and a direction it returns, by default, the 8 records of the class that + * relate to the most records along that relation, each with its count. With the measure + * `linkCount` it returns one number, the links of the relation. A link is a pair of a + * record of the class that binds the relation and an object key with no null part. Forward + * from the binding class the count is every link. Inverse from the other class it is the + * links whose object is a record of the class asked, and the row filter of the object class + * applies only when the count starts from it. */ export interface OntologyAggregateStatementRequest { direction?: Direction; + /** + * What to count along the relation. Only a request that names a relation and a direction + * takes one, and a request that names none counts `topRecords`. + */ + measure?: Measure; /** * Id of the class at the far end of the relation. Leave it out when the relation names one * class on that side, its range for `forward` and its domain for `inverse`. @@ -39,6 +49,23 @@ export enum Direction { Inverse = "inverse", } +/** + * What to count along the relation. Only a request that names a relation and a direction + * takes one, and a request that names none counts `topRecords`. + * + * What an aggregate over a relation counts. `topRecords` returns the 8 records of the class + * that relate to the most records along the relation, each with its count. `linkCount` + * returns one number, the links of the relation. A link is a pair of a record of the class + * that binds the relation and an object key with no null part. Forward from the binding + * class the count is every link. Inverse from the other class it is the links whose object + * is a record of the start class, and the object need not be a record when the count starts + * from the binding class. A request that names none asks for `topRecords`. + */ +export enum Measure { + LinkCount = "linkCount", + TopRecords = "topRecords", +} + /** * Which version of the ontology a statement reads. `release` is the active release. `draft` * is the working draft, and reading it takes `EditAll` on the ontology. The class, its diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts index acf83468dd49..5274b0449cfd 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts @@ -38,12 +38,17 @@ export interface OntologyStatementPlan { * Whether the statement asks for one row more than `rowCap`. That row is not part of the * answer. It says only that more rows exist. */ - extraRow: boolean; - family: EngineFamily; + extraRow: boolean; + family: EngineFamily; + /** + * What an aggregate over a relation counts. Absent on every other statement, including the + * count of a class. + */ + measure?: Measure; relation?: Relation; /** * The most rows a reader takes from the result. `find` and `expand` take 25, `open` takes - * 100, a relation count takes 8 and a class count takes 1. + * 100, a relation count takes 8, and a class count and a link count take 1. */ rowCap: number; /** @@ -152,6 +157,23 @@ export enum EngineFamily { Tsql = "tsql", } +/** + * What an aggregate over a relation counts. Absent on every other statement, including the + * count of a class. + * + * What an aggregate over a relation counts. `topRecords` returns the 8 records of the class + * that relate to the most records along the relation, each with its count. `linkCount` + * returns one number, the links of the relation. A link is a pair of a record of the class + * that binds the relation and an object key with no null part. Forward from the binding + * class the count is every link. Inverse from the other class it is the links whose object + * is a record of the start class, and the object need not be a record when the count starts + * from the binding class. A request that names none asks for `topRecords`. + */ +export enum Measure { + LinkCount = "linkCount", + TopRecords = "topRecords", +} + /** * The relation a statement follows. */ From 102e1909df80139ef9f0277552035ca938401198 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 07:47:54 -0800 Subject: [PATCH 067/203] Test that a deleted contributing table holds no join, inside and beyond the first read of a class --- .../NativeOntologyDataGraphCountBoundIT.java | 72 +++++++++++++++++++ .../ontology/OntologyCountRulesTest.java | 7 -- 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java index d302717976ee..3561a9a57ba1 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java @@ -88,6 +88,9 @@ class NativeOntologyDataGraphCountBoundIT extends BaseOntologyApprovalIT { private static final String HOLDER_STATEMENT = "bindingrole in ("; + /** The identity row and four others fill the five rows of the first read. */ + private static final int CLASS_CUT_BEFORE_THE_HOLDER = 5; + @Test void aHubOfTableRowsKeepsItsRecordsAndEveryRelationOntoItKeepsItsLinks(final TestNamespace ns) { final Star star = star(ns, "hub", OntologyJoinStatus.CONFIRMED, 0); @@ -197,6 +200,75 @@ void aClassAtTheContributingTableLimitStillStatesItsJoin(final TestNamespace ns) assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); } + @Test + void aDeletedContributingTableHoldsNoJoinWhenTheClassIsCutBeforeIt(final TestNamespace ns) { + assertADeletedHolderHoldsNoJoin(ns, "deletedcut", CLASS_CUT_BEFORE_THE_HOLDER); + } + + @Test + void aDeletedContributingTableHoldsNoJoinWhenItIsAmongTheFirstRows(final TestNamespace ns) { + assertADeletedHolderHoldsNoJoin(ns, "deletedfirst", 0); + } + + /** + * A real contributing table holds the only confirmed join of the relation, and the identity + * table holds an inferred one. While the table exists no count is stated, because the join sits + * on a contributing table. Soft-deleted or hard-deleted, the table holds no join, and the state + * is the inferred join of the identity table, as the statements of the mapping find it. Binding + * rows that sort before the table are inserted after its binding is put, because a put rewrites + * the rows of the class, so that with enough of them the table lies beyond the first read. + */ + private static void assertADeletedHolderHoldsNoJoin( + final TestNamespace ns, final String name, final int rowsBeforeTheHolder) { + final Pair pair = pair(ns, name, OntologyJoinStatus.INFERRED); + final Table holder = holderTable(ns, pair, name + "holder"); + put( + admin(), + pair.spoke(), + binding(holder, OntologyBindingRole.CONTRIBUTING, "id") + .withColumns( + List.of( + column(pair.relation(), "hub_id") + .withJoin( + join(pair.hubTable(), OntologyJoinStatus.CONFIRMED, "hub_id", "id")))), + 1L); + insertFakeRows(pair.spoke(), rowsBeforeTheHolder, 0); + assertEquals(2 + rowsBeforeTheHolder, bindingRows(pair.spoke()), "The class's rows"); + + assertEquals(state(State.NOT_DERIVABLE), links(pair)); + admin().tables().delete(holder.getId().toString(), Map.of("hardDelete", "false")); + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + admin().tables().restore(holder.getId()); + assertEquals(state(State.NOT_DERIVABLE), links(pair)); + admin() + .tables() + .delete(holder.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + } + + private static Table holderTable(final TestNamespace ns, final Pair pair, final String name) { + final Table holder = + table( + pair.schema(), + ns.prefix(name), + column("id", ColumnDataType.BIGINT), + column("hub_id", ColumnDataType.BIGINT)); + profile(holder, columnProfile("id", 40, 0, 40), columnProfile("hub_id", 31, 0, 4)); + return holder; + } + + private static long bindingRows(final OntologyConcept concept) { + return Entity.getJdbi() + .withHandle( + handle -> + handle + .createQuery( + "SELECT COUNT(*) FROM ontology_concept_binding WHERE conceptId = :id") + .bind("id", concept.getId().toString()) + .mapTo(Long.class) + .one()); + } + private static long holderStatements( final NativeOntologyGraphScanProbe.ScanObservation observed) { return observed.bindingSql().stream().filter(sql -> sql.contains(HOLDER_STATEMENT)).count(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java index 4e155c603210..38463537f990 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java @@ -620,13 +620,6 @@ void aOneColumnKeyOnAServiceTypeThatGivesNoExactCountHasNoRecords(final String e assertState(State.NOT_DERIVABLE, world.records(ORDER)); } - @ParameterizedTest - @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) - void aKeyOfSeveralColumnsOnAServiceTypeThatGivesNoExactCountHasNoRecords(final String engine) { - final var world = World.twoColumnKey(engine); - assertState(State.NOT_DERIVABLE, world.records(ORDER)); - } - @ParameterizedTest @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) void aRelationWhoseChildColumnIsOnAServiceTypeThatGivesNoExactCountHasNoLinks( From 76eedd1ebeebdb25e14aed2d35019da5d6fed939 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 07:52:27 -0800 Subject: [PATCH 068/203] Keep the name of a masked field's change in a stored event and drop only its values --- .../service/events/ChangeEventMasking.java | 37 ++++--- ...rtsRuleEvaluatorMaskedFieldChangeTest.java | 98 +++++++++++++++++++ .../events/ChangeEventMaskingTest.java | 37 +++++-- 3 files changed, 144 insertions(+), 28 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/alerting/matching/AlertsRuleEvaluatorMaskedFieldChangeTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java index cf24cb3a7c11..b720b637430f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.io.UncheckedIOException; -import java.util.Iterator; import java.util.List; import java.util.Optional; import org.openmetadata.schema.utils.JsonUtils; @@ -32,7 +31,7 @@ * What a change event is stored as. The entity it carries leaves out every field its schema marks * {@code "mask": true}, such as bot tokens, password hashes and connection secrets, whichever code * made the event and whether it holds the entity as an object or as a string of JSON. Its recorded - * field changes leave out the changes of a field that is masked as a whole. Every alert, + * field changes of a field that is masked as a whole keep the name and leave out the values. Every alert, * the audit log and {@code GET /v1/events} read the stored event. */ public final class ChangeEventMasking { @@ -59,8 +58,8 @@ public static String masked(final String changeEventJson) { private static String withMaskedEvent(final String changeEventJson, final Class entityClass) { final ObjectNode event = (ObjectNode) JsonUtils.readTree(changeEventJson); final boolean isEntityMasked = maskEntity(event, entityClass); - final boolean isChangeDropped = dropMaskedFieldChanges(event, entityClass); - return isEntityMasked || isChangeDropped ? JsonUtils.pojoToJson(event) : changeEventJson; + final boolean isChangeStripped = stripMaskedFieldValues(event, entityClass); + return isEntityMasked || isChangeStripped ? JsonUtils.pojoToJson(event) : changeEventJson; } private static boolean maskEntity(final ObjectNode event, final Class entityClass) { @@ -72,7 +71,7 @@ private static boolean maskEntity(final ObjectNode event, final Class entityC ? JsonUtils.readValueLenient(entity.asText(), entityClass) : JsonUtils.convertValueLenient(entity, entityClass); final ObjectNode masked = (ObjectNode) JsonUtils.readTree(JsonUtils.pojoToMaskedJson(typed)); - dropMaskedFieldChanges(masked, entityClass); + stripMaskedFieldValues(masked, entityClass); event.put(ENTITY, masked.toString()); } return isPresent; @@ -80,33 +79,33 @@ private static boolean maskEntity(final ObjectNode event, final Class entityC /** * A recorded field change holds the old and the new value of a field, so a change of a field - * that is masked as a whole is left out of the event and of the entity it carries. Nothing in the - * stored event then holds the field's values, and the entity's own endpoints still decide who - * reads them. + * that is masked as a whole keeps its name and loses both values, in the event and in the entity + * it carries. The stored event still records that the field changed, so an alert or a workflow + * trigger that filters on a field name keeps matching, and nothing in it holds the values. */ - private static boolean dropMaskedFieldChanges( + private static boolean stripMaskedFieldValues( final ObjectNode holder, final Class entityClass) { final List masked = MaskedFields.wholeFieldsOf(entityClass); - boolean isDropped = false; + boolean isStripped = false; for (final String description : CHANGE_DESCRIPTIONS) { for (final String kind : FIELD_CHANGE_LISTS) { if (!masked.isEmpty() && holder.path(description).path(kind) instanceof ArrayNode changes) { - isDropped |= removeChangesOf(changes, masked); + isStripped |= removeValuesOf(changes, masked); } } } - return isDropped; + return isStripped; } - private static boolean removeChangesOf(final ArrayNode changes, final List masked) { - final int before = changes.size(); - final Iterator each = changes.elements(); - while (each.hasNext()) { - if (isChangeOf(masked, each.next().path("name").asText())) { - each.remove(); + private static boolean removeValuesOf(final ArrayNode changes, final List masked) { + boolean isStripped = false; + for (final JsonNode change : changes) { + if (change instanceof ObjectNode fieldChange + && isChangeOf(masked, fieldChange.path("name").asText())) { + isStripped |= fieldChange.remove(List.of("oldValue", "newValue")).size() > 0; } } - return changes.size() != before; + return isStripped; } // A change names a field or a path inside it, such as "authenticationMechanism.config". diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/alerting/matching/AlertsRuleEvaluatorMaskedFieldChangeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/alerting/matching/AlertsRuleEvaluatorMaskedFieldChangeTest.java new file mode 100644 index 000000000000..c711ed876c02 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/alerting/matching/AlertsRuleEvaluatorMaskedFieldChangeTest.java @@ -0,0 +1,98 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.alerting.matching; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.auth.JWTAuthMechanism; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.teams.AuthenticationMechanism; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.ChangeDescription; +import org.openmetadata.schema.type.ChangeEvent; +import org.openmetadata.schema.type.EventType; +import org.openmetadata.schema.type.FieldChange; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.events.ChangeEventMasking; + +/** An alert reads the stored event, so a masked field must still match by name once stored. */ +class AlertsRuleEvaluatorMaskedFieldChangeTest { + + @BeforeAll + static void knowTheEntityTypes() { + EntityInterface.ENTITY_TYPE_TO_CLASS_MAP.putIfAbsent(Entity.USER, User.class); + EntityInterface.ENTITY_TYPE_TO_CLASS_MAP.putIfAbsent( + Entity.ONTOLOGY_CHANGE_SET.toLowerCase(Locale.ROOT), OntologyChangeSet.class); + } + + @Test + void aStoredDraftUpdateMatchesAnAlertOnItsOperations() { + final ChangeEvent stored = + stored( + new ChangeEvent() + .withEntityType(Entity.ONTOLOGY_CHANGE_SET) + .withEntity(new OntologyChangeSet().withId(UUID.randomUUID()).withName("draft")), + "operations"); + + assertTrue(new AlertsRuleEvaluator(stored).matchAnyFieldChange(List.of("operations"))); + assertFalse(new AlertsRuleEvaluator(stored).matchAnyFieldChange(List.of("description"))); + } + + @Test + void aStoredUserUpdateMatchesAnAlertOnItsAuthenticationMechanism() { + final User bot = + new User() + .withId(UUID.randomUUID()) + .withName("ingestion-bot") + .withEmail("ingestion-bot@open-metadata.org") + .withAuthenticationMechanism( + new AuthenticationMechanism() + .withAuthType(AuthenticationMechanism.AuthType.JWT) + .withConfig(new JWTAuthMechanism().withJWTToken("eyJ.secret.token"))); + final ChangeEvent stored = + stored( + new ChangeEvent().withEntityType(Entity.USER).withEntity(bot), + "authenticationMechanism"); + + assertTrue( + new AlertsRuleEvaluator(stored).matchAnyFieldChange(List.of("authenticationMechanism"))); + } + + private static ChangeEvent stored(final ChangeEvent event, final String field) { + final ChangeEvent recorded = + event + .withId(UUID.randomUUID()) + .withEventType(EventType.ENTITY_UPDATED) + .withTimestamp(System.currentTimeMillis()) + .withChangeDescription( + new ChangeDescription() + .withFieldsUpdated( + List.of( + new FieldChange() + .withName(field) + .withOldValue("old-secret") + .withNewValue("new-secret")))); + final String json = ChangeEventMasking.masked(JsonUtils.pojoToJson(recorded)); + assertFalse(json.contains("secret")); + return JsonUtils.readValue(json, ChangeEvent.class); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java index fbd5699b3142..d2bd968c2a0f 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java @@ -135,7 +135,7 @@ void anEventOfATypeWithNoMaskedFieldIsStoredAsItCame() { } @Test - void aChangeOfAMaskedFieldLeavesTheRecordedChanges() { + void aChangeOfAMaskedFieldKeepsItsNameAndLosesItsValues() { final ChangeDescription changes = new ChangeDescription() .withFieldsAdded(List.of(change("authenticationMechanism", null, "added-secret"))) @@ -151,11 +151,20 @@ void aChangeOfAMaskedFieldLeavesTheRecordedChanges() { JsonUtils.pojoToJson(userEvent(bot()).withChangeDescription(changes))); final JsonNode kept = JsonUtils.readTree(stored).path("changeDescription"); - assertEquals(0, kept.path("fieldsAdded").size()); - assertEquals(0, kept.path("fieldsDeleted").size()); - assertEquals(1, kept.path("fieldsUpdated").size()); - assertEquals("displayName", kept.path("fieldsUpdated").get(0).path("name").asText()); - assertEquals("New", kept.path("fieldsUpdated").get(0).path("newValue").asText()); + assertEquals( + List.of("authenticationMechanism"), kept.path("fieldsAdded").findValuesAsText("name")); + assertEquals( + List.of("authenticationMechanism"), kept.path("fieldsDeleted").findValuesAsText("name")); + assertEquals( + List.of("authenticationMechanism", "authenticationMechanism.config", "displayName"), + kept.path("fieldsUpdated").findValuesAsText("name")); + for (final String kind : List.of("fieldsAdded", "fieldsUpdated", "fieldsDeleted")) { + for (final JsonNode entry : kept.path(kind)) { + final boolean isMasked = entry.path("name").asText().startsWith("authenticationMechanism"); + assertEquals(!isMasked, entry.has("newValue") || entry.has("oldValue")); + } + } + assertEquals("New", kept.path("fieldsUpdated").get(2).path("newValue").asText()); assertFalse(stored.contains("secret")); } @@ -202,7 +211,8 @@ void aDraftsOperationsLeaveItsEntityAndItsRecordedChanges() { .withName("draft") .withUndoCursor(1) .withOperations(List.of(operation)) - .withChangeDescription(changes)); + .withChangeDescription(changes) + .withIncrementalChangeDescription(changes)); final String stored = ChangeEventMasking.masked(JsonUtils.pojoToJson(event)); @@ -210,13 +220,22 @@ void aDraftsOperationsLeaveItsEntityAndItsRecordedChanges() { final JsonNode entity = storedEntity(stored); assertFalse(entity.has("operations")); assertEquals( - List.of("undoCursor"), + List.of("operations", "undoCursor"), entity.path("changeDescription").path("fieldsUpdated").findValuesAsText("name")); + assertFalse(entity.path("changeDescription").path("fieldsUpdated").get(0).has("newValue")); + assertFalse(entity.path("changeDescription").path("fieldsUpdated").get(0).has("oldValue")); + final JsonNode incremental = entity.path("incrementalChangeDescription").path("fieldsUpdated"); + assertEquals(List.of("operations", "undoCursor"), incremental.findValuesAsText("name")); + assertFalse(incremental.get(0).has("newValue")); + assertFalse(incremental.get(0).has("oldValue")); assertEquals("draft", entity.path("name").asText()); assertEquals(1, entity.path("undoCursor").asInt()); final JsonNode updated = JsonUtils.readTree(stored).path("changeDescription").path("fieldsUpdated"); - assertEquals(List.of("undoCursor"), updated.findValuesAsText("name")); + assertEquals(List.of("operations", "undoCursor"), updated.findValuesAsText("name")); + assertFalse(updated.get(0).has("newValue")); + assertFalse(updated.get(0).has("oldValue")); + assertEquals("1", updated.get(1).path("newValue").asText()); } private static FieldChange change( From 2965a21a54c4227d8f429191ae4e7f50f7c0afad Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 08:04:22 -0800 Subject: [PATCH 069/203] Record the dataframe and statistics rules, the second read of a filtered class and the contributing table limit --- .../2026-11-22-a-count-is-exact-or-absent.md | 51 ++++++++++++++----- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md index f97d7e0182e9..1cd66965e745 100644 --- a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md +++ b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md @@ -1,7 +1,7 @@ # A record or link count comes from the stored profiles when they are exact, and is absent when they are not - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (a class cut by the first read is read again, a deleted table holds no join, a distinct count taken after a transform is not exact) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (a class cut by the first read is read again, a deleted table holds no join, a distinct count taken after a transform is not exact); v3 2026-11-23 (a table profiled through a dataframe or from catalog statistics gives no exact count, and the second-read and limit paragraphs say what they do) - **Deciders:** Ontology Studio maintainers - **Guard:** `OntologyCountRulesTest`, `NativeOntologyDataGraphCountIT`, `NativeOntologyDataGraphCountBoundIT` - **Related:** ADR:2026-11-21-graph-table-assets-carry-latest-profile-facts (the profile facts this record does not reuse), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, subject key and joins that a count reads), ADR:2026-11-22-record-statements-start-from-the-identity-table (the identity table and the join that a count follows) @@ -75,10 +75,30 @@ cast to `varbinary` with no length, which keeps 30 bytes, so two values that sha count once. On Oracle a `BYTES`, `BYTEA`, `BINARY`, `VARBINARY` or `BLOB` column is counted as `DBMS_LOB.GETLENGTH(column)`, so the count is the number of distinct lengths. The records of a key of one column of such a type on such an engine are `notDerivable`. The list is in -`OntologyCountRules`, with the profiler functions it comes from. `valuesCount` and `nullCount` are -not changed by any transform, because a cast or a length of a null is null and of a value is never -null, so a link count, which reads those two and asks `distinctCount` to equal `valuesCount`, and a -count of a key of several columns, which reads `valuesCount`, are as exact as before. +`OntologyCountRules`, with the profiler functions it comes from. On the SQL path only, +`valuesCount` and `nullCount` are not changed by any transform, because a cast or a length of a +null is null and of a value is never null, so a link count, which reads those two and asks +`distinctCount` to equal `valuesCount`, and a count of a key of several columns, which reads +`valuesCount`, are as exact as before on that path. + +**A table profiled through a dataframe gives no exact count.** Datalake and BurstIQ tables are read +in chunks, and the profiler casts every chunk to the column types of the catalog before it counts. +A null in a string column becomes the text `'None'` or `'nan'`, in a bytes column `b'None'` and in +a boolean column `True`, so `nullCount` falls to 0 and `valuesCount` and `distinctCount` count the +nulls. Every records or links count that reads a profile of a table of these service types, which +is a key on the identity table, a child column of a join, or the key of the related class's table, +is `notDerivable`. The service types are the ones whose profiler is +`PandasProfilerInterface` or a subclass of it, and the list is in `OntologyCountRules` with the +profiler code it comes from. + +**A table whose profiler can take counts from catalog statistics gives no exact count.** Trino and +StarRocks tables are profiled by a profiler that, when the pipeline sets `useStatistics`, takes +`distinctCount` and `nullCount` from the engine's statistics: `SHOW STATS`, a rounded null +fraction, and a HyperLogLog estimate. The stored profile does not say which path made it, a +pipeline's setting can change after a run, and a run can come from outside a pipeline, so no table +of these service types gives an exact count, whatever the setting. The rule is the one above, with +its own list in `OntologyCountRules`. A stored marker of where a count came from would let these +tables give exact counts again. **Links of a relation** need the join that `OntologyRelationPath.lookup` finds for the relation onto the identity table of the related class, confirmed and held by the identity binding of the @@ -100,14 +120,19 @@ profiles of their key columns and join columns. A page of 60 classes and 500 edg reads and no query for a class or an edge. A class whose first read reached five rows may bind more tables, and a table not read could hold -the join of a relation. When a relation's first class is cut that way, its identity table gives a -count and the rows read hold no confirmed join for the relation, the class is read again as the -statements of the mapping read it: its identity row and its contributing rows, at most 33, in one -statement for each group of 14 such classes, so that no scan maps more than 500 rows. A page where -no class is cut runs no such statement. A page of 60 classes of which every one is cut runs five. -A class over the 32 contributing tables that a statement accepts has no state for its join and its -links are `notDerivable`. Because of this read, the state of `links` never depends on how many -tables the first class binds. Nothing is stored and nothing is cached. The counts are +the join of a relation. When a relation's first class is cut that way, its identity table is +visible and has a profile, and the rows read hold no confirmed join for the relation, the class is +read again as the statements of the mapping read it: its identity row and its contributing rows, at +most 33, in one statement for each group of 14 such classes, so that no scan maps more than 500 +rows. A class whose identity binding has a row filter is read again in the same way, because the +state of its join does not depend on the filter, and reading it keeps that state independent of the +number of tables the class binds. A page where no class is cut runs no such statement. A page of 60 +classes of which every one is cut runs five. A class over the 32 contributing tables that a +statement accepts has no state for its join and its links are `notDerivable`. Its records, and its +links when its identity table holds a confirmed join, keep the counts its identity table gives, +although the statements of the mapping refuse the class: that limit bounds a statement and does not +change what the identity table holds. Because of this read, the state of `links` never depends on +how many tables the first class binds. Nothing is stored and nothing is cached. The counts are not part of `contextDigest`, so a count changing between two pages never refuses a cursor. ## Consequences From 882eccabd7a0f6a3b99300338468aa7bbb86afef Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 08:20:59 -0800 Subject: [PATCH 070/203] Test that a stored event names the change of a masked field and holds none of its values --- ...set-can-carry-table-bindings-and-shapes.md | 9 ++++-- .../OntologyChangeSetEventDeliveryIT.java | 31 ++++++++++++++----- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md index 6620b2247853..5dd2f02ad773 100644 --- a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md +++ b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md @@ -1,7 +1,7 @@ # An ontology change set can carry table bindings and shapes - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (every path that returns operations asks for the draft read right, and a save is refused when the writer's sight changed since its read); v3 2026-11-22 (every endpoint that acts on a change set asks that right, and a stored change event holds no operations) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (every path that returns operations asks for the draft read right, and a save is refused when the writer's sight changed since its read); v3 2026-11-22 (every endpoint that acts on a change set asks that right, and a stored change event holds no operations, and records that a masked field changed without its values) - **Deciders:** Ontology Studio maintainers - **Guard:** `OntologyBindingAndShapeOperationTest`, `OntologyDraftPreflightTest`, `OntologyBindingChangeExecutorTest`, `OntologyChangeApplicationServiceTest`, `OntologyChangeEvidenceViewTest`, `OntologyChangeSetBindingIT`, `OntologyChangeSetEvidenceIT`, `OntologyChangeSetEvidenceMcpIT`, `OntologyChangeSetDraftReadIT`, `OntologyChangeSetDraftReadMcpIT`, `OntologyChangeSetSaveSightIT`, `RdfOntologyChangeSetViewIT`, `RdfExcludedEntitiesTest`, `PatchEntityToolTest`, `OntologyChangeSetCommandReadIT`, `OntologyChangeSetEventDeliveryIT`, `OntologyChangeSetEndpointRightsTest`, `OntologyChangeSetReadAccessTest`, `ChangeEventMaskingTest`, `OntologyChangeEventPublisherTest` - **Related:** ADR:2026-10-19-native-concept-bindings-remain-operational-metadata (amended by this @@ -108,8 +108,11 @@ visible stays in the draft as the stored operation holds it. `operations`, `evidence` and `withheldEvidenceCount` are masked fields (ADR:2026-10-26-masked-fields-stay-out-of-change-events-and-version-history), so no stored change -event holds them. A masked field is also left out of the recorded field changes of an event, for -every entity type. The versions of a change set keep `operations`, because they are its content and +event holds them. A stored event records that a masked field changed and never its values: the +recorded field change of a field masked as a whole, or of a path under it, keeps its entry and its +`name` and loses its `oldValue` and `newValue`, for every entity type, in the event and in the +entity it carries. An alert that matches on a field name, and a workflow trigger that does, keep +working. The versions of a change set keep `operations`, because they are its content and the endpoints that serve them ask the draft read right, and the recorded change of `operations` in a version holds the operations without their evidence. A save that changes evidence alone is stored without a new version. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java index 7eb95f1fdb75..890810336ad3 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java @@ -19,6 +19,7 @@ import static org.openmetadata.schema.entity.events.SubscriptionDestination.SubscriptionType.WEBHOOK; import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; @@ -37,7 +38,7 @@ /** * An event reaches every subscriber, destination and the audit log, and the server that stores it * cannot know who will read it. So a stored event of a change set holds no operations, in its - * entity or in the recorded changes of a field, and a subscriber who may not read the draft + * entity or in the old and new value of a recorded field change, and a subscriber who may not read the draft * receives none of its binding. The draft itself still returns its operations to a reader. */ @Isolated @@ -68,6 +69,9 @@ void aWebhookOnEveryResourceReceivesNoOperationsOfADraft(final TestNamespace ns) for (final JsonNode event : events) { assertNoOperations(event, scene); } + assertTrue( + events.stream().anyMatch(event -> !operationChangesOf(event).isEmpty()), + "a stored event still names the change of the operations"); assertTrue(OntologyDraftScene.read(scene).contains(scene.table().getId().toString())); assertTrue(OntologyDraftScene.read(scene).contains(OntologyDraftScene.VALUE)); assertTrue(versionsHoldOperations(OntologyDraftScene.versions(scene), scene)); @@ -129,14 +133,25 @@ private static void assertNoOperations( final JsonNode held = entity.isTextual() ? JsonUtils.readTree(entity.asText()) : entity; assertEquals(scene.draft().getName(), held.path("name").asText(), body); assertFalse(held.has("operations"), body); + for (final JsonNode change : operationChangesOf(event)) { + assertFalse(change.has("oldValue") || change.has("newValue"), body); + } + } + + // The change keeps its name, so an alert on a change of the operations still matches. + private static List operationChangesOf(final JsonNode event) { + final List changes = new ArrayList<>(); for (final String kind : List.of("fieldsAdded", "fieldsUpdated", "fieldsDeleted")) { - assertFalse( - event - .path("changeDescription") - .path(kind) - .findValuesAsText("name") - .contains("operations"), - body); + event + .path("changeDescription") + .path(kind) + .forEach( + change -> { + if ("operations".equals(change.path("name").asText())) { + changes.add(change); + } + }); } + return changes; } } From 1e50f81b9859b361bcef11cd911e3a1b01dccd95 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 10:34:05 -0800 Subject: [PATCH 071/203] Give no exact count from a table whose connector writes catalog statistics as its profile, and drop the unreachable target check --- .../2026-11-22-a-count-is-exact-or-absent.md | 25 ++++++---- .../service/ontology/OntologyCountRules.java | 38 ++++++++------- .../ontology/OntologyCountRulesTest.java | 46 +++++++++++++++---- 3 files changed, 70 insertions(+), 39 deletions(-) diff --git a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md index 1cd66965e745..2344f4fc5ef9 100644 --- a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md +++ b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md @@ -1,9 +1,9 @@ # A record or link count comes from the stored profiles when they are exact, and is absent when they are not - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (a class cut by the first read is read again, a deleted table holds no join, a distinct count taken after a transform is not exact); v3 2026-11-23 (a table profiled through a dataframe or from catalog statistics gives no exact count, and the second-read and limit paragraphs say what they do) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (a class cut by the first read is read again, a deleted table holds no join, a distinct count taken after a transform is not exact); v3 2026-11-23 (a table profiled through a dataframe or from catalog statistics, including SAS, gives no exact count, and the second-read and limit paragraphs say what they do) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCountRulesTest`, `NativeOntologyDataGraphCountIT`, `NativeOntologyDataGraphCountBoundIT` +- **Guard:** `OntologyCountRulesTest`, `NativeOntologyDataGraphCountIT`, `NativeOntologyDataGraphCountBoundIT`, `IndependentOntologyTableBindingIT` - **Related:** ADR:2026-11-21-graph-table-assets-carry-latest-profile-facts (the profile facts this record does not reuse), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, subject key and joins that a count reads), ADR:2026-11-22-record-statements-start-from-the-identity-table (the identity table and the join that a count follows) ## Context @@ -17,7 +17,9 @@ A table profile has a `rowCount`, but it is not always counted. Where an engine' row count, the profiler stores that figure and runs no `COUNT(*)`. On Postgres it is `reltuples` and on MySQL `TABLE_ROWS`, and both are estimates. The column metrics `valuesCount`, `nullCount` and `distinctCount` are different: the profiler counts them with a query over the rows it read. -Those rows are the whole table, a sample, a partition window or the result of a custom query. +Those rows are the whole table, a sample, a partition window or the result of a custom query. A +connector can also write a profile of its own, from the catalog's statistics, and a count in it is +not a count over the rows. ## Decision @@ -86,17 +88,19 @@ in chunks, and the profiler casts every chunk to the column types of the catalog A null in a string column becomes the text `'None'` or `'nan'`, in a bytes column `b'None'` and in a boolean column `True`, so `nullCount` falls to 0 and `valuesCount` and `distinctCount` count the nulls. Every records or links count that reads a profile of a table of these service types, which -is a key on the identity table, a child column of a join, or the key of the related class's table, -is `notDerivable`. The service types are the ones whose profiler is +is a key on the identity table or a child column of a join, is `notDerivable`. The service types are the ones whose profiler is `PandasProfilerInterface` or a subclass of it, and the list is in `OntologyCountRules` with the profiler code it comes from. -**A table whose profiler can take counts from catalog statistics gives no exact count.** Trino and +**A table whose counts can come from a catalog's statistics gives no exact count.** Trino and StarRocks tables are profiled by a profiler that, when the pipeline sets `useStatistics`, takes `distinctCount` and `nullCount` from the engine's statistics: `SHOW STATS`, a rounded null -fraction, and a HyperLogLog estimate. The stored profile does not say which path made it, a -pipeline's setting can change after a run, and a run can come from outside a pipeline, so no table -of these service types gives an exact count, whatever the setting. The rule is the one above, with +fraction, and a HyperLogLog estimate. The SAS connector writes the column profiles itself, from the +SAS catalog (`ingestion/source/database/sas/metadata.py:468-488`): `missingCount` becomes +`nullCount`, `cardinalityCount` becomes `distinctCount`, and the table's `rowCount` becomes +`valuesCount`, so `valuesCount` counts the null rows. The stored profile does not say which path +made it, a pipeline's setting can change after a run, and a run can come from outside a pipeline, +so no table of these service types gives an exact count, whatever the setting. The rule is the one above, with its own list in `OntologyCountRules`. A stored marker of where a count came from would let these tables give exact counts again. @@ -104,7 +108,8 @@ tables give exact counts again. onto the identity table of the related class, confirmed and held by the identity binding of the first class. A join held by a contributing table gives no count, and a contributing table that does not exist holds no join, as in the statements of the mapping. The join's parent columns are the -related class's subject key in order. Neither identity binding has a row filter. The key of the +related class's subject key in order. A join target must sit in the bound table's database +(`IndependentOntologyTableBindingIT`), so one service type covers both tables. Neither identity binding has a row filter. The key of the first class is unique and holds no nulls. The metrics of every child column covered the whole table and at most one holds nulls. The count is `valuesCount` of that child column, or of any child column when none holds nulls. It counts non-null references, so a reference that matches no row of diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java index 94cdea987b20..dd7e341d9bde 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java @@ -164,13 +164,14 @@ final class OntologyCountRules { private static final Set PROFILED_FROM_DATAFRAMES = Set.of("Datalake", "BurstIQ"); /** - * The service types whose profiler can take a column's {@code distinctCount} and {@code - * nullCount} from the engine's catalog statistics instead of counting them. The stored profile - * does not say which path made it, a pipeline's {@code useStatistics} can change after a run, - * and a run can come from outside a pipeline, so no table of these service types gives an exact - * count. Every profiler that reads catalog statistics extends {@code ProfilerWithStatistics} - * ({@code profiler/interface/sqlalchemy/stored_statistics_profiler.py:49}), which replaces the - * counts when {@code useStatistics} is set (lines 69 and 104), and implements the {@code + * The service types whose column counts come from a catalog's statistics instead of a count over + * the rows, either because the profiler can read them from the catalog or because the connector + * writes the profile itself. The stored profile does not say which path made it, a pipeline's + * {@code useStatistics} can change after a run, and a run can come from outside a pipeline, so no + * table of these service types gives an exact count. Every profiler that reads catalog statistics + * extends {@code ProfilerWithStatistics} ({@code + * profiler/interface/sqlalchemy/stored_statistics_profiler.py:49}), which replaces the counts + * when {@code useStatistics} is set (lines 69 and 104), and implements the {@code * StoredStatisticsSource} of its engine (line 37). Two do: * *
      @@ -187,12 +188,17 @@ final class OntologyCountRules { * ingestion/source/database/starrocks/profiler/system_tables_profiler.py:82}). *
    * - * No other profiler or sampler computes a distinct, values or null count other than over the rows - * it read: the approximate functions of the dialects are percentiles ({@code + * One connector writes the column profiles itself, from the catalog's statistics: {@code SAS} + * ({@code ingestion/source/database/sas/metadata.py:468-488}). Its {@code missingCount} becomes + * {@code nullCount}, its {@code cardinalityCount} becomes {@code distinctCount}, and the table's + * {@code rowCount} becomes {@code valuesCount}, so {@code valuesCount} counts the null rows. + * + *

    No other profiler or sampler computes a distinct, values or null count other than over the + * rows it read: the approximate functions of the dialects are percentiles ({@code * profiler/orm/functions/median.py}), and a sampled or windowed read is recorded by the profile's * sample, the table's partition and the profiler configuration, which the rule already reads. */ - private static final Set PROFILED_FROM_STATISTICS = Set.of("Trino", "StarRocks"); + private static final Set PROFILED_FROM_STATISTICS = Set.of("Trino", "StarRocks", "SAS"); private static final double WHOLE_PERCENTAGE = 100d; @@ -311,11 +317,7 @@ static NativeOntologyCount links( case Lookup.Unconfirmed ignored -> subject.truncated() ? notDerivable() : state(State.JOIN_NOT_CONFIRMED); - case Lookup.Confirmed found -> linkCount( - probe.source(), - probe.target(), - found.stored(), - facts.tables().get(probe.target().assetId())); + case Lookup.Confirmed found -> linkCount(probe.source(), probe.target(), found.stored()); }; } @@ -414,10 +416,7 @@ private static NativeOntologyCount valueOfAtMostOneNullable( } private static NativeOntologyCount linkCount( - final Source source, - final BindingRow target, - final OntologyRelationPath.StoredJoin stored, - final Table targetTable) { + final Source source, final BindingRow target, final OntologyRelationPath.StoredJoin stored) { final List> key = source.row().subjectKey(); final List on = listOrEmpty(stored.join().getOn()); final boolean joined = @@ -428,7 +427,6 @@ private static NativeOntologyCount linkCount( .toList() .equals(target.subjectKey()); if (!joined - || !countsOverTheRows(targetTable) || source.row().rowFilter() != null || target.rowFilter() != null || nullOrEmpty(key) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java index 38463537f990..1298f5f8cbc0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java @@ -609,19 +609,19 @@ void aTransformedColumnOfAKeyOfSeveralColumnsStillCountsItsValues() { assertExact(100, world.records(ORDER)); } - // Dataframe profilers (Datalake, BurstIQ) cast every chunk before counting, and statistics - // profilers (Trino, StarRocks) can estimate, so a table of these service types gives no exact - // count. + // Dataframe profilers (Datalake, BurstIQ) cast every chunk before counting, statistics + // profilers (Trino, StarRocks) can estimate, and the SAS connector writes the catalog's + // statistics as the profile, so a table of these service types gives no exact count. @ParameterizedTest - @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks", "SAS"}) void aOneColumnKeyOnAServiceTypeThatGivesNoExactCountHasNoRecords(final String engine) { final var world = new World().engine(engine); assertState(State.NOT_DERIVABLE, world.records(ORDER)); } @ParameterizedTest - @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks", "SAS"}) void aRelationWhoseChildColumnIsOnAServiceTypeThatGivesNoExactCountHasNoLinks( final String engine) { final var world = new World().engine(engine); @@ -629,13 +629,41 @@ void aRelationWhoseChildColumnIsOnAServiceTypeThatGivesNoExactCountHasNoLinks( } @ParameterizedTest - @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks"}) - void aRelationOntoAKeyOnAServiceTypeThatGivesNoExactCountHasNoLinks(final String engine) { - final var world = new World().targetEngine(engine); - assertExact(100, world.records(ORDER)); + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks", "SAS"}) + void aDeclaredKeyOfSeveralNotNullColumnsOnAServiceTypeThatGivesNoExactCountHasNoRecords( + final String engine) { + final var world = World.twoColumnKey(engine); + world.columnConstraint("id", ColumnConstraint.NOT_NULL); + world.columnConstraint("tenant", ColumnConstraint.NOT_NULL); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks", "SAS"}) + void aDeclaredPrimaryKeyOnAServiceTypeThatGivesNoExactCountHasNoLinks(final String engine) { + final var world = new World().engine(engine); + world.tableConstraint(TableConstraint.ConstraintType.PRIMARY_KEY, "id"); + world.columnConstraint("id", ColumnConstraint.NOT_NULL); assertState(State.NOT_DERIVABLE, world.links()); } + // The SAS connector stores the table's row count as valuesCount, so a column of 9 rows with 2 + // missing has valuesCount 9, nullCount 2 and distinctCount 4, and the nulls are counted. + + @Test + void aSasProfileThatCountsTheNullRowsGivesNoLinks() { + final var world = new World().engine("SAS"); + world.metrics("customer_id", 9, 2, 4); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void theSameProfileOnPostgresGivesTheValuesCountAsLinks() { + final var world = new World().engine("Postgres"); + world.metrics("customer_id", 9, 2, 4); + assertExact(9, world.links()); + } + @ParameterizedTest @ValueSource( strings = {"Postgres", "Mysql", "Snowflake", "BigQuery", "Redshift", "Databricks", "Hive"}) From 3bf3aebcfbdd3ab0dace4331b6ed3217e7bd29cf Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 10:38:13 -0800 Subject: [PATCH 072/203] Refuse a declared key on a table that gives no exact count --- .../openmetadata/service/ontology/OntologyCountRules.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java index dd7e341d9bde..ea13c54a9f6e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java @@ -614,8 +614,15 @@ boolean distinctIsTransformed(final List path) { .contains(column.getDataType()); } + /** + * A declared key decides only on an engine that checks it and whose table gives an exact count. + * No answer reads a declared key of a table that gives none, because {@link #metrics} is null + * there and every count needs metrics, so this refusal holds the line if a type reaches both + * lists. + */ private boolean enforcesKeys() { return table.getServiceType() != null + && countsOverTheRows(table) && ENGINES_THAT_ENFORCE_KEYS.contains(table.getServiceType().value()); } From d729a0c4f0a565f827bb8cd23ef967c29eb52147 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 11:50:34 -0800 Subject: [PATCH 073/203] Regenerate the UI's TypeScript types for change set operations --- .../api/data/createOntologyChangeSet.ts | 308 ++++++++++++++++- .../api/data/nativeOntologyImportPreview.ts | 304 ++++++++++++++++- .../api/data/ontologyDomainDraftResult.ts | 308 ++++++++++++++++- .../api/data/ontologyMappingSuggestion.ts | 308 ++++++++++++++++- .../api/data/ontologyMappingSuggestionList.ts | 308 ++++++++++++++++- .../data/ontologyRelationshipSuggestion.ts | 308 ++++++++++++++++- .../ontologyRelationshipSuggestionList.ts | 308 ++++++++++++++++- .../api/data/updateOntologyChangeSet.ts | 308 ++++++++++++++++- .../entity/data/ontologyChangeSet.ts | 315 +++++++++++++++++- .../generated/type/ontologyBindingChange.ts | 122 +++++++ .../generated/type/ontologyChangeEvidence.ts | 51 +++ .../generated/type/ontologyChangeOperation.ts | 308 ++++++++++++++++- 12 files changed, 3167 insertions(+), 89 deletions(-) create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyBindingChange.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyChangeEvidence.ts diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/createOntologyChangeSet.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/createOntologyChangeSet.ts index 65584e051e76..59d7c205477d 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/createOntologyChangeSet.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/createOntologyChangeSet.ts @@ -46,17 +46,34 @@ export interface CreateOntologyChangeSet { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -69,10 +86,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -80,6 +103,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -360,6 +393,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -487,6 +645,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -877,9 +1075,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -938,7 +1138,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -984,7 +1184,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -1007,6 +1207,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyImportPreview.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyImportPreview.ts index 5a551ac28c26..60897cf145fb 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyImportPreview.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyImportPreview.ts @@ -60,17 +60,34 @@ export interface CreateOntologyChangeSetRequest { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -83,10 +100,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -94,6 +117,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -374,6 +407,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -501,6 +659,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -891,9 +1089,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -1021,6 +1221,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyDomainDraftResult.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyDomainDraftResult.ts index 45993e2cc0a6..d863eea20cbf 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyDomainDraftResult.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyDomainDraftResult.ts @@ -55,17 +55,34 @@ export interface CreateOntologyChangeSetRequest { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -78,10 +95,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -89,6 +112,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -369,6 +402,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -496,6 +654,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -886,9 +1084,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -947,7 +1147,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -993,7 +1193,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -1016,6 +1216,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingSuggestion.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingSuggestion.ts index afb8313880c4..8e811f3986c7 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingSuggestion.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingSuggestion.ts @@ -27,17 +27,34 @@ export interface OntologyMappingSuggestion { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -50,10 +67,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -61,6 +84,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -341,6 +374,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -468,6 +626,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -858,9 +1056,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -919,7 +1119,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -965,7 +1165,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -988,6 +1188,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingSuggestionList.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingSuggestionList.ts index 35ec24fa660a..5d7145a13cd8 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingSuggestionList.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingSuggestionList.ts @@ -36,17 +36,34 @@ export interface OntologyMappingSuggestion { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -59,10 +76,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -70,6 +93,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -350,6 +383,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -477,6 +635,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -867,9 +1065,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -928,7 +1128,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -974,7 +1174,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -997,6 +1197,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyRelationshipSuggestion.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyRelationshipSuggestion.ts index 41e0fb9a012b..10dfb9c37b2f 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyRelationshipSuggestion.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyRelationshipSuggestion.ts @@ -26,17 +26,34 @@ export interface OntologyRelationshipSuggestion { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -49,10 +66,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -60,6 +83,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -340,6 +373,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -467,6 +625,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -857,9 +1055,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -918,7 +1118,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -964,7 +1164,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -987,6 +1187,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyRelationshipSuggestionList.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyRelationshipSuggestionList.ts index 9685706136db..0bc36b9b8a54 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyRelationshipSuggestionList.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyRelationshipSuggestionList.ts @@ -35,17 +35,34 @@ export interface OntologyRelationshipSuggestion { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -58,10 +75,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -69,6 +92,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -349,6 +382,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -476,6 +634,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -866,9 +1064,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -927,7 +1127,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -973,7 +1173,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -996,6 +1196,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/updateOntologyChangeSet.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/updateOntologyChangeSet.ts index c5836155dcad..dc3313d72944 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/updateOntologyChangeSet.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/updateOntologyChangeSet.ts @@ -33,17 +33,34 @@ export interface OntologyEditLeaseToken { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -56,10 +73,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -67,6 +90,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -347,6 +380,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -474,6 +632,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -864,9 +1062,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -925,7 +1125,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -971,7 +1171,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -994,6 +1194,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/entity/data/ontologyChangeSet.ts b/openmetadata-ui/src/main/resources/ui/src/generated/entity/data/ontologyChangeSet.ts index 4c474109bb45..e27627f2a1da 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/entity/data/ontologyChangeSet.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/entity/data/ontologyChangeSet.ts @@ -36,7 +36,12 @@ export interface OntologyChangeSet { /** * Native ontology scope. Mutually exclusive with glossaries. */ - ontology?: EntityReference; + ontology?: EntityReference; + /** + * The operations of the draft. Reads that ask the draft read right return them. A stored + * change event never holds them, because an event reaches every subscriber and the server + * cannot know who may read the draft. + */ operations: OntologyChangeOperation[]; owners?: EntityReference[]; provider?: ProviderType; @@ -231,17 +236,34 @@ export interface FieldChange { export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -254,10 +276,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -265,6 +293,16 @@ export interface OntologyChangeOperation { state: OperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -413,6 +451,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -540,6 +703,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -930,9 +1133,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -991,7 +1196,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -1037,7 +1242,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -1060,6 +1265,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OperationState { Active = "ACTIVE", Undone = "UNDONE", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyBindingChange.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyBindingChange.ts new file mode 100644 index 000000000000..b49431a3bcd3 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyBindingChange.ts @@ -0,0 +1,122 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyChangeEvidence.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyChangeEvidence.ts new file mode 100644 index 000000000000..6b6a76d2b084 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyChangeEvidence.ts @@ -0,0 +1,51 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: Kind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum Kind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyChangeOperation.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyChangeOperation.ts index 5381711fd449..a0a6673991ed 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyChangeOperation.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyChangeOperation.ts @@ -16,17 +16,34 @@ export interface OntologyChangeOperation { axiom?: OntologyAxiom; /** - * Version used for optimistic concurrency. Omitted for create operations. + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. */ baseVersion?: number; - concept?: OntologyConcept; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; /** * Model confidence in this AI suggestion, from 0 to 1. */ confidence?: number; - glossary?: Glossary; - id: string; - mapping?: ConceptMapping; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; /** * Identifier of the model that produced this AI suggestion. */ @@ -39,10 +56,16 @@ export interface OntologyChangeOperation { rationale?: string; relationship?: OntologyRelationship; /** - * IRIs of concepts that an import expects to create in the same change set. Applying the - * operation without an UPSERT_CONCEPT operation for each of them is refused. + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. */ requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; /** * Published context memories that support this AI suggestion. */ @@ -50,6 +73,16 @@ export interface OntologyChangeOperation { state: OntologyChangeOperationState; targetId?: string; term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; } /** @@ -330,6 +363,131 @@ export enum ProviderType { User = "user", } +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + /** * A formal class, SKOS concept, or both, owned by an ontology independently of glossary * terms. @@ -457,6 +615,46 @@ export enum OntologyDefinitionStatus { InReview = "InReview", } +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + /** * This schema defines the Glossary entity. A Glossary is collection of hierarchical * GlossaryTerms. @@ -847,9 +1045,11 @@ export enum OperationType { UpdateRelationship = "UPDATE_RELATIONSHIP", UpdateTerm = "UPDATE_TERM", UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", UpsertConcept = "UPSERT_CONCEPT", UpsertMapping = "UPSERT_MAPPING", UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", } /** @@ -908,7 +1108,7 @@ export interface OntologyProperty { * OWL key, or uniqueness in source data. */ isIdentifier?: boolean; - kind: Kind; + kind: PropertyKind; name: string; /** * Owning ontology entity. Glossaries do not own ontology definitions. @@ -954,7 +1154,7 @@ export enum Characteristic { Transitive = "TRANSITIVE", } -export enum Kind { +export enum PropertyKind { Annotation = "ANNOTATION", Data = "DATA", Object = "OBJECT", @@ -977,6 +1177,96 @@ export interface OntologyRelationship { toTerm: EntityReference; } +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + export enum OntologyChangeOperationState { Active = "ACTIVE", Undone = "UNDONE", From bcaba17b44a3d1736fbbfc2690e64ef23ef5adfe Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 14:45:30 -0800 Subject: [PATCH 074/203] Regenerate the UI's TypeScript types for record and link counts --- .../api/data/nativeOntologyAssetCluster.ts | 53 +++++++++++++++ .../generated/api/data/nativeOntologyCount.ts | 56 ++++++++++++++++ .../api/data/nativeOntologyDataGraph.ts | 61 +++++++++++++++++ .../api/data/nativeOntologyDataGraphPage.ts | 65 ++++++++++++++++++- 4 files changed, 233 insertions(+), 2 deletions(-) create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyCount.ts diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyAssetCluster.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyAssetCluster.ts index ecdaa405aee5..dc3d9a116541 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyAssetCluster.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyAssetCluster.ts @@ -31,6 +31,11 @@ export interface NativeOntologyAssetCluster { * Concept represented by the cluster. */ concept: EntityReference; + /** + * How many records the concept has, from the stored profiles of its identity table. Absent + * when the concept binds no table. + */ + records?: NativeOntologyCount; } export interface Asset { @@ -113,3 +118,51 @@ export interface EntityReference { */ type: string; } + +/** + * How many records the concept has, from the stored profiles of its identity table. Absent + * when the concept binds no table. + * + * A count that the stored profiles of a table give exactly, or the reason they do not. A + * count is exact or it is absent: a profile's row count is never used, because the profiler + * may take it from the engine's catalog, which can be an estimate. + */ +export interface NativeOntologyCount { + /** + * Time of the profile run whose metrics gave the count. Present exactly when state is exact. + */ + profiledAt?: number; + /** + * exact: the stored profiles give the number. noIdentityTable: the class binds tables and + * none is its identity table. identityTableHidden: the class has an identity table that the + * caller may not view, or that is deleted. noProfile: the caller may not view the data + * profile of the table, or the table has no stored profile. joinNotConfirmed: the relation + * has a join onto the identity table of the related class and it is not confirmed. noJoin: + * the relation has no join onto it. notDerivable: the stored profiles cannot give the exact + * number, and a query over the table could. + */ + state: State; + /** + * The count. Present exactly when state is exact. + */ + value?: number; +} + +/** + * exact: the stored profiles give the number. noIdentityTable: the class binds tables and + * none is its identity table. identityTableHidden: the class has an identity table that the + * caller may not view, or that is deleted. noProfile: the caller may not view the data + * profile of the table, or the table has no stored profile. joinNotConfirmed: the relation + * has a join onto the identity table of the related class and it is not confirmed. noJoin: + * the relation has no join onto it. notDerivable: the stored profiles cannot give the exact + * number, and a query over the table could. + */ +export enum State { + Exact = "exact", + IdentityTableHidden = "identityTableHidden", + JoinNotConfirmed = "joinNotConfirmed", + NoIdentityTable = "noIdentityTable", + NoJoin = "noJoin", + NoProfile = "noProfile", + NotDerivable = "notDerivable", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyCount.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyCount.ts new file mode 100644 index 000000000000..78fd2a6bcf50 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyCount.ts @@ -0,0 +1,56 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A count that the stored profiles of a table give exactly, or the reason they do not. A + * count is exact or it is absent: a profile's row count is never used, because the profiler + * may take it from the engine's catalog, which can be an estimate. + */ +export interface NativeOntologyCount { + /** + * Time of the profile run whose metrics gave the count. Present exactly when state is exact. + */ + profiledAt?: number; + /** + * exact: the stored profiles give the number. noIdentityTable: the class binds tables and + * none is its identity table. identityTableHidden: the class has an identity table that the + * caller may not view, or that is deleted. noProfile: the caller may not view the data + * profile of the table, or the table has no stored profile. joinNotConfirmed: the relation + * has a join onto the identity table of the related class and it is not confirmed. noJoin: + * the relation has no join onto it. notDerivable: the stored profiles cannot give the exact + * number, and a query over the table could. + */ + state: State; + /** + * The count. Present exactly when state is exact. + */ + value?: number; +} + +/** + * exact: the stored profiles give the number. noIdentityTable: the class binds tables and + * none is its identity table. identityTableHidden: the class has an identity table that the + * caller may not view, or that is deleted. noProfile: the caller may not view the data + * profile of the table, or the table has no stored profile. joinNotConfirmed: the relation + * has a join onto the identity table of the related class and it is not confirmed. noJoin: + * the relation has no join onto it. notDerivable: the stored profiles cannot give the exact + * number, and a query over the table could. + */ +export enum State { + Exact = "exact", + IdentityTableHidden = "identityTableHidden", + JoinNotConfirmed = "joinNotConfirmed", + NoIdentityTable = "noIdentityTable", + NoJoin = "noJoin", + NoProfile = "noProfile", + NotDerivable = "notDerivable", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyDataGraph.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyDataGraph.ts index 6a63a13f4522..e865387cbcf9 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyDataGraph.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyDataGraph.ts @@ -55,6 +55,11 @@ export interface NativeOntologyAssetCluster { * Concept represented by the cluster. */ concept: EntityReference; + /** + * How many records the concept has, from the stored profiles of its identity table. Absent + * when the concept binds no table. + */ + records?: NativeOntologyCount; } export interface Asset { @@ -143,6 +148,57 @@ export interface EntityReference { type: string; } +/** + * How many records the concept has, from the stored profiles of its identity table. Absent + * when the concept binds no table. + * + * A count that the stored profiles of a table give exactly, or the reason they do not. A + * count is exact or it is absent: a profile's row count is never used, because the profiler + * may take it from the engine's catalog, which can be an estimate. + * + * How many links the relation has from the records of the first concept, from the stored + * profiles of its identity table. Absent when the page does not hold the first concept. + */ +export interface NativeOntologyCount { + /** + * Time of the profile run whose metrics gave the count. Present exactly when state is exact. + */ + profiledAt?: number; + /** + * exact: the stored profiles give the number. noIdentityTable: the class binds tables and + * none is its identity table. identityTableHidden: the class has an identity table that the + * caller may not view, or that is deleted. noProfile: the caller may not view the data + * profile of the table, or the table has no stored profile. joinNotConfirmed: the relation + * has a join onto the identity table of the related class and it is not confirmed. noJoin: + * the relation has no join onto it. notDerivable: the stored profiles cannot give the exact + * number, and a query over the table could. + */ + state: State; + /** + * The count. Present exactly when state is exact. + */ + value?: number; +} + +/** + * exact: the stored profiles give the number. noIdentityTable: the class binds tables and + * none is its identity table. identityTableHidden: the class has an identity table that the + * caller may not view, or that is deleted. noProfile: the caller may not view the data + * profile of the table, or the table has no stored profile. joinNotConfirmed: the relation + * has a join onto the identity table of the related class and it is not confirmed. noJoin: + * the relation has no join onto it. notDerivable: the stored profiles cannot give the exact + * number, and a query over the table could. + */ +export enum State { + Exact = "exact", + IdentityTableHidden = "identityTableHidden", + JoinNotConfirmed = "joinNotConfirmed", + NoIdentityTable = "noIdentityTable", + NoJoin = "noJoin", + NoProfile = "noProfile", + NotDerivable = "notDerivable", +} + /** * Two returned concepts that an object property joins, through an object property assertion * or a class restriction. @@ -154,6 +210,11 @@ export interface ConceptEdge { * ontology declares none the caller may view. */ label: string; + /** + * How many links the relation has from the records of the first concept, from the stored + * profiles of its identity table. Absent when the page does not hold the first concept. + */ + links?: NativeOntologyCount; /** * The declared property, when this ontology declares one for the IRI and the caller may * view it. diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyDataGraphPage.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyDataGraphPage.ts index d5cccc826ddb..a488fa646f7c 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyDataGraphPage.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/nativeOntologyDataGraphPage.ts @@ -169,7 +169,7 @@ export interface ColumnBinding { * Unresolved when the exact column is missing or the property is unavailable or no longer * applicable. No rename inference is performed. */ - state: State; + state: ColumnState; } export interface Column { @@ -310,7 +310,7 @@ export enum JoinStatus { * Unresolved when the exact column is missing or the property is unavailable or no longer * applicable. No rename inference is performed. */ -export enum State { +export enum ColumnState { Resolved = "resolved", Unresolved = "unresolved", } @@ -379,6 +379,11 @@ export interface NativeOntologyAssetCluster { * Concept represented by the cluster. */ concept: EntityReference; + /** + * How many records the concept has, from the stored profiles of its identity table. Absent + * when the concept binds no table. + */ + records?: NativeOntologyCount; } export interface Asset { @@ -411,6 +416,57 @@ export interface Asset { serviceType?: string; } +/** + * How many records the concept has, from the stored profiles of its identity table. Absent + * when the concept binds no table. + * + * A count that the stored profiles of a table give exactly, or the reason they do not. A + * count is exact or it is absent: a profile's row count is never used, because the profiler + * may take it from the engine's catalog, which can be an estimate. + * + * How many links the relation has from the records of the first concept, from the stored + * profiles of its identity table. Absent when the page does not hold the first concept. + */ +export interface NativeOntologyCount { + /** + * Time of the profile run whose metrics gave the count. Present exactly when state is exact. + */ + profiledAt?: number; + /** + * exact: the stored profiles give the number. noIdentityTable: the class binds tables and + * none is its identity table. identityTableHidden: the class has an identity table that the + * caller may not view, or that is deleted. noProfile: the caller may not view the data + * profile of the table, or the table has no stored profile. joinNotConfirmed: the relation + * has a join onto the identity table of the related class and it is not confirmed. noJoin: + * the relation has no join onto it. notDerivable: the stored profiles cannot give the exact + * number, and a query over the table could. + */ + state: RecordsState; + /** + * The count. Present exactly when state is exact. + */ + value?: number; +} + +/** + * exact: the stored profiles give the number. noIdentityTable: the class binds tables and + * none is its identity table. identityTableHidden: the class has an identity table that the + * caller may not view, or that is deleted. noProfile: the caller may not view the data + * profile of the table, or the table has no stored profile. joinNotConfirmed: the relation + * has a join onto the identity table of the related class and it is not confirmed. noJoin: + * the relation has no join onto it. notDerivable: the stored profiles cannot give the exact + * number, and a query over the table could. + */ +export enum RecordsState { + Exact = "exact", + IdentityTableHidden = "identityTableHidden", + JoinNotConfirmed = "joinNotConfirmed", + NoIdentityTable = "noIdentityTable", + NoJoin = "noJoin", + NoProfile = "noProfile", + NotDerivable = "notDerivable", +} + export interface LoadedPrefix { bindingRevision: number; conceptId: string; @@ -440,6 +496,11 @@ export interface ConceptEdge { * ontology declares none the caller may view. */ label: string; + /** + * How many links the relation has from the records of the first concept, from the stored + * profiles of its identity table. Absent when the page does not hold the first concept. + */ + links?: NativeOntologyCount; /** * The declared property, when this ontology declares one for the IRI and the caller may * view it. From 0fcb50beed22271b62c7a90fd74714be24c9d08d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 16:42:25 -0800 Subject: [PATCH 075/203] Compile the shapes of a class into data quality checks A pure function answers each part of a shape constraint for the tables that the class binds: a built-in column test, a query the server writes, held by the mapping, not mapped, or not enforceable with a reason. A test is offered only when it finds a violation exactly when a record breaks the part. The response schema is api/data/ontologyShapeChecks.json. The decision record states the meaning of a record and a value, the rule for each part, and why each refusal exists. --- ...ape-check-is-exact-or-it-is-not-offered.md | 179 ++++ .../service/ontology/OntologyBuiltinTest.java | 99 ++ .../service/ontology/OntologyCheckGates.java | 223 ++++ .../service/ontology/OntologyCheckProbe.java | 80 ++ .../ontology/OntologyDeclaredKeys.java | 104 ++ .../service/ontology/OntologyPartOutcome.java | 57 ++ .../ontology/OntologyPortablePattern.java | 183 ++++ .../service/ontology/OntologySettled.java | 67 ++ .../OntologyShapeCardinalityRules.java | 170 ++++ .../ontology/OntologyShapeCheckCompiler.java | 291 ++++++ .../ontology/OntologyShapeCheckFacts.java | 101 ++ .../ontology/OntologyShapeValueRules.java | 356 +++++++ .../service/ontology/sql/SqlEngineFamily.java | 17 +- .../service/ontology/sql/TypedValues.java | 31 +- .../ontology/OntologyPortablePatternTest.java | 106 ++ .../OntologyShapeCheckCompilerTest.java | 952 ++++++++++++++++++ .../ontology/OntologyShapeCheckModel.java | 202 ++++ .../schema/api/data/ontologyShapeChecks.json | 218 ++++ 18 files changed, 3418 insertions(+), 18 deletions(-) create mode 100644 docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBuiltinTest.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySettled.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java create mode 100644 openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md new file mode 100644 index 000000000000..a34beadfdfc7 --- /dev/null +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -0,0 +1,179 @@ +# A shape check is exact or it is not offered + +- **Status:** Accepted +- **Revisions:** v1 2026-11-23 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyShapeCheckCompilerTest`, `OntologyPortablePatternTest` +- **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) + +## Context + +A shape says what the records of a class must satisfy: how many values a property has, which class +or datatype a value has, and which values are allowed. A table binding says which rows of which +tables are those records. A data quality test runs on one table and counts rows. + +A row is not always a record. A binding can keep only some rows of a table, two rows can share a +key, a key column can hold a null, and a value can sit in a second table. A test that counts rows +then reports a violation that no record has, or misses one that a record has. A person who reads +the result cannot tell which of the two happened, so a test of that kind is worse than no test. + +## Decision + +**The server says how each constraint of a class's shapes is checked, and creates nothing.** +`GET /v1/ontologyConcepts/{id}/shapeChecks` compiles every shape that targets the class in the +release or the draft. A constraint is answered part by part: `minCount`, `maxCount`, `class`, +`datatype`, `range` (`minInclusive` and `maxInclusive` together), `in` and `pattern`. Each part gets +one of five outcomes. + +| Outcome | Meaning | +|---|---| +| `check` | A test finds a violation exactly when a record breaks the part. One check for each table. | +| `heldByMapping` | No record can break the part, because of how the class is mapped. | +| `notMapped` | The class binds the property in no column, or the version has no such property. | +| `notEnforceable` | No exact test exists. A `reason` from a closed list says why. | +| `hidden` | The caller may not view a table that the answer rests on. | + +**A check is exact.** Its number is 0 exactly when every record satisfies the part. Where no such +test exists the part is `notEnforceable`. The server never offers a test that is close. + +**What is checked.** + +- A record of a class is a row of its identity table that the row filter of the binding keeps and + whose subject key columns are all non-null. Rows with the same key are one record. Only records + are checked. A row of a contributing table or a link table whose key matches no record is not + checked. +- A data property has a value on a record in each bound column that is not null. A relation has a + value where the columns of its confirmed join are all non-null. Whether that value is a record of + some class is what `class` asks, so a key that matches no row still counts as a value for + `minCount` and `maxCount`. +- Only the bindings of the class that the shape targets are read. A shape is not compiled for the + subclasses of its target, because a statement about a class does not read their rows. +- Two values are equal when the source says so, its collation included. A source that compares + text without regard to case counts `a` and `A` as one value, and finds `A` in a list that holds + `a`. The check and the source agree, which is what a person who reads the table expects. + +**A table is simple for the class** when it is the identity table of the class, the binding has no +row filter, and the columns of its declared primary key are exactly the subject key. On a simple +table each row is one record and each record is one row. A primary key is declared by a +`PRIMARY_KEY` table constraint, or by the column constraint `PRIMARY_KEY` when exactly one column +carries it. The declaration in the catalog is taken at its word. + +**The rule.** "Generated" is a `tableCustomSQLQuery` test whose query the server writes. + +| Part | On a simple table | Anywhere else | +|---|---|---| +| `minCount 0` | `heldByMapping` | `heldByMapping` | +| `minCount 1`, a property bound to a subject key column of the identity table | `heldByMapping` | `heldByMapping` | +| `minCount 1`, one column | `columnValuesToBeNotNull` | generated: records with no value | +| `minCount 1`, a relation of several columns | generated | generated | +| `minCount n`, n above 1 | generated | generated: records with fewer than n distinct values | +| `maxCount n`, n at least 1, a value on a simple table, or on a table where a declared primary or unique key lies inside the subject key columns | `heldByMapping` | `heldByMapping` | +| `maxCount n` otherwise, `maxCount 0` included | generated | generated: records with more than n distinct values | +| `in`, literals | `columnValuesToBeInSet` with `matchEnum` `true`, for a text or whole-number column with the column constraint `NOT_NULL` or `PRIMARY_KEY` | generated: values outside the list | +| `range` | `columnValuesToBeBetween`, for a numeric column and bounds that a double holds exactly | generated: values outside the bounds | +| `pattern` | `columnValuesToMatchRegex`, for a portable pattern | `notEnforceable` | +| `class` | generated: values with no record of that class | the same | +| `datatype` | `heldByMapping` when every value of the column's type is a value of the datatype, else `notEnforceable` | the same | + +**A column test needs a simple table, because it counts rows.** A row that the filter drops is no +record, and a column test still reads it. Two rows with one key are one record: when one holds a +null and the other a value, the record has a value and `columnValuesToBeNotNull` fails. A value in +a contributing table belongs to a record only when its key matches one, and a column test cannot +ask. A generated query starts from the records, so it is exact on every table. + +**`columnValuesToBeInSet` runs with `matchEnum`.** Without it the test passes as soon as one listed +value occurs in the column, whatever the other rows hold. With it the test counts the rows whose +value is not listed. It counts a null as not listed, and a null is no value, so the column must be +declared `NOT_NULL` or `PRIMARY_KEY`. The test reads a list of text or of whole numbers, so other +column types get the generated query. + +**`columnValuesToBeBetween` reads its bounds as doubles.** A bound that no double holds exactly +would move, so such a range gets the generated query. So does a range on a date, a time or a +timestamp column. A range on a column whose values have no order the server knows is +`notEnforceable`. + +**A generated test counts in the source.** It runs with the strategy `COUNT`, the operator `<=` and +the threshold `0`, so the query returns one number and the test passes exactly when the number is +0. The strategy `ROWS` would bring one row for each violation to the runner. The count query has no +`ORDER BY` and no row limit. A second query, `inspectionQuery`, lists the keys of the records in +violation for a person to read. Every column in both is qualified with its table alias, every table +is in one database, and no label, comment or name of an ontology term reaches the text. A value +reaches the text only as a typed value +(ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). + +**A pattern is checked only when every engine reads it alike.** The regex test is the only way to +check a pattern, so the column is a text column of a simple table. The pattern starts with `^` and +ends with an unescaped `$`. Between them it holds only letters, digits and spaces, escaped +punctuation, `.`, character classes of plain characters and ranges, negated or not, groups with no +prefix, alternation inside a group, and the quantifiers `?`, `*`, `+`, `{n}`, `{n,}` and `{n,m}`. +An alternation outside a group is refused, because `^a|b$` means something else on an engine that +anchors a pattern by itself. A back reference, a look-around, a lazy or possessive quantifier, a +class such as `\d`, an anchor in the middle and a flag are refused. On the `MYSQL` family a pattern +with a letter is refused too, because a match there ignores case under most collations. The `TSQL` +family has no such operator. A refused pattern is `notEnforceable`. + +**`class` reads the confirmed join of a relation.** The class of the constraint must have its +identity table where the join arrives. The query counts the values that match no record of that +class, so it carries the row filter of that binding and its non-null key. When a subclass of that +class has its identity table on the same table and the binding of the class has a row filter, the +filter may leave out records of the subclass, and the part is `notEnforceable`. + +**`datatype` is settled by the column's type.** It supports `xsd:string`, `xsd:boolean`, +`xsd:integer`, `xsd:decimal`, `xsd:double`, `xsd:float`, `xsd:date`, `xsd:time` and +`xsd:dateTime`. A fixed-point column with a scale of 0 holds integers, and a whole-number column +holds decimals. When every value of the column's type is a value of the datatype the part is +`heldByMapping`. Otherwise no query can tell, and the part is `notEnforceable`. + +**What is not enforceable, and why.** + +| Reason | When | +|---|---| +| `noIdentityTable` | The class has no identity table, so it has no records. | +| `severalTables` | `minCount` above 0 or `maxCount` on a property that the class binds in several places. The count would run over all of them at once. | +| `boundOnInverse` | The class does not bind the relation, and another class binds its inverse. | +| `noJoin`, `joinNotConfirmed` | The relation has no join, or one that is only inferred. Only a confirmed join is read. | +| `notARelation`, `notADataProperty` | `class` on a data property, or `datatype`, `range`, `in` or `pattern` on a relation. | +| `targetClassNotOnJoin` | The class of the constraint has no identity table where the join arrives. | +| `subclassOnJoinTable` | A subclass shares the filtered identity table of the class of the constraint. | +| `valuesAreRecords` | An `in` list names a record by IRI. | +| `valueDoesNotFitColumn` | A literal does not parse as a value of the column's type, or carries a language tag. A stored row filter that no longer parses gives the same reason. | +| `tooManyValues` | An `in` list of more than 1,000 values. | +| `columnTypeNotSupported` | The column's type has no values the part can be compared with. | +| `datatypeNotSupported`, `datatypeMismatch` | The datatype is not one of the nine, or the column's type can hold a value that the datatype does not have. | +| `patternNotPortable`, `tableNotSimple` | The pattern is outside the common core, or its column is not on a simple table. | +| `columnMissing` | A bound column, a key column or a join column left the table. | +| `otherDatabase` | A table of the check is in another database than the identity table. | +| `engineNotSupported` | A generated query on a service type that no statement is written for, a pattern on the `TSQL` family, or a query on the `CLICKHOUSE` family that keeps the records with no matching row, because an unmatched row there holds a default value and no null. | + +A literal is parsed by the type of the column it is compared with, and the datatype of the literal +is not read. A property bound in several tables is checked once for each table for `in`, `range`, +`class`, `datatype` and `pattern`. When the tables do not agree, each answer is its own part entry. +A column test needs no statement, so it is offered on a service type that no statement is written +for. + +**A check has an identity that survives an edit of its bound.** It is the lowercase hex SHA-256 of +the shape id, the constraint id, the part, the class id, the table id and the column path, joined +by a separator that none of them can hold. A check also lists the class, the table and the binding +revision of every binding it read. A check belongs to the table whose binding holds the property, +the link table included. + +**What a caller may not view is masked after the compile.** The compile is the same for every +caller. A constraint whose answer rests on a table the caller may not view, which is the identity +table, a table that binds the property or the table a join arrives at, has every part `hidden`, +with no check, no reason and no column. No table name appears anywhere else in the response. + +## Consequences + +A person is shown a test only when its result means what the shape says. Everything else comes with +a reason that names what to change: declare the key, confirm the join, pick an identity table. + +A catalog whose declared primary key is wrong gives a column test that is not exact, because the +declaration is taken at its word. A generated query does not depend on it. + +A pattern outside the common core, a pattern on a table that is not simple, and a count over a +property bound in several places have no check. Each needs its own exact form before it can be +offered, and a new record when it gets one. + +The answer is computed for each request from the shapes and the bindings as they are. Nothing is +stored, so a check has no state here. Creating tests from this answer is a separate step that keys +on the identity of a check and compares the binding revisions it read. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBuiltinTest.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBuiltinTest.java new file mode 100644 index 000000000000..bd20ebf61ec1 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBuiltinTest.java @@ -0,0 +1,99 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.List; +import java.util.Set; +import org.openmetadata.common.utils.CommonUtil; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.tests.TestDefinition; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test; +import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * The column test definitions the catalog ships with that a shape check can use. Each reads the + * column data types its definition supports from the seed file the catalog loads the definition + * from, because creating a test on any other type is refused. + */ +enum OntologyBuiltinTest { + NOT_NULL("columnValuesToBeNotNull"), + IN_SET("columnValuesToBeInSet"), + BETWEEN("columnValuesToBeBetween"), + MATCH_REGEX("columnValuesToMatchRegex"); + + /** The table test that runs a statement written for the check. */ + static final String CUSTOM_SQL = "tableCustomSQLQuery"; + + private static final String SEED_FILE = "json/data/tests/%s.json"; + private static final String COLUMNS_FIELD = "columns"; + private final String definition; + private final Set supported; + + OntologyBuiltinTest(final String definition) { + this.definition = definition; + this.supported = Set.copyOf(listOrEmpty(seed(definition).getSupportedDataTypes())); + } + + private static TestDefinition seed(final String definition) { + try { + return JsonUtils.readValue( + CommonUtil.getResourceAsStream( + OntologyBuiltinTest.class.getClassLoader(), String.format(SEED_FILE, definition)), + TestDefinition.class); + } catch (final IOException unread) { + throw new UncheckedIOException(unread); + } + } + + /** + * True when the definition takes a test on the column: it is a column of the table itself and + * not a field inside one, and the definition supports its data type. + */ + boolean takes(final List path, final Column column) { + return path.size() == 1 && supported.contains(column.getDataType()); + } + + /** The test on one column of the table, with its parameters. */ + Test.Builtin on( + final Table table, final String column, final List parameters) { + final String link = + new EntityLink( + Entity.TABLE, + table.getFullyQualifiedName(), + COLUMNS_FIELD, + FullyQualifiedName.quoteName(column), + null) + .getLinkString(); + return new Test.Builtin(definition, link, parameters); + } + + /** The link of a test on the table as a whole. */ + static String tableLink(final Table table) { + return new EntityLink(Entity.TABLE, table.getFullyQualifiedName()).getLinkString(); + } + + static TestCaseParameterValue parameter(final String name, final String value) { + return new TestCaseParameterValue().withName(name).withValue(value); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java new file mode 100644 index 000000000000..7e52ad946dcb --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java @@ -0,0 +1,223 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; +import static org.openmetadata.service.ontology.OntologySettled.of; +import static org.openmetadata.service.ontology.OntologySettled.refused; +import static org.openmetadata.service.ontology.OntologySettled.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.IntStream; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyCheckProbe.Reach; +import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedRowFilter; + +/** + * What every rule of the shape check compile asks of a mapping before it answers: each is a value, + * or the reason the mapping gives no exact test. A binding is read as it is stored, and the table + * it names may have changed since, so a column that left or a filter that no longer parses is an + * answer here and never an error. + */ +final class OntologyCheckGates { + private OntologyCheckGates() {} + + /** + * The records of a class: its identity table as a statement reads it. + * + * @param simple true when every row of the table is one record and every record is one row + */ + record Records(ReadTable identity, boolean simple) {} + + /** + * How a statement gets from the records of a class to the table that holds a property. + * + * @param holder the contributing table, or null when the identity table holds the property + */ + record Route(ReadTable identity, ReadTable holder, List keyPairs) {} + + static boolean isRelation(final OntologyProperty property) { + return property.getKind() == OntologyPropertyKind.OBJECT; + } + + static OntologySettled records(final Subject subject) { + return subject + .identity() + .map( + identity -> + readTable(identity) + .map(read -> new Records(read, OntologyDeclaredKeys.isSimple(identity)))) + .orElseGet(() -> refused(OntologyShapeCheckReason.NO_IDENTITY_TABLE)); + } + + /** The table, when its subject key still resolves and its row filter still parses. */ + static OntologySettled readTable(final MappedTable table) { + final List> key = table.keyPaths(); + if (key.isEmpty() || !key.stream().allMatch(table::holds)) { + return refused(OntologyShapeCheckReason.COLUMN_MISSING); + } + return filter(table).map(filter -> new ReadTable(table, filter.orElse(null))); + } + + private static OntologySettled> filter(final MappedTable table) { + final OntologyRowFilter stored = table.row().rowFilter(); + if (stored == null) { + return of(Optional.empty()); + } + if (!table.holds(stored.getColumn())) { + return refused(OntologyShapeCheckReason.COLUMN_MISSING); + } + try { + return of(Optional.of(OntologyTableBindingChecks.typedRowFilter(table.table(), stored))); + } catch (final BadRequestException unparsed) { + // The filter parsed when it was saved, and the column has another data type now. + return refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN); + } + } + + /** The column a data property is bound to at a place. */ + static OntologySettled column(final Place place) { + final Column column = + OntologyBindingRules.resolveColumn(place.holder().table(), place.binding().getColumnPath()); + return column == null ? refused(OntologyShapeCheckReason.COLUMN_MISSING) : of(column); + } + + /** + * The columns whose values are the values of the property at a place: the bound column of a + * data property, and the columns of the confirmed join of a relation. + */ + static OntologySettled>> values( + final OntologyProperty property, final Place place) { + if (!isRelation(property)) { + return held(place.holder(), List.of(place.binding().getColumnPath())); + } + return join(place) + .then( + join -> + held( + place.holder(), + join.getOn().stream().map(OntologyJoinColumnPair::getChild).toList())); + } + + /** The join of a relation at a place, when a person has confirmed it. */ + static OntologySettled join(final Place place) { + final OntologyColumnJoin join = place.binding().getJoin(); + if (join == null || nullOrEmpty(join.getOn())) { + return refused(OntologyShapeCheckReason.NO_JOIN); + } + return when( + join.getStatus() == OntologyJoinStatus.CONFIRMED, + join, + OntologyShapeCheckReason.JOIN_NOT_CONFIRMED); + } + + static OntologySettled>> held( + final MappedTable table, final List> paths) { + return when( + paths.stream().allMatch(table::holds), paths, OntologyShapeCheckReason.COLUMN_MISSING); + } + + /** The way from the records to the table of a place, which is no way at all on its own table. */ + static OntologySettled route(final Records records, final Place place) { + final ReadTable identity = records.identity(); + if (place.onIdentity()) { + return of(new Route(identity, null, List.of())); + } + return joined(identity, place.holder()) + .then( + holder -> + keyPairs(identity.table(), holder.table()) + .map(pairs -> new Route(identity, holder, pairs))); + } + + /** Another table as a statement that starts from the identity table joins it. */ + static OntologySettled joined(final ReadTable identity, final MappedTable other) { + if (!identity.table().database().equals(other.database())) { + return refused(OntologyShapeCheckReason.OTHER_DATABASE); + } + return readTable(other); + } + + /** A contributing table pairs its subject key with the key of the identity table by position. */ + private static OntologySettled> keyPairs( + final MappedTable identity, final MappedTable holder) { + final List> key = identity.keyPaths(); + final List> paired = holder.keyPaths(); + return when( + key.size() == paired.size(), + IntStream.range(0, Math.min(key.size(), paired.size())) + .mapToObj(part -> new JoinPair(key.get(part), paired.get(part))) + .toList(), + OntologyShapeCheckReason.COLUMN_MISSING); + } + + /** The route on an engine that statements are written for. */ + static OntologySettled reach(final Route route) { + return SqlEngineFamily.forServiceType(route.identity().table().serviceType()) + .map(family -> of(new Reach(family, route.identity(), route.holder(), route.keyPairs()))) + .orElseGet(() -> refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED)); + } + + /** + * A statement that keeps the rows with no match on the other side of a join. ClickHouse fills + * the columns of a missing row with the default of their type unless a setting says otherwise, + * so a test for null finds no missing row there. + */ + static OntologySettled withOuterJoin(final Reach reach) { + return when( + reach.family() != SqlEngineFamily.CLICKHOUSE, + reach, + OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + } + + /** One test on the table of a place, with every binding row it was built from. */ + static OntologyPartOutcome check( + final Place place, + final List> columns, + final Test test, + final List read) { + final List rows = new ArrayList<>(read.stream().map(MappedTable::row).toList()); + if (!rows.contains(place.holder().row())) { + rows.add(place.holder().row()); + } + return new Check(List.of(new TableCheck(place, columns, test, List.copyOf(rows)))); + } + + /** The tables a generated test reads to reach its values. */ + static List read(final Reach reach) { + return reach.joinsHolder() + ? List.of(reach.identity().table(), reach.holder().table()) + : List.of(reach.identity().table()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java new file mode 100644 index 000000000000..ac2219e1ed91 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java @@ -0,0 +1,80 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.util.List; +import java.util.Optional; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedRowFilter; +import org.openmetadata.service.ontology.sql.TypedValue; + +/** + * Which records of a class a generated test counts. The compile makes one only from a mapping it + * has checked: every column a probe names is in its table, every filter and value is parsed, and + * every table is in one database on an engine that statements are written for. {@link + * OntologyShapeCheckSql} writes the statement and can refuse nothing. + */ +sealed interface OntologyCheckProbe { + Reach reach(); + + /** + * A table as a statement reads it. + * + * @param filter the row filter of its binding with its values parsed, or null when it has none + */ + record ReadTable(MappedTable table, TypedRowFilter filter) {} + + /** + * How a statement gets from the records of the class to the values of a property. + * + * @param holder the contributing table that holds the property, or null when the identity table + * holds it + * @param keyPairs each column of the subject key of the identity table with the column of the + * holder's subject key that it equals, or no pair when the identity table holds the property + */ + record Reach( + SqlEngineFamily family, ReadTable identity, ReadTable holder, List keyPairs) { + boolean joinsHolder() { + return holder != null; + } + } + + /** Records with fewer than {@code count} distinct values in {@code columns}. */ + record FewerValues(Reach reach, List> columns, int count) + implements OntologyCheckProbe {} + + /** Records with more than {@code count} distinct values in {@code columns}. */ + record MoreValues(Reach reach, List> columns, int count) + implements OntologyCheckProbe {} + + /** Records with a value in {@code column} that is none of {@code allowed}. */ + record OutsideList(Reach reach, List column, List allowed) + implements OntologyCheckProbe {} + + /** Records with a value in {@code column} below {@code min} or above {@code max}. */ + record OutsideRange( + Reach reach, List column, Optional min, Optional max) + implements OntologyCheckProbe {} + + /** + * Records with a value of a relation that is no record of the class the relation must reach. + * + * @param on each column of the join in the table that holds the relation, with the column of + * {@code target} that it equals + * @param target the identity table of the class the values must be records of + */ + record NoRecord(Reach reach, List on, ReadTable target) implements OntologyCheckProbe {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java new file mode 100644 index 000000000000..3254c61ebb7e --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java @@ -0,0 +1,104 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; + +/** + * What the keys that the catalog declares on a table say about the records a binding makes of its + * rows. A declaration is taken at its word: whether the engine checks the key is not asked + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A primary key is declared by a + * table constraint, or by the column constraint on the one column that carries it. + */ +final class OntologyDeclaredKeys { + private OntologyDeclaredKeys() {} + + /** + * True when every row of the table is one record of the class and every record is one row: the + * table is the identity table, its binding has no row filter, and the columns of its declared + * primary key are exactly its subject key. A test that reads the rows of such a table reads the + * records. + */ + static boolean isSimple(final MappedTable table) { + final List> key = table.keyPaths(); + return table.row().role() == OntologyBindingRole.IDENTITY + && table.row().rowFilter() == null + && !key.isEmpty() + && key.stream().allMatch(path -> path.size() == 1) + && primaryKeys(table.table()).contains(topLevel(key)); + } + + /** + * True when the table holds at most one row for each value of its subject key, because a + * declared primary or unique key lies inside the subject key columns. + */ + static boolean oneRowPerKey(final MappedTable table) { + final Set key = topLevel(table.keyPaths()); + final List> declared = new ArrayList<>(primaryKeys(table.table())); + declared.addAll(uniqueKeys(table.table())); + return declared.stream().anyMatch(columns -> !columns.isEmpty() && key.containsAll(columns)); + } + + /** The names of the key's columns that sit at the top of the table, which constraints name. */ + private static Set topLevel(final List> key) { + return key.stream() + .filter(path -> path.size() == 1) + .map(List::getFirst) + .collect(Collectors.toSet()); + } + + private static List> primaryKeys(final Table table) { + final List> keys = new ArrayList<>(tableKeys(table, ConstraintType.PRIMARY_KEY)); + final Set flagged = flagged(table, ColumnConstraint.PRIMARY_KEY); + // Several columns that each carry the constraint are a key of unknown shape, so only one + // counts. + if (flagged.size() == 1) { + keys.add(flagged); + } + return keys; + } + + private static List> uniqueKeys(final Table table) { + final List> keys = new ArrayList<>(tableKeys(table, ConstraintType.UNIQUE)); + flagged(table, ColumnConstraint.UNIQUE).forEach(column -> keys.add(Set.of(column))); + return keys; + } + + private static List> tableKeys(final Table table, final ConstraintType type) { + return listOrEmpty(table.getTableConstraints()).stream() + .filter(constraint -> constraint.getConstraintType() == type) + .map(TableConstraint::getColumns) + .map(columns -> Set.copyOf(listOrEmpty(columns))) + .toList(); + } + + private static Set flagged(final Table table, final ColumnConstraint constraint) { + return listOrEmpty(table.getColumns()).stream() + .filter(column -> column.getConstraint() == constraint) + .map(Column::getName) + .collect(Collectors.toSet()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java new file mode 100644 index 000000000000..9330b74fa4a1 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java @@ -0,0 +1,57 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.util.List; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; + +/** + * How one part of a shape constraint is checked on the tables of a class + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). Only a check holds tests and only + * a refusal holds a reason. + */ +sealed interface OntologyPartOutcome { + /** Tests that find a violation exactly when a record breaks the part, one for each table. */ + record Check(List checks) implements OntologyPartOutcome {} + + /** The table bindings already hold the part for every record, so nothing is tested. */ + record HeldByMapping() implements OntologyPartOutcome {} + + /** The class binds the property in no column, or the version read has no such property. */ + record NotMapped() implements OntologyPartOutcome {} + + /** No test finds exactly the records that break the part. */ + record NotEnforceable(OntologyShapeCheckReason reason) implements OntologyPartOutcome {} + + /** + * One test on the table that holds the property. + * + * @param columns the columns of that table whose values the test reads + * @param read every binding row the test was built from + */ + record TableCheck(Place place, List> columns, Test test, List read) {} + + /** What runs: a test definition the catalog ships with, or a statement written for the part. */ + sealed interface Test { + /** A column test, as a request to create a test case takes it. */ + record Builtin(String definition, String entityLink, List parameters) + implements Test {} + + /** A statement that counts the records in violation. */ + record Generated(OntologyCheckProbe probe) implements Test {} + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java new file mode 100644 index 000000000000..a5b36e88b3f9 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java @@ -0,0 +1,183 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.util.regex.Pattern; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * The regular expressions that every engine a regex test runs on reads alike + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). Engines differ in what they add to + * the common core, so a pattern is taken only when it stays inside it: + * + *

      + *
    • it starts with {@code ^} and ends with {@code $}, and holds no other anchor; + *
    • a character is an ASCII letter, a digit, a space, {@code .}, or a backslash before an + * ASCII punctuation character; + *
    • a character class holds letters, digits, spaces and ranges of them, and may be negated; + *
    • a group has no prefix such as {@code (?:}, and holds every alternation; + *
    • a quantifier is {@code ?}, {@code *}, {@code +}, {@code {n}}, {@code {n,}} or {@code + * {n,m}}, and nothing follows it that would make it lazy or possessive. + *
    + * + * An alternation outside a group is refused because {@code ^a|b$} anchors one branch each on an + * engine that searches and both on an engine that matches the whole value. + */ +final class OntologyPortablePattern { + private static final Pattern LETTER = Pattern.compile("[A-Za-z]"); + private static final Pattern COUNT = Pattern.compile("0|[1-9][0-9]{0,2}"); + private static final String QUANTIFIERS = "?*+{"; + private static final int MOST_REPEATS = 255; + private static final char LAST_ASCII = '~'; + private final String body; + private int at; + + private OntologyPortablePattern(final String body) { + this.body = body; + } + + /** True when the engines of {@code family} match the pattern as every other family does. */ + static boolean reads(final String pattern, final SqlEngineFamily family) { + // REGEXP ignores the case of a letter under most collations of the MySQL family. + final boolean foldsCase = family == SqlEngineFamily.MYSQL && LETTER.matcher(pattern).find(); + return !foldsCase && isPortable(pattern); + } + + static boolean isPortable(final String pattern) { + final int end = pattern.length() - 1; + if (end < 1 || pattern.charAt(0) != '^' || pattern.charAt(end) != '$') { + return false; + } + final OntologyPortablePattern parser = new OntologyPortablePattern(pattern.substring(1, end)); + return parser.sequence() && parser.at == parser.body.length(); + } + + private boolean more() { + return at < body.length(); + } + + /** Atoms, each with at most one quantifier, up to the end of an alternative. */ + private boolean sequence() { + while (more() && body.charAt(at) != '|' && body.charAt(at) != ')') { + if (!atom() || !quantifier()) { + return false; + } + } + return true; + } + + private boolean atom() { + final char next = body.charAt(at); + if (isPlain(next) || next == '.') { + at++; + return true; + } + return switch (next) { + case '\\' -> escaped(); + case '[' -> characterClass(); + case '(' -> group(); + default -> false; + }; + } + + private static boolean isPlain(final char character) { + return character == ' ' || character <= LAST_ASCII && Character.isLetterOrDigit(character); + } + + /** A backslash before a punctuation character, which every engine reads as that character. */ + private boolean escaped() { + final boolean punctuation = + at + 1 < body.length() + && body.charAt(at + 1) > ' ' + && body.charAt(at + 1) <= LAST_ASCII + && !Character.isLetterOrDigit(body.charAt(at + 1)); + at += 2; + return punctuation; + } + + private boolean characterClass() { + at++; + at += more() && body.charAt(at) == '^' ? 1 : 0; + final int first = at; + while (more() && body.charAt(at) != ']') { + if (!member()) { + return false; + } + } + return at > first && more() && body.charAt(at++) == ']'; + } + + /** One plain character of a class, or a range of two digits or of two letters of one case. */ + private boolean member() { + final char low = body.charAt(at++); + if (!isPlain(low)) { + return false; + } + if (!more() || body.charAt(at) != '-') { + return true; + } + final char high = at + 1 < body.length() ? body.charAt(at + 1) : ' '; + at += 2; + return low <= high && Character.getType(low) == Character.getType(high) && low != ' '; + } + + private boolean group() { + at++; + if (more() && body.charAt(at) == '?') { + return false; + } + boolean another = true; + while (another) { + final int start = at; + if (!sequence() || at == start) { + return false; + } + another = more() && body.charAt(at) == '|'; + at += another ? 1 : 0; + } + return more() && body.charAt(at++) == ')'; + } + + /** At most one quantifier, with nothing after it that changes how it repeats. */ + private boolean quantifier() { + if (!more() || QUANTIFIERS.indexOf(body.charAt(at)) < 0) { + return true; + } + if (body.charAt(at) != '{') { + at++; + } else if (!counted()) { + return false; + } + return !more() || QUANTIFIERS.indexOf(body.charAt(at)) < 0; + } + + private boolean counted() { + final int close = body.indexOf('}', at); + if (close < 0) { + return false; + } + final String[] bounds = body.substring(at + 1, close).split(",", -1); + at = close + 1; + if (bounds.length > 2 || !isCount(bounds[0])) { + return false; + } + return bounds.length == 1 + || bounds[1].isEmpty() + || isCount(bounds[1]) && Integer.parseInt(bounds[0]) <= Integer.parseInt(bounds[1]); + } + + private static boolean isCount(final String digits) { + return COUNT.matcher(digits).matches() && Integer.parseInt(digits) <= MOST_REPEATS; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySettled.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySettled.java new file mode 100644 index 000000000000..2f81b3d2f6b0 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySettled.java @@ -0,0 +1,67 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; + +/** + * What a rule of the shape check compile settles: a value, or the reason a part of a constraint + * has no exact test. A rule that needs several facts asks for them in order with {@link #then}, + * and the first refusal is the answer. + */ +sealed interface OntologySettled { + record Value(T value) implements OntologySettled {} + + record Refused(OntologyShapeCheckReason reason) implements OntologySettled {} + + static OntologySettled of(final T value) { + return new Value<>(value); + } + + static OntologySettled refused(final OntologyShapeCheckReason reason) { + return new Refused<>(reason); + } + + /** The value when {@code holds}, and the refusal otherwise. */ + static OntologySettled when( + final boolean holds, final T value, final OntologyShapeCheckReason otherwise) { + return holds ? of(value) : refused(otherwise); + } + + /** Every value in order, or the first refusal. */ + static OntologySettled> all(final List> settled) { + final List values = new ArrayList<>(); + for (final OntologySettled one : settled) { + if (one instanceof Refused refused) { + return refused(refused.reason()); + } + values.add(((Value) one).value()); + } + return of(List.copyOf(values)); + } + + default OntologySettled then(final Function> next) { + return switch (this) { + case Value found -> next.apply(found.value()); + case Refused refused -> refused(refused.reason()); + }; + } + + default OntologySettled map(final Function change) { + return then(value -> of(change.apply(value))); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java new file mode 100644 index 000000000000..9ac58320773a --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java @@ -0,0 +1,170 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.service.ontology.OntologySettled.of; +import static org.openmetadata.service.ontology.OntologySettled.refused; +import static org.openmetadata.service.ontology.OntologySettled.when; + +import java.util.ArrayList; +import java.util.List; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.service.ontology.OntologyCheckGates.Records; +import org.openmetadata.service.ontology.OntologyCheckGates.Route; +import org.openmetadata.service.ontology.OntologyCheckProbe.FewerValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.MoreValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.NoRecord; +import org.openmetadata.service.ontology.OntologyCheckProbe.Reach; +import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Target; + +/** + * How the parts of a constraint that count the values of a property, or ask what a relation + * reaches, are checked at one place: {@code minCount}, {@code maxCount} and {@code class} + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A data property has a value on a + * record in each row where its column is not null, and a relation where every column of its + * confirmed join is not null. Two rows that hold the same value hold one value. + */ +final class OntologyShapeCardinalityRules { + private OntologyShapeCardinalityRules() {} + + /** + * The values of a property at one place, with the way to them from the records. + * + * @param columns the columns that hold one value together + */ + record Values(Records records, Place place, List> columns, Route route) {} + + static OntologySettled values( + final Records records, final OntologyProperty property, final Place place) { + return OntologyCheckGates.values(property, place) + .then( + columns -> + OntologyCheckGates.route(records, place) + .map(route -> new Values(records, place, columns, route))); + } + + /** Every record has at least {@code count} values, for a count above zero. */ + static OntologySettled atLeast(final int count, final Values values) { + if (count == 1 && isKeyOfRecord(values)) { + return of(new HeldByMapping()); + } + if (count == 1 && takesNotNullTest(values)) { + return of(notNull(values)); + } + return OntologyCheckGates.reach(values.route()) + .then(reach -> reach.joinsHolder() ? OntologyCheckGates.withOuterJoin(reach) : of(reach)) + .map(reach -> generated(values, new FewerValues(reach, values.columns(), count))); + } + + /** Every record has at most {@code count} values. */ + static OntologySettled atMost(final int count, final Values values) { + if (count >= 1 && OntologyDeclaredKeys.oneRowPerKey(values.place().holder())) { + return of(new HeldByMapping()); + } + return OntologyCheckGates.reach(values.route()) + .map(reach -> generated(values, new MoreValues(reach, values.columns(), count))); + } + + /** A record is a row with no null in its key, so a value made of key columns is never absent. */ + private static boolean isKeyOfRecord(final Values values) { + return values.place().onIdentity() + && values.records().identity().table().keyPaths().containsAll(values.columns()); + } + + private static boolean takesNotNullTest(final Values values) { + final Place place = values.place(); + final Column column = + OntologyBindingRules.resolveColumn(place.holder().table(), values.columns().getFirst()); + return values.columns().size() == 1 + && values.records().simple() + && place.onIdentity() + && OntologyBuiltinTest.NOT_NULL.takes(values.columns().getFirst(), column); + } + + private static OntologyPartOutcome notNull(final Values values) { + final MappedTable table = values.place().holder(); + final Test test = + OntologyBuiltinTest.NOT_NULL.on( + table.table(), values.columns().getFirst().getFirst(), List.of()); + return OntologyCheckGates.check(values.place(), values.columns(), test, List.of(table)); + } + + private static OntologyPartOutcome generated( + final Values values, final OntologyCheckProbe probe) { + return OntologyCheckGates.check( + values.place(), + values.columns(), + new Test.Generated(probe), + OntologyCheckGates.read(probe.reach())); + } + + /** + * Every value of a relation at one place is a record of the class the part names. The join must + * arrive at the identity table of that class, and a row there is a record when it passes the + * filter of that binding and has no null in its key. + * + * @param target the class the part names, or null when the version read has no such class + */ + static OntologySettled reaches(final Values values, final Target target) { + return OntologyCheckGates.join(values.place()) + .then(join -> arrival(values, join, target)) + .then( + probe -> + when( + !(target.subclassSharesTable() && probe.target().filter() != null), + probe, + OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE)) + .map(probe -> generated(values, probe, target.identity())); + } + + private static OntologySettled arrival( + final Values values, final OntologyColumnJoin join, final Target target) { + final boolean arrives = + target != null + && target.identity() != null + && target.identity().row().assetId().equals(join.getTargetAssetId()); + if (!arrives) { + return refused(OntologyShapeCheckReason.TARGET_CLASS_NOT_ON_JOIN); + } + final List on = + join.getOn().stream().map(pair -> new JoinPair(pair.getChild(), pair.getParent())).toList(); + return OntologyCheckGates.held(target.identity(), on.stream().map(JoinPair::joined).toList()) + .then(parents -> OntologyCheckGates.joined(values.route().identity(), target.identity())) + .then(read -> antiJoin(values, on, read)); + } + + private static OntologySettled antiJoin( + final Values values, final List on, final ReadTable target) { + return OntologyCheckGates.reach(values.route()) + .then(OntologyCheckGates::withOuterJoin) + .map((final Reach reach) -> new NoRecord(reach, on, target)); + } + + private static OntologyPartOutcome generated( + final Values values, final NoRecord probe, final MappedTable target) { + final List read = new ArrayList<>(OntologyCheckGates.read(probe.reach())); + read.add(target); + return OntologyCheckGates.check( + values.place(), values.columns(), new Test.Generated(probe), read); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java new file mode 100644 index 000000000000..1a0e25f30c0b --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java @@ -0,0 +1,291 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyCheckGates.isRelation; +import static org.openmetadata.service.ontology.OntologySettled.refused; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.service.ontology.OntologyCheckGates.Records; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotMapped; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; + +/** + * Compiles the shapes that target a class into data quality checks on the tables the class binds + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A constraint is answered part by + * part. A part gets a test only when the test finds a violation exactly when a record of the + * class breaks it. Otherwise the answer says that the mapping already holds the part, that the + * property is not mapped, or why no exact test exists. + * + *

    Nothing here reads a database or a policy. The facts are the same for every caller, so the + * answer is too, and what a caller may not view is masked afterwards. + */ +final class OntologyShapeCheckCompiler { + static final int MOST_LISTED_VALUES = 1000; + + /** What each part of a constraint states, in the order the parts are answered. */ + private static final Map> STATED = + stated(); + + private final OntologyShapeCheckFacts facts; + private final OntologySettled records; + + private OntologyShapeCheckCompiler(final OntologyShapeCheckFacts facts) { + this.facts = facts; + this.records = OntologyCheckGates.records(facts.subject()); + } + + record CompiledShape(OntologyShape shape, List constraints) {} + + /** + * One constraint with the answer for each part it states. + * + * @param rests the ids of the tables the answer rests on: the identity table of the class, each + * table that holds the property, and each table a join of the property arrives at + * @param parts one entry for each part, or one for each different answer when the tables that + * hold the property do not agree + */ + record CompiledConstraint( + OntologyShapeConstraint constraint, Set rests, List parts) {} + + record CompiledPart(OntologyShapePart part, OntologyPartOutcome outcome) {} + + /** One constraint with its property as the version declares it and the records of the class. */ + private record Asked( + OntologyShapeConstraint constraint, OntologyProperty property, Records records) {} + + static List compile( + final OntologyShapeCheckFacts facts, final List shapes) { + final OntologyShapeCheckCompiler compiler = new OntologyShapeCheckCompiler(facts); + return shapes.stream() + .map( + shape -> + new CompiledShape( + shape, + listOrEmpty(shape.getConstraints()).stream() + .map(compiler::constraint) + .toList())) + .toList(); + } + + private static Map> stated() { + final Map> stated = + new EnumMap<>(OntologyShapePart.class); + stated.put(OntologyShapePart.MIN_COUNT, OntologyShapeConstraint::getMinCount); + stated.put(OntologyShapePart.MAX_COUNT, OntologyShapeConstraint::getMaxCount); + stated.put(OntologyShapePart.CLASS, OntologyShapeConstraint::getClassIri); + stated.put(OntologyShapePart.DATATYPE, OntologyShapeConstraint::getDatatypeIri); + stated.put( + OntologyShapePart.RANGE, + constraint -> + constraint.getMinInclusive() == null + ? constraint.getMaxInclusive() + : constraint.getMinInclusive()); + stated.put(OntologyShapePart.IN, OntologyShapeConstraint::getIn); + stated.put(OntologyShapePart.PATTERN, OntologyShapeConstraint::getPattern); + return stated; + } + + private CompiledConstraint constraint(final OntologyShapeConstraint constraint) { + final OntologyProperty property = facts.properties().get(constraint.getPath()); + final List places = + property == null ? List.of() : facts.subject().places(property.getId()); + final List parts = new ArrayList<>(); + STATED.forEach( + (part, value) -> { + if (value.apply(constraint) != null) { + answers(part, constraint, property, places) + .forEach(outcome -> parts.add(new CompiledPart(part, outcome))); + } + }); + return new CompiledConstraint(constraint, rests(places), List.copyOf(parts)); + } + + private Set rests(final List places) { + final Set rests = new LinkedHashSet<>(); + facts.subject().identity().ifPresent(identity -> rests.add(identity.row().assetId())); + for (final Place place : places) { + rests.add(place.holder().row().assetId()); + if (place.binding().getJoin() != null + && place.binding().getJoin().getTargetAssetId() != null) { + rests.add(place.binding().getJoin().getTargetAssetId()); + } + } + return rests; + } + + private List answers( + final OntologyShapePart part, + final OntologyShapeConstraint constraint, + final OntologyProperty property, + final List places) { + if (property == null) { + return List.of(new NotMapped()); + } + if (places.isEmpty()) { + return List.of(unmapped(property)); + } + if (part == OntologyShapePart.MIN_COUNT && constraint.getMinCount() == 0) { + return List.of(new HeldByMapping()); + } + return switch (records) { + case OntologySettled.Refused none -> List.of(new NotEnforceable(none.reason())); + case OntologySettled.Value found -> merged( + settled(part, new Asked(constraint, property, found.value()), places)); + }; + } + + /** + * The answer for a property that no identity or contributing table of the class holds. A table + * with no role holds no value of a record, so a class that binds the property only there has + * the property and no records to check it on. + */ + private OntologyPartOutcome unmapped(final OntologyProperty property) { + final Subject subject = facts.subject(); + if (subject.binds(property.getId())) { + return subject.identity().isEmpty() + ? new NotEnforceable(OntologyShapeCheckReason.NO_IDENTITY_TABLE) + : new NotMapped(); + } + return isRelation(property) && facts.boundOnInverse().contains(property.getId()) + ? new NotEnforceable(OntologyShapeCheckReason.BOUND_ON_INVERSE) + : new NotMapped(); + } + + private List> settled( + final OntologyShapePart part, final Asked asked, final List places) { + final OntologyShapeConstraint constraint = asked.constraint(); + final Records found = asked.records(); + return switch (part) { + case MIN_COUNT, MAX_COUNT -> List.of(counted(part, asked, places)); + case CLASS -> eachRelation(asked, places); + case DATATYPE -> eachData( + asked, + places, + place -> OntologyShapeValueRules.datatype(constraint.getDatatypeIri(), place)); + case RANGE -> eachData( + asked, places, place -> OntologyShapeValueRules.range(constraint, found, place)); + case IN -> listed(asked, places); + case PATTERN -> eachData( + asked, + places, + place -> OntologyShapeValueRules.pattern(constraint.getPattern(), found, place)); + }; + } + + /** A count over several columns is a count over all of them at once, which no test makes. */ + private static OntologySettled counted( + final OntologyShapePart part, final Asked asked, final List places) { + if (places.size() > 1) { + return refused(OntologyShapeCheckReason.SEVERAL_TABLES); + } + final OntologyShapeConstraint constraint = asked.constraint(); + return OntologyShapeCardinalityRules.values( + asked.records(), asked.property(), places.getFirst()) + .then( + values -> + part == OntologyShapePart.MIN_COUNT + ? OntologyShapeCardinalityRules.atLeast(constraint.getMinCount(), values) + : OntologyShapeCardinalityRules.atMost(constraint.getMaxCount(), values)); + } + + private List> eachRelation( + final Asked asked, final List places) { + if (!isRelation(asked.property())) { + return List.of(refused(OntologyShapeCheckReason.NOT_A_RELATION)); + } + return places.stream() + .map( + place -> + OntologyShapeCardinalityRules.values(asked.records(), asked.property(), place) + .then( + values -> + OntologyShapeCardinalityRules.reaches( + values, facts.targets().get(asked.constraint().getClassIri())))) + .toList(); + } + + private static List> eachData( + final Asked asked, + final List places, + final Function> rule) { + return isRelation(asked.property()) + ? List.of(refused(OntologyShapeCheckReason.NOT_A_DATA_PROPERTY)) + : places.stream().map(rule).toList(); + } + + /** A list that names a record compares records, and a column holds no record to compare. */ + private static List> listed( + final Asked asked, final List places) { + final List list = listOrEmpty(asked.constraint().getIn()); + if (list.stream().anyMatch(item -> item.getIri() != null)) { + return List.of(refused(OntologyShapeCheckReason.VALUES_ARE_RECORDS)); + } + if (list.size() > MOST_LISTED_VALUES) { + return List.of(refused(OntologyShapeCheckReason.TOO_MANY_VALUES)); + } + return eachData( + asked, places, place -> OntologyShapeValueRules.in(list, asked.records(), place)); + } + + /** + * One entry when every table gives the same answer: the tests of all of them together, or the + * one answer they share. Otherwise the tests first, then each other answer once. + */ + private static List merged( + final List> settled) { + final List outcomes = + settled.stream().map(OntologyShapeCheckCompiler::outcome).toList(); + final List checks = + outcomes.stream() + .filter(Check.class::isInstance) + .flatMap(outcome -> ((Check) outcome).checks().stream()) + .toList(); + final List merged = new ArrayList<>(); + if (!checks.isEmpty()) { + merged.add(new Check(checks)); + } + outcomes.stream() + .filter(outcome -> !(outcome instanceof Check)) + .distinct() + .forEach(merged::add); + return List.copyOf(merged); + } + + private static OntologyPartOutcome outcome(final OntologySettled settled) { + return switch (settled) { + case OntologySettled.Value found -> found.value(); + case OntologySettled.Refused none -> new NotEnforceable(none.reason()); + }; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java new file mode 100644 index 000000000000..2967ab421f04 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java @@ -0,0 +1,101 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Stream; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; + +/** + * Everything the shape check compile reads, as plain values + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). Every table is here whether or not + * the caller may view it, because the compile is the same for every caller and what a caller may + * not view is masked after it. + * + * @param properties the properties of the ontology version that the shapes name, by IRI, with the + * property each relation declares as its inverse + * @param targets the classes of that version that a {@code class} part names, by IRI + * @param boundOnInverse the ids of the relations whose declared inverse a class of the domain of + * that inverse binds + * @param revisions the binding revision of every class whose bindings were read, by class id + */ +record OntologyShapeCheckFacts( + Subject subject, + Map properties, + Map targets, + Set boundOnInverse, + Map revisions) { + + /** + * The class whose shapes are compiled. + * + * @param tables every table the class binds that exists, the identity table first + */ + record Subject(UUID id, URI iri, List tables) { + Optional identity() { + return tables.stream() + .filter(table -> table.row().role() == OntologyBindingRole.IDENTITY) + .findFirst(); + } + + /** + * Where the records of the class hold the values of a property: each column of the identity + * table and of the contributing tables that the property is bound to, the identity table + * first. A table with no role defines no record and adds nothing to one. + */ + List places(final UUID propertyId) { + return tables.stream() + .filter(table -> table.row().role() != null) + .flatMap(table -> bound(table, propertyId)) + .toList(); + } + + /** True when the class binds the property in a column of any table, whatever its role. */ + boolean binds(final UUID propertyId) { + return tables.stream().flatMap(table -> bound(table, propertyId)).findAny().isPresent(); + } + + private static Stream bound(final MappedTable table, final UUID propertyId) { + return listOrEmpty(table.row().columns()).stream() + .filter(binding -> propertyId.equals(binding.getPropertyId())) + .map(binding -> new Place(table, binding)); + } + } + + /** One column of one table that a property is bound to. */ + record Place(MappedTable holder, OntologyColumnBinding binding) { + boolean onIdentity() { + return holder.row().role() == OntologyBindingRole.IDENTITY; + } + } + + /** + * A class that a {@code class} part names. + * + * @param identity its identity table, or null when it has none or the table no longer exists + * @param subclassSharesTable true when a subclass of the class has its identity table on the + * same table + */ + record Target(UUID id, MappedTable identity, boolean subclassSharesTable) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java new file mode 100644 index 000000000000..6a0b01c8c668 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java @@ -0,0 +1,356 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.service.ontology.OntologyBuiltinTest.parameter; +import static org.openmetadata.service.ontology.OntologySettled.of; +import static org.openmetadata.service.ontology.OntologySettled.refused; +import static org.openmetadata.service.ontology.OntologySettled.when; + +import java.math.BigDecimal; +import java.net.URI; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.OntologyCheckGates.Records; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideList; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; +import org.openmetadata.service.ontology.sql.ParsedValue; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedValue; +import org.openmetadata.service.ontology.sql.TypedValues; +import org.openmetadata.service.ontology.sql.TypedValues.Kind; + +/** + * How the parts of a constraint that ask about each value of a data property are checked at one + * place: {@code datatype}, {@code range}, {@code in} and {@code pattern} + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A null is no value, so it breaks + * none of them. A value of a constraint is read as a value of the column it is compared with, and + * the comparison is the engine's own. + */ +final class OntologyShapeValueRules { + private static final String MIN_VALUE = "minValue"; + private static final String MAX_VALUE = "maxValue"; + private static final String ALLOWED_VALUES = "allowedValues"; + private static final String MATCH_ENUM = "matchEnum"; + private static final String REGEX = "regex"; + private static final String TRUE = "true"; + private static final String FALSE = "false"; + + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + private static final String RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + + /** The datatypes of a literal that carries a language tag, which no column value has. */ + private static final Set TAGGED = Set.of(RDF + "langString", RDF + "PlainLiteral"); + + private static final Set ORDERED = + EnumSet.of(Kind.WHOLE, Kind.DECIMAL, Kind.DATE, Kind.TIME, Kind.TIMESTAMP); + private static final Set NUMBERS = EnumSet.of(Kind.WHOLE, Kind.DECIMAL); + private static final Set LISTED_BY_A_COLUMN_TEST = EnumSet.of(Kind.TEXT, Kind.WHOLE); + private static final Set NEVER_NULL = + EnumSet.of(ColumnConstraint.NOT_NULL, ColumnConstraint.PRIMARY_KEY); + + private static final Set WHOLE_TYPES = + EnumSet.of( + ColumnDataType.TINYINT, + ColumnDataType.BYTEINT, + ColumnDataType.SMALLINT, + ColumnDataType.INT, + ColumnDataType.BIGINT, + ColumnDataType.LARGEINT); + private static final Set FIXED_POINT_TYPES = + EnumSet.of(ColumnDataType.DECIMAL, ColumnDataType.NUMERIC, ColumnDataType.NUMBER); + + /** + * The columns whose every value is a value of a datatype, by datatype IRI. A fixed-point column + * with a scale of zero holds whole numbers only, and a whole-number column holds decimals. + */ + private static final Map> HOLDS_ONLY = + Map.of( + XSD + "string", + ofTypes( + ColumnDataType.VARCHAR, + ColumnDataType.CHAR, + ColumnDataType.STRING, + ColumnDataType.TEXT, + ColumnDataType.MEDIUMTEXT, + ColumnDataType.ENUM), + XSD + "boolean", + ofTypes(ColumnDataType.BOOLEAN), + XSD + "integer", + column -> WHOLE_TYPES.contains(column.getDataType()) || isFixedPoint(column, true), + XSD + "decimal", + column -> WHOLE_TYPES.contains(column.getDataType()) || isFixedPoint(column, false), + XSD + "double", + ofTypes(ColumnDataType.DOUBLE, ColumnDataType.FLOAT), + XSD + "float", + ofTypes(ColumnDataType.FLOAT), + XSD + "date", + ofTypes(ColumnDataType.DATE), + XSD + "time", + ofTypes(ColumnDataType.TIME), + XSD + "dateTime", + ofTypes(ColumnDataType.TIMESTAMP, ColumnDataType.TIMESTAMPZ, ColumnDataType.DATETIME)); + + private OntologyShapeValueRules() {} + + /** The bounds of a range as values of the column. A range has at least one. */ + private record Bounds(Optional min, Optional max) { + boolean fitDoubles() { + return min.map(OntologyShapeValueRules::fitsADouble).orElse(true) + && max.map(OntologyShapeValueRules::fitsADouble).orElse(true); + } + } + + private static Predicate ofTypes( + final ColumnDataType first, final ColumnDataType... rest) { + final Set types = EnumSet.of(first, rest); + return column -> types.contains(column.getDataType()); + } + + private static boolean isFixedPoint(final Column column, final boolean wholeOnly) { + final boolean noFraction = column.getScale() != null && column.getScale() == 0; + return FIXED_POINT_TYPES.contains(column.getDataType()) && (!wholeOnly || noFraction); + } + + /** Every value of the column is a value of the datatype, so nothing is left to test. */ + static OntologySettled datatype(final URI datatype, final Place place) { + final Predicate holdsOnly = HOLDS_ONLY.get(datatype.toString()); + return OntologyCheckGates.column(place) + .then( + column -> + holdsOnly == null + ? refused(OntologyShapeCheckReason.DATATYPE_NOT_SUPPORTED) + : when( + holdsOnly.test(column), + new HeldByMapping(), + OntologyShapeCheckReason.DATATYPE_MISMATCH)); + } + + /** Every value lies between the bounds of the constraint, which are part of the range. */ + static OntologySettled range( + final OntologyShapeConstraint constraint, final Records records, final Place place) { + return OntologyCheckGates.column(place) + .then( + column -> + bounds(column, constraint).then(bounds -> ranged(records, place, column, bounds))); + } + + private static OntologySettled bounds( + final Column column, final OntologyShapeConstraint constraint) { + if (TypedValues.kind(column).filter(ORDERED::contains).isEmpty()) { + return refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED); + } + return bound(column, constraint.getMinInclusive()) + .then(min -> bound(column, constraint.getMaxInclusive()).map(max -> new Bounds(min, max))); + } + + private static OntologySettled> bound( + final Column column, final OntologyLiteral literal) { + return literal == null ? of(Optional.empty()) : value(column, literal).map(Optional::of); + } + + private static OntologySettled ranged( + final Records records, final Place place, final Column column, final Bounds bounds) { + final List path = place.binding().getColumnPath(); + final boolean number = TypedValues.kind(column).filter(NUMBERS::contains).isPresent(); + if (number && bounds.fitDoubles() && takes(OntologyBuiltinTest.BETWEEN, records, place)) { + return of(columnTest(OntologyBuiltinTest.BETWEEN, place, between(bounds))); + } + return OntologyCheckGates.route(records, place) + .then(OntologyCheckGates::reach) + .map(reach -> generated(place, new OutsideRange(reach, path, bounds.min(), bounds.max()))); + } + + private static List between(final Bounds bounds) { + final List parameters = new ArrayList<>(); + bounds.min().ifPresent(min -> parameters.add(parameter(MIN_VALUE, min.source()))); + bounds.max().ifPresent(max -> parameters.add(parameter(MAX_VALUE, max.source()))); + return List.copyOf(parameters); + } + + /** The range test reads its bounds as doubles, so a bound must be one exactly. */ + private static boolean fitsADouble(final TypedValue bound) { + final BigDecimal exact = + switch (bound.parsed()) { + case ParsedValue.WholeNumber whole -> new BigDecimal(whole.value()); + case ParsedValue.DecimalNumber decimal -> decimal.value(); + default -> null; + }; + return exact != null + && Double.isFinite(exact.doubleValue()) + && new BigDecimal(exact.doubleValue()).compareTo(exact) == 0; + } + + /** Every value is one of the listed literals. */ + static OntologySettled in( + final List list, final Records records, final Place place) { + return OntologyCheckGates.column(place) + .then( + column -> + listed(column, list).then(values -> listTest(records, place, column, values))); + } + + private static OntologySettled> listed( + final Column column, final List list) { + if (TypedValues.kind(column).isEmpty()) { + return refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED); + } + return OntologySettled.all( + list.stream().map(item -> value(column, item.getLiteral())).toList()); + } + + private static OntologySettled listTest( + final Records records, + final Place place, + final Column column, + final List values) { + final boolean listable = + TypedValues.kind(column).filter(LISTED_BY_A_COLUMN_TEST::contains).isPresent() + && NEVER_NULL.contains(column.getConstraint()) + && !values.isEmpty(); + if (listable && takes(OntologyBuiltinTest.IN_SET, records, place)) { + return of(columnTest(OntologyBuiltinTest.IN_SET, place, inSet(values))); + } + return OntologyCheckGates.route(records, place) + .then(OntologyCheckGates::reach) + .map( + reach -> + generated(place, new OutsideList(reach, place.binding().getColumnPath(), values))); + } + + /** + * The parameters of the set test. With {@code matchEnum} it fails for every row whose value is + * not listed, and without it for no row as long as one listed value occurs. + */ + private static List inSet(final List values) { + final List allowed = + values.stream() + .map( + value -> + value.parsed() instanceof ParsedValue.WholeNumber whole + ? (Object) whole.value() + : value.source()) + .toList(); + return List.of( + parameter(ALLOWED_VALUES, JsonUtils.pojoToJson(allowed)), parameter(MATCH_ENUM, TRUE)); + } + + /** + * Every value matches the pattern. Only the regex test can say so, and it reads rows, so the + * table must be simple. + */ + static OntologySettled pattern( + final String pattern, final Records records, final Place place) { + return OntologyCheckGates.column(place) + .then(column -> matched(pattern, records, place, column)) + .map( + family -> + columnTest( + OntologyBuiltinTest.MATCH_REGEX, place, List.of(parameter(REGEX, pattern)))); + } + + private static OntologySettled matched( + final String pattern, final Records records, final Place place, final Column column) { + final boolean text = TypedValues.kind(column).filter(Kind.TEXT::equals).isPresent(); + final List path = place.binding().getColumnPath(); + if (!text || !OntologyBuiltinTest.MATCH_REGEX.takes(path, column)) { + return refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED); + } + if (!place.onIdentity() || !records.simple()) { + return refused(OntologyShapeCheckReason.TABLE_NOT_SIMPLE); + } + return SqlEngineFamily.forServiceType(place.holder().serviceType()) + .filter(family -> family != SqlEngineFamily.TSQL) + .map( + family -> + when( + OntologyPortablePattern.reads(pattern, family), + family, + OntologyShapeCheckReason.PATTERN_NOT_PORTABLE)) + .orElseGet(() -> refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED)); + } + + /** One literal of a constraint as a value of the column. */ + private static OntologySettled value( + final Column column, final OntologyLiteral literal) { + final boolean unreadable = + literal == null + || literal.getDatatypeIri() != null + && TAGGED.contains(literal.getDatatypeIri().toString()); + if (unreadable) { + return refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN); + } + try { + return of(TypedValues.value(column, written(column, literal.getValue()))); + } catch (final BadRequestException unparsed) { + return refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN); + } + } + + /** A literal is text, and a boolean column takes the JSON values true and false. */ + private static Object written(final Column column, final String text) { + final boolean bool = TypedValues.kind(column).filter(Kind.BOOL::equals).isPresent(); + if (bool && (TRUE.equals(text) || FALSE.equals(text))) { + return Boolean.valueOf(text); + } + return text; + } + + /** True when a column test on the place reads exactly the records and the definition takes it. */ + private static boolean takes( + final OntologyBuiltinTest test, final Records records, final Place place) { + final List path = place.binding().getColumnPath(); + return place.onIdentity() + && records.simple() + && test.takes(path, OntologyBindingRules.resolveColumn(place.holder().table(), path)); + } + + private static OntologyPartOutcome columnTest( + final OntologyBuiltinTest test, + final Place place, + final List parameters) { + final List path = place.binding().getColumnPath(); + return OntologyCheckGates.check( + place, + List.of(path), + test.on(place.holder().table(), path.getFirst(), parameters), + List.of(place.holder())); + } + + private static OntologyPartOutcome generated(final Place place, final OntologyCheckProbe probe) { + return OntologyCheckGates.check( + place, + List.of(place.binding().getColumnPath()), + new Test.Generated(probe), + OntologyCheckGates.read(probe.reach())); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/SqlEngineFamily.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/SqlEngineFamily.java index 76e165f33a92..02b88e964403 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/SqlEngineFamily.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/SqlEngineFamily.java @@ -18,6 +18,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -129,12 +130,16 @@ public enum SqlEngineFamily { } public static SqlEngineFamily ofServiceType(final String serviceType) { - final SqlEngineFamily family = serviceType == null ? null : BY_SERVICE_TYPE.get(serviceType); - if (family == null) { - throw new BadRequestException( - String.format("SQL generation does not support %s", serviceType)); - } - return family; + return forServiceType(serviceType) + .orElseThrow( + () -> + new BadRequestException( + String.format("SQL generation does not support %s", serviceType))); + } + + /** The family that writes for the service type, or empty when no statement is written for it. */ + public static Optional forServiceType(final String serviceType) { + return Optional.ofNullable(serviceType).map(BY_SERVICE_TYPE::get); } public OntologyConceptQueryDialect dialect() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java index 76d2b59841ec..f648b16d0ae4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.regex.Pattern; import java.util.stream.IntStream; @@ -84,7 +85,7 @@ public final class TypedValues { "a UUID is written as 32 hexadecimal digits in groups of 8, 4, 4, 4 and 12"; /** How the values of a data type are written. A data type with no kind takes no value. */ - private enum Kind { + public enum Kind { WHOLE, DECIMAL, TEXT, @@ -212,18 +213,24 @@ private static List members(final Column column, final Object raw) { return list.stream().map(member -> value(column, member)).toList(); } + /** How the values of the column's data type are written, or empty when it takes no value. */ + public static Optional kind(final Column column) { + return Optional.ofNullable( + switch (column.getDataType()) { + case TINYINT, BYTEINT, SMALLINT, INT, BIGINT, LARGEINT -> Kind.WHOLE; + case DECIMAL, NUMERIC, NUMBER, FLOAT, DOUBLE -> Kind.DECIMAL; + case VARCHAR, CHAR, STRING, TEXT, MEDIUMTEXT, ENUM -> Kind.TEXT; + case BOOLEAN, BIT -> Kind.BOOL; + case DATE -> Kind.DATE; + case TIME -> Kind.TIME; + case TIMESTAMP, TIMESTAMPZ, DATETIME -> Kind.TIMESTAMP; + case UUID -> Kind.UUID; + default -> null; + }); + } + private static Kind kindOf(final Column column) { - return switch (column.getDataType()) { - case TINYINT, BYTEINT, SMALLINT, INT, BIGINT, LARGEINT -> Kind.WHOLE; - case DECIMAL, NUMERIC, NUMBER, FLOAT, DOUBLE -> Kind.DECIMAL; - case VARCHAR, CHAR, STRING, TEXT, MEDIUMTEXT, ENUM -> Kind.TEXT; - case BOOLEAN, BIT -> Kind.BOOL; - case DATE -> Kind.DATE; - case TIME -> Kind.TIME; - case TIMESTAMP, TIMESTAMPZ, DATETIME -> Kind.TIMESTAMP; - case UUID -> Kind.UUID; - default -> throw unsupported(column); - }; + return kind(column).orElseThrow(() -> unsupported(column)); } /** diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java new file mode 100644 index 000000000000..4c3e0b4f0080 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java @@ -0,0 +1,106 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** Which regular expressions every engine reads alike, one pattern for each rule. */ +class OntologyPortablePatternTest { + @ParameterizedTest + @ValueSource( + strings = { + "^$", + "^abc 123$", + "^a.c$", + "^a\\.b\\-c\\$\\^\\\\$", + "^[a-z]$", + "^[A-Z0-9 ]+$", + "^[^0-9]*$", + "^[abc]{3}$", + "^a?b*c+$", + "^a{2}b{2,}c{2,5}$", + "^(ab|cd)$", + "^(a(b|c))+d$", + "^(a|b)(c|d)$", + "^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}$" + }) + void acceptsAPatternInsideTheCommonCore(final String pattern) { + assertEquals(true, OntologyPortablePattern.isPortable(pattern), pattern); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "abc", + "^abc", + "abc$", + "^abc\\$", + "^a|b$", + "^a^b$", + "^a$b$", + "^\\d+$", + "^\\w$", + "^a\\1$", + "^(?:a)$", + "^(?=a)a$", + "^(?i)a$", + "^a*?$", + "^a+?$", + "^a??$", + "^a*+$", + "^a{2}?$", + "^a**$", + "^*a$", + "^a{,2}$", + "^a{3,2}$", + "^a{256}$", + "^a{2$", + "^(a$", + "^a)$", + "^()$", + "^(a|)$", + "^[]$", + "^[a$", + "^[z-a]$", + "^[a-Z]$", + "^[a-]$", + "^[\\d]$", + "^[a\\-z]$", + "^[[:alpha:]]$", + "^a_b$", + "^café$", + "^a\tb$" + }) + void refusesAPatternThatEnginesReadDifferently(final String pattern) { + assertEquals(false, OntologyPortablePattern.isPortable(pattern), pattern); + } + + @ParameterizedTest + @ValueSource(strings = {"^[a-z]+$", "^A1$", "^x$"}) + void refusesALetterOnlyForTheMysqlFamily(final String pattern) { + assertEquals(false, OntologyPortablePattern.reads(pattern, SqlEngineFamily.MYSQL), pattern); + assertEquals(true, OntologyPortablePattern.reads(pattern, SqlEngineFamily.POSTGRES), pattern); + } + + @ParameterizedTest + @ValueSource(strings = {"^[0-9]{3}\\-[0-9]{4}$", "^1 2$"}) + void acceptsAPatternWithoutLettersForTheMysqlFamily(final String pattern) { + assertEquals(true, OntologyPortablePattern.reads(pattern, SqlEngineFamily.MYSQL), pattern); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java new file mode 100644 index 000000000000..72a66f78c458 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java @@ -0,0 +1,952 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; +import static org.openmetadata.service.ontology.OntologyMappingShapes.contributing; +import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; +import static org.openmetadata.service.ontology.OntologyMappingShapes.relation; +import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; + +import java.net.URI; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyCheckProbe.FewerValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.MoreValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.NoRecord; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideList; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotMapped; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test.Builtin; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test.Generated; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; + +/** + * Every row of the rule that compiles a shape constraint into data quality checks + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered), each with a literal mapping and + * the literal answer. + */ +class OntologyShapeCheckCompilerTest { + private static final String POSTGRES = "Postgres"; + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + private static final String EMAIL_LINK = + "<#E::table::warehouse.sales.shop.customers::columns::email>"; + + /** A shipment names its account with two columns, the two-column key of the account table. */ + private static final Shape TWO_COLUMN_RELATION = + new Shape( + "twoColumnRelation", + List.of( + table("shipments", List.of(integer("id"), text("tenant"), integer("customer"))), + table( + "crm_customers", + List.of(text("tenant_id"), integer("customer_id"), text("name")))), + List.of("Shipment", "Account"), + List.of(relation("shippedTo", "Shipment", "Account")), + List.of( + identity( + "Shipment", + "shipments", + List.of("id"), + null, + new ColumnBindingSpec( + "shippedTo", + "tenant", + new JoinSpec( + "crm_customers", + OntologyJoinStatus.CONFIRMED, + List.of("tenant", "customer"), + List.of("tenant_id", "customer_id")))), + identity("Account", "crm_customers", List.of("tenant_id", "customer_id"), null)), + List.of()); + + /** A membership is held by a person, and people share a filtered table with other parties. */ + private static final Shape FILTERED_TARGET = + new Shape( + "filteredTarget", + List.of( + table("parties", List.of(integer("id"), text("kind"), text("name"))), + table("memberships", List.of(integer("id"), integer("party_id")))), + List.of("Membership", "Person"), + List.of(relation("heldBy", "Membership", "Person")), + List.of( + identity( + "Person", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person")), + identity( + "Membership", + "memberships", + List.of("id"), + null, + OntologyMappingShapes.joined("heldBy", "party_id", "parties", "id"))), + List.of()); + + private static OntologyShapeCheckModel customers() { + return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, POSTGRES); + } + + /** The customers table with its key declared, so that its rows are its records. */ + private static OntologyShapeCheckModel simpleCustomers() { + return customers().primaryKey("customers", "id"); + } + + private static OntologyShapeCheckModel shape(final Shape shape) { + return new OntologyShapeCheckModel(shape, POSTGRES); + } + + private static OntologyShapeCheckModel customersWith(final BindingSpec... bindings) { + return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, POSTGRES, List.of(bindings)); + } + + /** The customer class with its name bound in its identity table and in a contributing table. */ + private static OntologyShapeCheckModel nameInTwoTables() { + return new OntologyShapeCheckModel( + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + identity("Customer", "customers", List.of("id"), null, bound("customerName", "name")), + contributing( + "Customer", + "customer_addresses", + List.of("customer_id"), + bound("customerName", "city")))); + } + + private static OntologyShapeValue literal(final String value) { + return new OntologyShapeValue().withLiteral(new OntologyLiteral().withValue(value)); + } + + private static List literals(final String... values) { + return List.of(values).stream().map(OntologyShapeCheckCompilerTest::literal).toList(); + } + + private static OntologyLiteral limit(final String value) { + return new OntologyLiteral().withValue(value); + } + + private static TestCaseParameterValue parameter(final String name, final String value) { + return new TestCaseParameterValue().withName(name).withValue(value); + } + + private static NotEnforceable refused(final OntologyShapeCheckReason reason) { + return new NotEnforceable(reason); + } + + private static T probe( + final Class kind, final TableCheck check) { + return assertInstanceOf(kind, assertInstanceOf(Generated.class, check.test()).probe()); + } + + private static Column column( + final OntologyShapeCheckModel model, final String table, final String name) { + return model.mapping().table(table).getColumns().stream() + .filter(column -> column.getName().equals(name)) + .findFirst() + .orElseThrow(); + } + + private static List tables(final List rows) { + return rows.stream().map(BindingRow::assetFqnHash).toList(); + } + + @Test + void minCountZeroIsHeldByAnyMapping() { + final OntologyShapeCheckModel simple = simpleCustomers(); + assertEquals( + new HeldByMapping(), simple.answer("Customer", simple.on("customerEmail").withMinCount(0))); + final OntologyShapeCheckModel filtered = shape(FILTERED_IDENTITY); + assertEquals( + new HeldByMapping(), filtered.answer("Person", filtered.on("personName").withMinCount(0))); + final OntologyShapeCheckModel linked = shape(LINK_TABLE); + assertEquals( + new HeldByMapping(), linked.answer("Order", linked.on("contains").withMinCount(0))); + } + + @Test + void minCountOneOnASubjectKeyColumnIsHeld() { + final BindingSpec nameIsTheKey = + identity("Customer", "customers", List.of("id"), null, bound("customerName", "id")); + final OntologyShapeCheckModel plain = customersWith(nameIsTheKey); + assertEquals( + new HeldByMapping(), plain.answer("Customer", plain.on("customerName").withMinCount(1))); + final OntologyShapeCheckModel simple = + customersWith(nameIsTheKey).primaryKey("customers", "id"); + assertEquals( + new HeldByMapping(), simple.answer("Customer", simple.on("customerName").withMinCount(1))); + } + + @Test + void minCountOneOnOneColumnOfASimpleTableIsTheNotNullTest() { + final OntologyShapeCheckModel model = simpleCustomers(); + final TableCheck check = model.check("Customer", model.on("customerEmail").withMinCount(1)); + assertEquals(new Builtin("columnValuesToBeNotNull", EMAIL_LINK, List.of()), check.test()); + assertEquals("customers", check.place().holder().table().getName()); + assertEquals(List.of(List.of("email")), check.columns()); + assertEquals(List.of("customers"), tables(check.read())); + } + + @Test + void minCountOneOffASimpleTableCountsRecordsWithNoValue() { + final OntologyShapeCheckModel undeclared = customers(); + final FewerValues noKey = + probe( + FewerValues.class, + undeclared.check("Customer", undeclared.on("customerEmail").withMinCount(1))); + assertEquals(1, noKey.count()); + assertEquals(List.of(List.of("email")), noKey.columns()); + assertNull(noKey.reach().holder()); + assertNull(noKey.reach().identity().filter()); + + final OntologyShapeCheckModel filtered = shape(FILTERED_IDENTITY).primaryKey("parties", "id"); + final FewerValues people = + probe( + FewerValues.class, filtered.check("Person", filtered.on("personName").withMinCount(1))); + assertEquals(OntologyRowFilterOperator.EQUALS, people.reach().identity().filter().operator()); + } + + @Test + void minCountOneOnAContributingTableJoinsItToTheRecords() { + final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); + final TableCheck check = model.check("Account", model.on("accountTier").withMinCount(1)); + final FewerValues probe = probe(FewerValues.class, check); + assertEquals("crm_customer_profile", check.place().holder().table().getName()); + assertEquals("crm_customer_profile", probe.reach().holder().table().table().getName()); + assertEquals( + List.of( + new JoinPair(List.of("tenant_id"), List.of("tenant")), + new JoinPair(List.of("customer_id"), List.of("customer"))), + probe.reach().keyPairs()); + assertEquals(List.of("crm_customers", "crm_customer_profile"), tables(check.read())); + } + + @Test + void minCountOneOnARelationOfSeveralColumnsIsGeneratedEvenOnASimpleTable() { + final OntologyShapeCheckModel model = shape(TWO_COLUMN_RELATION).primaryKey("shipments", "id"); + final FewerValues probe = + probe(FewerValues.class, model.check("Shipment", model.on("shippedTo").withMinCount(1))); + assertEquals(1, probe.count()); + assertEquals(List.of(List.of("tenant"), List.of("customer")), probe.columns()); + } + + @Test + void minCountAboveOneCountsDistinctValuesEvenOnASimpleTable() { + final OntologyShapeCheckModel simple = simpleCustomers(); + assertEquals( + 2, + probe( + FewerValues.class, + simple.check("Customer", simple.on("customerEmail").withMinCount(2))) + .count()); + final OntologyShapeCheckModel repeated = shape(REPEATED_CONTRIBUTION); + assertEquals( + 3, + probe( + FewerValues.class, + repeated.check("Customer", repeated.on("addressCity").withMinCount(3))) + .count()); + } + + @Test + void maxCountOfAtLeastOneIsHeldOnASimpleTable() { + final OntologyShapeCheckModel model = simpleCustomers(); + assertEquals( + new HeldByMapping(), model.answer("Customer", model.on("customerEmail").withMaxCount(1))); + assertEquals( + new HeldByMapping(), model.answer("Customer", model.on("customerEmail").withMaxCount(3))); + } + + @Test + void maxCountOfAtLeastOneIsHeldWhereADeclaredKeyLiesInsideTheSubjectKey() { + final OntologyShapeCheckModel contributing = + shape(REPEATED_CONTRIBUTION).uniqueKey("customer_addresses", "customer_id"); + assertEquals( + new HeldByMapping(), + contributing.answer("Customer", contributing.on("addressCity").withMaxCount(1))); + final OntologyShapeCheckModel filtered = shape(FILTERED_IDENTITY).primaryKey("parties", "id"); + assertEquals( + new HeldByMapping(), filtered.answer("Person", filtered.on("personName").withMaxCount(1))); + } + + @Test + void maxCountWithoutSuchAKeyCountsDistinctValues() { + final OntologyShapeCheckModel undeclared = shape(REPEATED_CONTRIBUTION); + final TableCheck check = + undeclared.check("Customer", undeclared.on("addressCity").withMaxCount(1)); + final MoreValues probe = probe(MoreValues.class, check); + assertEquals(1, probe.count()); + assertEquals(List.of(List.of("city")), probe.columns()); + assertEquals("customer_addresses", check.place().holder().table().getName()); + + final OntologyShapeCheckModel widerKey = + shape(REPEATED_CONTRIBUTION).uniqueKey("customer_addresses", "customer_id", "city"); + assertEquals( + 1, + probe( + MoreValues.class, + widerKey.check("Customer", widerKey.on("addressCity").withMaxCount(1))) + .count()); + } + + @Test + void maxCountZeroIsGeneratedEvenOnASimpleTable() { + final OntologyShapeCheckModel model = simpleCustomers(); + assertEquals( + 0, + probe(MoreValues.class, model.check("Customer", model.on("customerEmail").withMaxCount(0))) + .count()); + } + + @Test + void inOnATextColumnThatIsNeverNullOnASimpleTableIsTheSetTest() { + final OntologyShapeCheckModel model = simpleCustomers().notNull("customers", "email"); + final OntologyShapeConstraint constraint = + model.on("customerEmail").withIn(literals("ada@example.org", "it's \"x\"")); + assertEquals( + new Builtin( + "columnValuesToBeInSet", + EMAIL_LINK, + List.of( + parameter("allowedValues", "[\"ada@example.org\",\"it's \\\"x\\\"\"]"), + parameter("matchEnum", "true"))), + model.check("Customer", constraint).test()); + } + + @Test + void inOnAWholeNumberKeyColumnOfASimpleTableListsNumbers() { + final OntologyShapeCheckModel model = + customersWith( + identity("Customer", "customers", List.of("id"), null, bound("customerName", "id"))) + .primaryKey("customers", "id") + .notNull("customers", "id"); + assertEquals( + new Builtin( + "columnValuesToBeInSet", + "<#E::table::warehouse.sales.shop.customers::columns::id>", + List.of(parameter("allowedValues", "[1,2]"), parameter("matchEnum", "true"))), + model.check("Customer", model.on("customerName").withIn(literals("1", "2"))).test()); + } + + @Test + void inOnAColumnThatMayHoldNullIsGenerated() { + final OntologyShapeCheckModel model = simpleCustomers(); + final OutsideList probe = + probe( + OutsideList.class, + model.check("Customer", model.on("customerEmail").withIn(literals("a", "b")))); + assertEquals(List.of("email"), probe.column()); + assertEquals(List.of("a", "b"), probe.allowed().stream().map(value -> value.source()).toList()); + } + + @Test + void inOffASimpleTableIsGenerated() { + final OntologyShapeCheckModel filtered = + shape(FILTERED_IDENTITY).primaryKey("parties", "id").notNull("parties", "name"); + final OutsideList people = + probe( + OutsideList.class, + filtered.check("Person", filtered.on("personName").withIn(literals("Ada")))); + assertEquals(List.of("name"), people.column()); + + final OntologyShapeCheckModel linked = shape(LINK_TABLE); + final TableCheck quantity = + linked.check("Order", linked.on("itemQuantity").withIn(literals("1", "2"))); + assertEquals("order_items", quantity.place().holder().table().getName()); + assertEquals( + "order_items", + probe(OutsideList.class, quantity).reach().holder().table().table().getName()); + } + + @Test + void inOnADecimalColumnIsGeneratedEvenOnASimpleTable() { + final OntologyShapeCheckModel model = + shape(COLUMN_RELATION).primaryKey("orders", "id").notNull("orders", "total"); + final OutsideList probe = + probe( + OutsideList.class, + model.check("Order", model.on("orderTotal").withIn(literals("9.99", "20")))); + assertEquals( + List.of("9.99", "20"), probe.allowed().stream().map(value -> value.source()).toList()); + } + + @Test + void rangeOnANumericColumnOfASimpleTableIsTheBetweenTest() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); + final String link = "<#E::table::warehouse.sales.shop.orders::columns::total>"; + assertEquals( + new Builtin( + "columnValuesToBeBetween", + link, + List.of(parameter("minValue", "0"), parameter("maxValue", "1000.5"))), + model + .check( + "Order", + model + .on("orderTotal") + .withMinInclusive(limit("0")) + .withMaxInclusive(limit("1000.5"))) + .test()); + assertEquals( + new Builtin("columnValuesToBeBetween", link, List.of(parameter("maxValue", "250"))), + model.check("Order", model.on("orderTotal").withMaxInclusive(limit("250"))).test()); + } + + @Test + void rangeWithABoundThatNoDoubleHoldsIsGenerated() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); + final OutsideRange probe = + probe( + OutsideRange.class, + model.check("Order", model.on("orderTotal").withMaxInclusive(limit("0.1")))); + assertEquals(Optional.empty(), probe.min()); + assertEquals("0.1", probe.max().orElseThrow().source()); + } + + @Test + void rangeOffASimpleTableIsGenerated() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + final OutsideRange probe = + probe( + OutsideRange.class, + model.check( + "Order", + model.on("orderTotal").withMinInclusive(limit("0")).withMaxInclusive(limit("5")))); + assertEquals(List.of("total"), probe.column()); + assertEquals("0", probe.min().orElseThrow().source()); + assertEquals("5", probe.max().orElseThrow().source()); + } + + @Test + void rangeOnATextColumnIsNotEnforceable() { + final OntologyShapeCheckModel model = simpleCustomers(); + assertEquals( + refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED), + model.answer("Customer", model.on("customerEmail").withMinInclusive(limit("a")))); + } + + @Test + void patternOnATextColumnOfASimpleTableIsTheRegexTest() { + final OntologyShapeCheckModel model = simpleCustomers(); + final String pattern = "^[a-z]+\\@example\\.org$"; + assertEquals( + new Builtin("columnValuesToMatchRegex", EMAIL_LINK, List.of(parameter("regex", pattern))), + model.check("Customer", model.on("customerEmail").withPattern(pattern)).test()); + } + + @Test + void patternOffASimpleTableIsNotEnforceable() { + final OntologyShapeCheckModel undeclared = customers(); + assertEquals( + refused(OntologyShapeCheckReason.TABLE_NOT_SIMPLE), + undeclared.answer("Customer", undeclared.on("customerEmail").withPattern("^a$"))); + final OntologyShapeCheckModel contributing = shape(COMPOSITE_KEY); + assertEquals( + refused(OntologyShapeCheckReason.TABLE_NOT_SIMPLE), + contributing.answer("Account", contributing.on("accountTier").withPattern("^a$"))); + } + + @ParameterizedTest + @CsvSource({"Mssql", "Oracle"}) + void patternOnAnEngineWithNoCommonRegexIsNotEnforceable(final String serviceType) { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel(UNFILTERED_IDENTITY, serviceType).primaryKey("customers", "id"); + assertEquals( + refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + model.answer("Customer", model.on("customerEmail").withPattern("^a$"))); + } + + @Test + void patternOutsideTheCommonCoreIsNotEnforceable() { + final OntologyShapeCheckModel model = simpleCustomers(); + assertEquals( + refused(OntologyShapeCheckReason.PATTERN_NOT_PORTABLE), + model.answer("Customer", model.on("customerEmail").withPattern("^\\d+$"))); + } + + @Test + void patternWithALetterIsNotPortableToTheMysqlFamily() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel(UNFILTERED_IDENTITY, "Mysql").primaryKey("customers", "id"); + assertEquals( + refused(OntologyShapeCheckReason.PATTERN_NOT_PORTABLE), + model.answer("Customer", model.on("customerEmail").withPattern("^[a-z]+$"))); + assertEquals( + new Builtin( + "columnValuesToMatchRegex", EMAIL_LINK, List.of(parameter("regex", "^[0-9]{3}$"))), + model.check("Customer", model.on("customerEmail").withPattern("^[0-9]{3}$")).test()); + } + + @Test + void patternOnAColumnThatIsNotTextIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); + assertEquals( + refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED), + model.answer("Order", model.on("orderTotal").withPattern("^[0-9]+$"))); + } + + @Test + void classCountsValuesThatAreNoRecordOfTheNamedClass() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); + final TableCheck check = + model.check("Order", model.on("placedBy").withClassIri(COLUMN_RELATION.iri("Customer"))); + final NoRecord probe = probe(NoRecord.class, check); + assertEquals(List.of(new JoinPair(List.of("customer_id"), List.of("id"))), probe.on()); + assertEquals("customers", probe.target().table().table().getName()); + assertNull(probe.target().filter()); + assertEquals(List.of(List.of("customer_id")), check.columns()); + assertEquals(List.of("orders", "customers"), tables(check.read())); + } + + @Test + void classOnALinkTableBelongsToTheLinkTableAndNamesEveryBindingItRead() { + final OntologyShapeCheckModel model = shape(LINK_TABLE); + final TableCheck check = + model.check("Order", model.on("contains").withClassIri(LINK_TABLE.iri("Product"))); + final NoRecord probe = probe(NoRecord.class, check); + assertEquals("order_items", check.place().holder().table().getName()); + assertEquals(List.of(new JoinPair(List.of("product_sku"), List.of("sku"))), probe.on()); + assertEquals(List.of("orders", "order_items", "products"), tables(check.read())); + assertEquals( + List.of( + model.mapping().id("Order"), + model.mapping().id("Order"), + model.mapping().id("Product")), + check.read().stream().map(BindingRow::conceptId).toList()); + } + + @Test + void classCarriesTheFilterOfTheTargetBinding() { + final OntologyShapeCheckModel model = shape(FILTERED_TARGET); + final NoRecord probe = + probe( + NoRecord.class, + model.check( + "Membership", model.on("heldBy").withClassIri(FILTERED_TARGET.iri("Person")))); + assertEquals(List.of("kind"), probe.target().filter().column()); + assertEquals("person", probe.target().filter().values().getFirst().source()); + } + + @Test + void classIsNotEnforceableWhenASubclassSharesAFilteredTargetTable() { + final OntologyShapeCheckModel filtered = + shape(FILTERED_TARGET).shareTableWithSubclass("Person"); + assertEquals( + refused(OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE), + filtered.answer( + "Membership", filtered.on("heldBy").withClassIri(FILTERED_TARGET.iri("Person")))); + + final OntologyShapeCheckModel unfiltered = + shape(COLUMN_RELATION).shareTableWithSubclass("Customer"); + assertInstanceOf( + Check.class, + unfiltered.answer( + "Order", unfiltered.on("placedBy").withClassIri(COLUMN_RELATION.iri("Customer")))); + } + + @Test + void classOnADataPropertyIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + assertEquals( + refused(OntologyShapeCheckReason.NOT_A_RELATION), + model.answer( + "Order", model.on("orderTotal").withClassIri(COLUMN_RELATION.iri("Customer")))); + } + + @Test + void classWhoseIdentityTableIsNotWhereTheJoinArrivesIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + assertEquals( + refused(OntologyShapeCheckReason.TARGET_CLASS_NOT_ON_JOIN), + model.answer("Order", model.on("placedBy").withClassIri(COLUMN_RELATION.iri("Order")))); + assertEquals( + refused(OntologyShapeCheckReason.TARGET_CLASS_NOT_ON_JOIN), + model.answer("Order", model.on("placedBy").withClassIri(COLUMN_RELATION.iri("Unknown")))); + } + + @ParameterizedTest + @CsvSource({"INFERRED,JOIN_NOT_CONFIRMED", ",NO_JOIN"}) + void relationWithoutAConfirmedJoinIsNotEnforceable( + final OntologyJoinStatus status, final OntologyShapeCheckReason reason) { + final JoinSpec join = + status == null + ? null + : new JoinSpec("customers", status, List.of("customer_id"), List.of("id")); + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel( + COLUMN_RELATION, + POSTGRES, + List.of( + COLUMN_RELATION.binding("Customer", "customers"), + identity( + "Order", + "orders", + List.of("id"), + null, + new ColumnBindingSpec("placedBy", "customer_id", join)))); + final OntologyShapeConstraint constraint = + model + .on("placedBy") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(COLUMN_RELATION.iri("Customer")); + assertEquals( + List.of(refused(reason), refused(reason), refused(reason)), + model.answers("Order", constraint)); + assertEquals(new HeldByMapping(), model.answer("Order", model.on("placedBy").withMinCount(0))); + } + + @Test + void relationTheClassDoesNotBindIsBoundOnItsInverseOrNotMapped() { + final OntologyShapeCheckModel inverse = shape(COLUMN_RELATION).bindOnInverse("placedBy"); + assertEquals( + List.of( + refused(OntologyShapeCheckReason.BOUND_ON_INVERSE), + refused(OntologyShapeCheckReason.BOUND_ON_INVERSE)), + inverse.answers("Customer", inverse.on("placedBy").withMinCount(1).withMaxCount(5))); + final OntologyShapeCheckModel unbound = shape(COLUMN_RELATION); + assertEquals( + new NotMapped(), unbound.answer("Customer", unbound.on("placedBy").withMinCount(1))); + } + + @Test + void valuePartsOnARelationAreNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + final OntologyShapeConstraint constraint = + model + .on("placedBy") + .withDatatypeIri(URI.create(XSD + "integer")) + .withMinInclusive(limit("1")) + .withIn(literals("1")) + .withPattern("^1$"); + final NotEnforceable notData = refused(OntologyShapeCheckReason.NOT_A_DATA_PROPERTY); + assertEquals(List.of(notData, notData, notData, notData), model.answers("Order", constraint)); + } + + @ParameterizedTest + @CsvSource({ + "VARCHAR,,string", + "ENUM,,string", + "BOOLEAN,,boolean", + "INT,,integer", + "BIGINT,,decimal", + "DECIMAL,0,integer", + "NUMERIC,2,decimal", + "NUMBER,,decimal", + "DOUBLE,,double", + "FLOAT,,double", + "FLOAT,,float", + "DATE,,date", + "TIME,,time", + "TIMESTAMP,,dateTime", + "DATETIME,,dateTime" + }) + void datatypeIsHeldWhenEveryValueOfTheColumnTypeIsOfTheDatatype( + final ColumnDataType type, final Integer scale, final String datatype) { + final OntologyShapeCheckModel model = customers(); + column(model, "customers", "email").withDataType(type).withScale(scale); + assertEquals( + new HeldByMapping(), + model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype)))); + } + + @ParameterizedTest + @CsvSource({ + "VARCHAR,,integer", + "INT,,string", + "DECIMAL,2,integer", + "DECIMAL,,integer", + "DOUBLE,,float", + "BIT,,boolean", + "TIMESTAMP,,date" + }) + void datatypeThatTheColumnTypeCanBreakIsNotEnforceable( + final ColumnDataType type, final Integer scale, final String datatype) { + final OntologyShapeCheckModel model = customers(); + column(model, "customers", "email").withDataType(type).withScale(scale); + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype)))); + } + + @Test + void datatypeOutsideTheSupportedOnesIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_NOT_SUPPORTED), + model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + "anyURI")))); + } + + @Test + void propertyBoundInSeveralTablesIsCheckedOncePerTable() { + final OntologyShapeCheckModel model = nameInTwoTables(); + final Check check = + assertInstanceOf( + Check.class, model.answer("Customer", model.on("customerName").withIn(literals("a")))); + assertEquals( + List.of("customers", "customer_addresses"), + check.checks().stream().map(one -> one.place().holder().table().getName()).toList()); + assertEquals( + List.of(List.of(List.of("name")), List.of(List.of("city"))), + check.checks().stream().map(TableCheck::columns).toList()); + } + + @Test + void countsOverSeveralTablesAreNotEnforceable() { + final OntologyShapeCheckModel model = nameInTwoTables(); + final NotEnforceable several = refused(OntologyShapeCheckReason.SEVERAL_TABLES); + assertEquals( + List.of(several, several), + model.answers("Customer", model.on("customerName").withMinCount(1).withMaxCount(1))); + assertEquals( + new HeldByMapping(), model.answer("Customer", model.on("customerName").withMinCount(0))); + } + + @Test + void tablesThatDoNotAgreeGetOneAnswerEach() { + final OntologyShapeCheckModel model = nameInTwoTables().primaryKey("customers", "id"); + final List answers = + model.answers("Customer", model.on("customerName").withPattern("^[0-9]+$")); + assertEquals(2, answers.size()); + final Check check = assertInstanceOf(Check.class, answers.getFirst()); + assertEquals( + List.of("customers"), + check.checks().stream().map(one -> one.place().holder().table().getName()).toList()); + assertEquals(refused(OntologyShapeCheckReason.TABLE_NOT_SIMPLE), answers.getLast()); + } + + @Test + void literalThatDoesNotParseAsTheColumnTypeIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + final NotEnforceable misfit = refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN); + assertEquals( + misfit, model.answer("Order", model.on("orderTotal").withIn(literals("1", "many")))); + assertEquals( + misfit, model.answer("Order", model.on("orderTotal").withMaxInclusive(limit("1e3")))); + } + + @Test + void literalWithALanguageTagIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + final OntologyShapeValue tagged = + new OntologyShapeValue() + .withLiteral( + new OntologyLiteral() + .withValue("hello") + .withDatatypeIri( + URI.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"))); + assertEquals( + refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN), + model.answer("Customer", model.on("customerEmail").withIn(List.of(tagged)))); + } + + @Test + void listThatNamesARecordIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + final OntologyShapeValue named = + new OntologyShapeValue().withIri(URI.create("https://example.org/records/1")); + assertEquals( + refused(OntologyShapeCheckReason.VALUES_ARE_RECORDS), + model.answer("Customer", model.on("customerEmail").withIn(List.of(literal("a"), named)))); + } + + @Test + void listOfMoreThanAThousandValuesIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + final List thousand = + IntStream.range(0, 1000).mapToObj(index -> literal("v" + index)).toList(); + assertEquals( + 1000, + probe( + OutsideList.class, + model.check("Customer", model.on("customerEmail").withIn(thousand))) + .allowed() + .size()); + final List oneMore = + IntStream.range(0, 1001).mapToObj(index -> literal("v" + index)).toList(); + assertEquals( + refused(OntologyShapeCheckReason.TOO_MANY_VALUES), + model.answer("Customer", model.on("customerEmail").withIn(oneMore))); + } + + @Test + void columnThatLeftTheTableIsNotEnforceable() { + final OntologyShapeCheckModel value = simpleCustomers(); + value.mapping().table("customers").getColumns().removeIf(c -> c.getName().equals("email")); + final NotEnforceable missing = refused(OntologyShapeCheckReason.COLUMN_MISSING); + assertEquals( + List.of(missing, missing, missing), + value.answers( + "Customer", + value + .on("customerEmail") + .withMinCount(1) + .withDatatypeIri(URI.create(XSD + "string")) + .withIn(literals("a")))); + + final OntologyShapeCheckModel key = customers(); + key.mapping().table("customers").getColumns().removeIf(c -> c.getName().equals("id")); + assertEquals(missing, key.answer("Customer", key.on("customerEmail").withMinCount(1))); + } + + @Test + void tableInAnotherDatabaseIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); + model + .mapping() + .table("crm_customer_profile") + .setFullyQualifiedName("warehouse.archive.shop.crm_customer_profile"); + assertEquals( + refused(OntologyShapeCheckReason.OTHER_DATABASE), + model.answer("Account", model.on("accountTier").withIn(literals("gold")))); + } + + @Test + void generatedCheckNeedsAnEngineThatStatementsAreWrittenForAndAColumnTestDoesNot() { + final OntologyShapeCheckModel undeclared = + new OntologyShapeCheckModel(UNFILTERED_IDENTITY, "Oracle"); + assertEquals( + refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + undeclared.answer("Customer", undeclared.on("customerEmail").withMinCount(1))); + final OntologyShapeCheckModel simple = + new OntologyShapeCheckModel(UNFILTERED_IDENTITY, "Oracle").primaryKey("customers", "id"); + assertEquals( + new Builtin("columnValuesToBeNotNull", EMAIL_LINK, List.of()), + simple.check("Customer", simple.on("customerEmail").withMinCount(1)).test()); + } + + @Test + void clickHouseGetsNoStatementThatKeepsUnmatchedRows() { + final OntologyShapeCheckModel contributing = + new OntologyShapeCheckModel(COMPOSITE_KEY, "Clickhouse"); + assertEquals( + List.of(refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED)), + contributing.answers("Account", contributing.on("accountTier").withMinCount(1))); + assertInstanceOf( + MoreValues.class, + ((Generated) + contributing + .check("Account", contributing.on("accountTier").withMaxCount(1)) + .test()) + .probe()); + assertInstanceOf( + FewerValues.class, + ((Generated) + contributing + .check("Account", contributing.on("accountName").withMinCount(1)) + .test()) + .probe()); + final OntologyShapeCheckModel related = + new OntologyShapeCheckModel(COLUMN_RELATION, "Clickhouse"); + assertEquals( + refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + related.answer( + "Order", related.on("placedBy").withClassIri(COLUMN_RELATION.iri("Customer")))); + } + + @Test + void propertyTheClassBindsInNoColumnIsNotMapped() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + assertEquals( + List.of(new NotMapped(), new NotMapped()), + model.answers("Customer", model.on("orderTotal").withMinCount(0).withIn(literals("1")))); + } + + @Test + void propertyTheVersionLacksIsNotMapped() { + final OntologyShapeCheckModel model = simpleCustomers(); + model.mapping().omit("customerEmail"); + assertEquals( + new NotMapped(), model.answer("Customer", model.on("customerEmail").withMinCount(1))); + } + + @Test + void classWithoutAnIdentityTableHasNoRecordsToCheck() { + final OntologyShapeCheckModel contributingOnly = + customersWith( + contributing("Customer", "customers", List.of("id"), bound("customerEmail", "email"))); + final NotEnforceable none = refused(OntologyShapeCheckReason.NO_IDENTITY_TABLE); + assertEquals( + List.of(none, none), + contributingOnly.answers( + "Customer", + contributingOnly.on("customerEmail").withMinCount(1).withIn(literals("a")))); + assertEquals( + new HeldByMapping(), + contributingOnly.answer("Customer", contributingOnly.on("customerEmail").withMinCount(0))); + + final OntologyShapeCheckModel noRole = + customersWith( + new BindingSpec( + "Customer", + "customers", + null, + List.of(), + null, + List.of(bound("customerEmail", "email")))); + assertEquals(none, noRole.answer("Customer", noRole.on("customerEmail").withMinCount(1))); + } + + @Test + void constraintRestsOnTheIdentityTableTheHolderAndTheTableItsJoinReaches() { + final OntologyShapeCheckModel model = shape(LINK_TABLE); + assertEquals( + Set.of( + model.mapping().id("orders"), + model.mapping().id("order_items"), + model.mapping().id("products")), + model.compile("Order", model.on("contains").withMinCount(1)).rests()); + assertEquals( + Set.of(model.mapping().id("orders")), + model.compile("Order", model.on("productTitle").withMinCount(1)).rests()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java new file mode 100644 index 000000000000..b67eafe3445f --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java @@ -0,0 +1,202 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyMappingReader.Bindings; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledConstraint; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledPart; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Target; + +/** + * One mapping shape as the shape check compile reads it. A test declares a key, binds a relation + * on its inverse or shares a table with a subclass, then asks what one constraint compiles to. + */ +final class OntologyShapeCheckModel { + static final String CONSTRAINT_ID = "c1"; + private final Shape shape; + private final OntologyMappingShapeModel mapping; + private final Set boundOnInverse = new HashSet<>(); + private final Set sharedWithSubclass = new HashSet<>(); + + OntologyShapeCheckModel(final Shape shape, final String serviceType) { + this(shape, serviceType, shape.bindings()); + } + + OntologyShapeCheckModel( + final Shape shape, final String serviceType, final List bindings) { + this.shape = shape; + this.mapping = new OntologyMappingShapeModel(shape, serviceType, bindings); + } + + /** The tables and binding rows under the facts. A test changes a table through it. */ + OntologyMappingShapeModel mapping() { + return mapping; + } + + /** The catalog declares a primary key of the table on these columns. */ + OntologyShapeCheckModel primaryKey(final String table, final String... columns) { + return declare(table, ConstraintType.PRIMARY_KEY, columns); + } + + /** The catalog declares a unique key of the table on these columns. */ + OntologyShapeCheckModel uniqueKey(final String table, final String... columns) { + return declare(table, ConstraintType.UNIQUE, columns); + } + + private OntologyShapeCheckModel declare( + final String table, final ConstraintType type, final String... columns) { + mapping + .table(table) + .setTableConstraints( + List.of(new TableConstraint().withConstraintType(type).withColumns(List.of(columns)))); + return this; + } + + /** The catalog says the column never holds a null. */ + OntologyShapeCheckModel notNull(final String table, final String column) { + mapping.table(table).getColumns().stream() + .filter(candidate -> candidate.getName().equals(column)) + .forEach(candidate -> candidate.setConstraint(ColumnConstraint.NOT_NULL)); + return this; + } + + /** Another class binds the inverse of the relation. */ + OntologyShapeCheckModel bindOnInverse(final String relation) { + boundOnInverse.add(relation); + return this; + } + + /** A subclass of the class has its identity table on the identity table of the class. */ + OntologyShapeCheckModel shareTableWithSubclass(final String type) { + sharedWithSubclass.add(type); + return this; + } + + /** A constraint on one property of the shape, ready for the parts a test states. */ + OntologyShapeConstraint on(final String property) { + return new OntologyShapeConstraint().withId(CONSTRAINT_ID).withPath(shape.iri(property)); + } + + OntologyShapeCheckFacts facts(final String type) { + final Bindings bindings = mapping.bindings(); + return new OntologyShapeCheckFacts( + new Subject(mapping.id(type), mapping.iri(type), tables(type, bindings)), + mapping.properties().values().stream() + .collect(Collectors.toMap(OntologyProperty::getIri, Function.identity())), + targets(bindings), + boundOnInverse.stream().map(mapping::id).collect(Collectors.toSet()), + revisions()); + } + + /** The binding revision of each class: its position in the shape, from 1. */ + private Map revisions() { + final Map revisions = new HashMap<>(); + for (int index = 0; index < shape.classes().size(); index++) { + revisions.put(mapping.id(shape.classes().get(index)), index + 1L); + } + return revisions; + } + + /** The tables of a class that exist: its identity table, then the others in binding order. */ + private List tables(final String type, final Bindings bindings) { + final List rows = new ArrayList<>(); + final BindingRow identity = bindings.identity().get(mapping.id(type)); + if (identity != null) { + rows.add(identity); + } + rows.addAll(bindings.contributing().getOrDefault(mapping.id(type), List.of())); + final Set live = mapping.catalog().live(); + return rows.stream().filter(row -> live.contains(row.assetId())).map(this::mapped).toList(); + } + + /** The model names each binding row after its table, so the row says which table it binds. */ + private MappedTable mapped(final BindingRow row) { + return new MappedTable(mapping.table(row.assetFqnHash()), row); + } + + private Map targets(final Bindings bindings) { + final Set live = mapping.catalog().live(); + final Map targets = new HashMap<>(); + for (final String type : shape.classes()) { + final BindingRow identity = bindings.identity().get(mapping.id(type)); + final boolean held = identity != null && live.contains(identity.assetId()); + targets.put( + mapping.iri(type), + new Target( + mapping.id(type), held ? mapped(identity) : null, sharedWithSubclass.contains(type))); + } + return targets; + } + + /** The shape that holds only {@code constraint}, compiled for the class. */ + CompiledConstraint compile(final String type, final OntologyShapeConstraint constraint) { + final OntologyShape held = + new OntologyShape() + .withId(mapping.id("shape")) + .withName("shape") + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withTargetConcept(mapping.iri(type)) + .withConstraints(List.of(constraint)); + return OntologyShapeCheckCompiler.compile(facts(type), List.of(held)) + .getFirst() + .constraints() + .getFirst(); + } + + /** The answers of the parts of one constraint, in part order. */ + List answers(final String type, final OntologyShapeConstraint constraint) { + return compile(type, constraint).parts().stream().map(CompiledPart::outcome).toList(); + } + + /** The answer of a constraint that states one part and gets one answer. */ + OntologyPartOutcome answer(final String type, final OntologyShapeConstraint constraint) { + final List answers = answers(type, constraint); + if (answers.size() != 1) { + throw new AssertionError("Expected one answer and got " + answers); + } + return answers.getFirst(); + } + + /** The one test of a constraint that states one part and is checked on one table. */ + TableCheck check(final String type, final OntologyShapeConstraint constraint) { + if (answer(type, constraint) instanceof Check found && found.checks().size() == 1) { + return found.checks().getFirst(); + } + throw new AssertionError("Expected one check and got " + answer(type, constraint)); + } +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json new file mode 100644 index 000000000000..cb51d1208a9a --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json @@ -0,0 +1,218 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyShapeChecks.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyShapeChecks", + "description": "How each constraint of the shapes that target a class is checked on the tables the class binds. A constraint is answered part by part: by a data quality test that finds a violation exactly when a record breaks the part, by nothing because the mapping already holds it, or not at all, and then with the reason. Nothing is created, scheduled or run (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered).", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeChecks", + "definitions": { + "part": { + "description": "One part of a constraint. `range` is `minInclusive` and `maxInclusive` together.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyShapePart", + "enum": ["minCount", "maxCount", "class", "datatype", "range", "in", "pattern"] + }, + "outcome": { + "description": "How a part is checked. `check` carries the tests that check it. `heldByMapping` needs no test, because the table bindings already hold the part for every record. `notMapped` means the class binds the property in no column, or the version read has no such property. `notEnforceable` means no test finds exactly the records that break the part, and `reason` says why. `hidden` means the caller may not view a table the answer rests on.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckOutcome", + "enum": ["check", "heldByMapping", "notMapped", "notEnforceable", "hidden"] + }, + "reason": { + "description": "Why a part has no exact test. `noIdentityTable`: the class binds the property and has no identity table, so it has no records. `severalTables`: the class binds the property in several columns, and a count over all of them has no test. `boundOnInverse`: the class does not bind the relation and another class binds its inverse. `noJoin` and `joinNotConfirmed`: the relation has no join, or one that is only inferred. `notARelation` and `notADataProperty`: the part asks for the other kind of property. `targetClassNotOnJoin`: the class the part names has no identity table where the join arrives. `subclassOnJoinTable`: a subclass of that class has its identity table there too, and the filter of the class would leave its records out. `valuesAreRecords`: the list names records by IRI. `valueDoesNotFitColumn`: a value does not parse as the data type of the column. `tooManyValues`: the list has more than 1,000 values. `columnTypeNotSupported`: the data type of the column takes no such comparison. `datatypeNotSupported`: the datatype is not one this answer reads. `datatypeMismatch`: the column can hold a value that is not of the datatype. `patternNotPortable`: engines read the pattern in different ways. `tableNotSimple`: the test reads rows, and the rows of the table are not its records one for one. `columnMissing`: a column of the binding left the table. `otherDatabase`: a table sits in another database than the identity table. `engineNotSupported`: no statement is written for the service type.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckReason", + "enum": [ + "noIdentityTable", + "severalTables", + "boundOnInverse", + "noJoin", + "joinNotConfirmed", + "notARelation", + "notADataProperty", + "targetClassNotOnJoin", + "subclassOnJoinTable", + "valuesAreRecords", + "valueDoesNotFitColumn", + "tooManyValues", + "columnTypeNotSupported", + "datatypeNotSupported", + "datatypeMismatch", + "patternNotPortable", + "tableNotSimple", + "columnMissing", + "otherDatabase", + "engineNotSupported" + ] + }, + "readBinding": { + "description": "One table binding that a check was built from, with the binding revision of its class.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckBinding", + "properties": { + "conceptId": { + "description": "Id of the class that binds the table.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "assetId": { + "description": "Id of the bound table.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "revision": { + "description": "Revision of the bindings of the class, as the bindings endpoint returns it.", + "type": "integer", + "minimum": 0, + "existingJavaType": "java.lang.Long" + } + }, + "required": ["conceptId", "assetId", "revision"], + "additionalProperties": false + }, + "check": { + "description": "One data quality test on one table. `testDefinition`, `entityLink` and `parameterValues` are what a request to create a test case takes. The result of the test is 0 violations exactly when every record of the class satisfies the part.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheck", + "properties": { + "identity": { + "description": "Lowercase hex SHA-256 of the shape id, the constraint id, the part, the class id, the table id and the bound column path. It names the check and does not depend on a value of the constraint, so a changed bound keeps it.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "table": { + "description": "The table the test belongs to: the one whose binding holds the property, which is a link table when a link table holds a relation.", + "$ref": "../../type/entityReference.json" + }, + "columns": { + "description": "The columns of that table that hold the values the test reads: the bound column of a data property, or the columns of the join of a relation.", + "type": "array", + "items": { "$ref": "../../type/ontologyConceptBindings.json#/definitions/columnPath" }, + "default": [] + }, + "testDefinition": { + "description": "Fully qualified name of the test definition.", + "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "entityLink": { + "description": "The table, or the column of it, that the test is created on.", + "$ref": "../../type/basic.json#/definitions/entityLink" + }, + "parameterValues": { + "description": "The parameters of the test. A generated test carries its statement in `sqlExpression`, with every colon written as a backslash and a colon, and `strategy` `COUNT`, `operator` `<=` and `threshold` `0`. The statement returns one number, the records in violation.", + "type": "array", + "items": { "$ref": "../../tests/testCase.json#/definitions/testCaseParameterValue" }, + "default": [] + }, + "inspectionQuery": { + "description": "For a generated test, the statement that lists the keys of the records in violation, for a person to read. Absent on a test that needs no statement.", + "$ref": "../../type/basic.json#/definitions/sqlQuery" + }, + "readBindings": { + "description": "Every table binding the check read: the identity table of the class, the table that holds the property, and the identity table of the class a `class` part names. All revisions come from one consistent read.", + "type": "array", + "items": { "$ref": "#/definitions/readBinding" }, + "default": [] + } + }, + "required": [ + "identity", + "table", + "columns", + "testDefinition", + "entityLink", + "parameterValues", + "readBindings" + ], + "additionalProperties": false + }, + "checkedPart": { + "description": "How one part of a constraint is checked. When the class binds the property in several tables and they do not all give the same answer, the part has one entry for each answer.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyCheckedPart", + "properties": { + "part": { "$ref": "#/definitions/part" }, + "outcome": { "$ref": "#/definitions/outcome" }, + "reason": { + "description": "Present exactly when the outcome is `notEnforceable`.", + "$ref": "#/definitions/reason" + }, + "checks": { + "description": "One test for each table. Present exactly when the outcome is `check`.", + "type": "array", + "items": { "$ref": "#/definitions/check" }, + "default": null + } + }, + "required": ["part", "outcome"], + "additionalProperties": false + }, + "checkedConstraint": { + "description": "One constraint of a shape with the answer for each part it states.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyCheckedConstraint", + "properties": { + "id": { + "description": "Id of the constraint within its shape.", + "type": "string" + }, + "path": { + "description": "IRI of the property the constraint is about.", + "$ref": "../../type/ontologyIri.json" + }, + "parts": { + "description": "The parts the constraint states, in the order `minCount`, `maxCount`, `class`, `datatype`, `range`, `in`, `pattern`.", + "type": "array", + "items": { "$ref": "#/definitions/checkedPart" }, + "default": [] + } + }, + "required": ["id", "path", "parts"], + "additionalProperties": false + }, + "checkedShape": { + "description": "One shape that targets the class.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyCheckedShape", + "properties": { + "id": { + "description": "Id of the shape.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "name": { + "description": "Name of the shape.", + "$ref": "../../type/basic.json#/definitions/entityName" + }, + "severity": { "$ref": "../../entity/data/ontologyShape.json#/definitions/severity" }, + "constraints": { + "description": "The constraints of the shape, in the order the shape holds them.", + "type": "array", + "items": { "$ref": "#/definitions/checkedConstraint" }, + "default": [] + } + }, + "required": ["id", "name", "severity", "constraints"], + "additionalProperties": false + } + }, + "properties": { + "conceptId": { + "description": "Id of the class.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "classIri": { + "description": "IRI of the class.", + "$ref": "../../type/ontologyIri.json" + }, + "version": { + "description": "The version of the ontology that the class, its shapes and its properties were read from. Table bindings sit outside versions and are always current.", + "$ref": "ontologyStatementPlan.json#/definitions/versionRead" + }, + "shapes": { + "description": "The shapes of that version that target the class, in name order. A shape that targets a parent of the class is not listed.", + "type": "array", + "items": { "$ref": "#/definitions/checkedShape" }, + "default": [] + } + }, + "required": ["conceptId", "classIri", "version", "shapes"], + "additionalProperties": false +} From b6015eca26a0a44723d58f3850811c4852d0782f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 16:53:08 -0800 Subject: [PATCH 076/203] Write the queries of the generated shape checks A generated check gets two statements from one writer: the list of the keys of the records in violation, and the count of that list. Both start from the identity table of the class, keep only its records and count a record once, so the count is 0 exactly when every record satisfies the part. The golden files hold the count query of each part on each of the six mapping shapes for nine engine families. The test reads them and never writes one. --- .../ontology/OntologyConceptSqlGenerator.java | 4 +- .../service/ontology/OntologySelectText.java | 7 + .../ontology/OntologyShapeCheckSql.java | 250 +++++++++++++++++ .../service/ontology/sql/TypedStatement.java | 15 ++ .../OntologyShapeCheckCompilerTest.java | 72 +---- .../OntologyShapeCheckGoldenTest.java | 110 ++++++++ .../OntologyShapeCheckGoldenWriter.java | 45 ++++ .../ontology/OntologyShapeCheckGoldens.java | 174 ++++++++++++ .../ontology/OntologyShapeCheckModel.java | 79 ++++++ .../ontology/OntologyShapeCheckSqlTest.java | 254 ++++++++++++++++++ .../ontology/OntologyStatementGoldens.java | 2 +- .../ontology/sql/TypedStatementTest.java | 23 ++ .../columnRelation-orderTotal-range.sql | 7 + .../columnRelation-placedBy-class.sql | 9 + .../columnRelation-placedBy-maxCount.sql | 12 + .../columnRelation-placedBy-minCount.sql | 11 + .../bigquery/compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../compositeKey-accountTier-minCount.sql | 13 + .../filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../bigquery/linkTable-contains-class.sql | 10 + .../bigquery/linkTable-contains-maxCount.sql | 13 + .../bigquery/linkTable-contains-minCount.sql | 12 + .../bigquery/linkTable-itemQuantity-range.sql | 8 + .../bigquery/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + ...eatedContribution-addressCity-minCount.sql | 12 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + .../columnRelation-orderTotal-range.sql | 7 + .../columnRelation-placedBy-maxCount.sql | 12 + .../columnRelation-placedBy-minCount.sql | 11 + .../compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../linkTable-contains-maxCount.sql | 13 + .../linkTable-itemQuantity-range.sql | 8 + .../clickhouse/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + .../mysql/columnRelation-orderTotal-range.sql | 7 + .../mysql/columnRelation-placedBy-class.sql | 9 + .../columnRelation-placedBy-maxCount.sql | 12 + .../columnRelation-placedBy-minCount.sql | 11 + .../mysql/compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../compositeKey-accountTier-minCount.sql | 13 + .../mysql/filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../mysql/linkTable-contains-class.sql | 10 + .../mysql/linkTable-contains-maxCount.sql | 13 + .../mysql/linkTable-contains-minCount.sql | 12 + .../mysql/linkTable-itemQuantity-range.sql | 8 + .../mysql/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + ...eatedContribution-addressCity-minCount.sql | 12 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + .../columnRelation-orderTotal-range.sql | 7 + .../columnRelation-placedBy-class.sql | 9 + .../columnRelation-placedBy-maxCount.sql | 12 + .../columnRelation-placedBy-minCount.sql | 11 + .../postgres/compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../compositeKey-accountTier-minCount.sql | 13 + .../filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../postgres/linkTable-contains-class.sql | 10 + .../postgres/linkTable-contains-maxCount.sql | 13 + .../postgres/linkTable-contains-minCount.sql | 12 + .../postgres/linkTable-itemQuantity-range.sql | 8 + .../postgres/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + ...eatedContribution-addressCity-minCount.sql | 12 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + .../columnRelation-orderTotal-range.sql | 7 + .../columnRelation-placedBy-class.sql | 9 + .../columnRelation-placedBy-maxCount.sql | 12 + .../columnRelation-placedBy-minCount.sql | 11 + .../redshift/compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../compositeKey-accountTier-minCount.sql | 13 + .../filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../redshift/linkTable-contains-class.sql | 10 + .../redshift/linkTable-contains-maxCount.sql | 13 + .../redshift/linkTable-contains-minCount.sql | 12 + .../redshift/linkTable-itemQuantity-range.sql | 8 + .../redshift/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + ...eatedContribution-addressCity-minCount.sql | 12 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + .../columnRelation-orderTotal-range.sql | 7 + .../columnRelation-placedBy-class.sql | 9 + .../columnRelation-placedBy-maxCount.sql | 12 + .../columnRelation-placedBy-minCount.sql | 11 + .../snowflake/compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../compositeKey-accountTier-minCount.sql | 13 + .../filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../snowflake/linkTable-contains-class.sql | 10 + .../snowflake/linkTable-contains-maxCount.sql | 13 + .../snowflake/linkTable-contains-minCount.sql | 12 + .../linkTable-itemQuantity-range.sql | 8 + .../snowflake/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + ...eatedContribution-addressCity-minCount.sql | 12 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + .../spark/columnRelation-orderTotal-range.sql | 7 + .../spark/columnRelation-placedBy-class.sql | 9 + .../columnRelation-placedBy-maxCount.sql | 12 + .../columnRelation-placedBy-minCount.sql | 11 + .../spark/compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../compositeKey-accountTier-minCount.sql | 13 + .../spark/filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../spark/linkTable-contains-class.sql | 10 + .../spark/linkTable-contains-maxCount.sql | 13 + .../spark/linkTable-contains-minCount.sql | 12 + .../spark/linkTable-itemQuantity-range.sql | 8 + .../spark/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + ...eatedContribution-addressCity-minCount.sql | 12 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + .../trino/columnRelation-orderTotal-range.sql | 7 + .../trino/columnRelation-placedBy-class.sql | 9 + .../columnRelation-placedBy-maxCount.sql | 12 + .../columnRelation-placedBy-minCount.sql | 11 + .../trino/compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../compositeKey-accountTier-minCount.sql | 13 + .../trino/filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../trino/linkTable-contains-class.sql | 10 + .../trino/linkTable-contains-maxCount.sql | 13 + .../trino/linkTable-contains-minCount.sql | 12 + .../trino/linkTable-itemQuantity-range.sql | 8 + .../trino/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + ...eatedContribution-addressCity-minCount.sql | 12 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + .../tsql/columnRelation-orderTotal-range.sql | 7 + .../tsql/columnRelation-placedBy-class.sql | 9 + .../tsql/columnRelation-placedBy-maxCount.sql | 12 + .../tsql/columnRelation-placedBy-minCount.sql | 11 + .../tsql/compositeKey-accountTier-in.sql | 9 + .../compositeKey-accountTier-maxCount.sql | 14 + .../compositeKey-accountTier-minCount.sql | 13 + .../tsql/filteredIdentity-personName-in.sql | 8 + .../filteredIdentity-personName-maxCount.sql | 13 + .../filteredIdentity-personName-minCount.sql | 12 + .../tsql/linkTable-contains-class.sql | 10 + .../tsql/linkTable-contains-maxCount.sql | 13 + .../tsql/linkTable-contains-minCount.sql | 12 + .../tsql/linkTable-itemQuantity-range.sql | 8 + .../tsql/linkTable-orderChannel-in.sql | 7 + .../repeatedContribution-addressCity-in.sql | 8 + ...eatedContribution-addressCity-maxCount.sql | 13 + ...eatedContribution-addressCity-minCount.sql | 12 + .../unfilteredIdentity-customerEmail-in.sql | 7 + ...ilteredIdentity-customerEmail-maxCount.sql | 12 + ...ilteredIdentity-customerEmail-minCount.sql | 11 + 196 files changed, 2898 insertions(+), 70 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenWriter.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-orderTotal-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-class.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-itemQuantity-range.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-orderChannel-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-minCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-in.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-maxCount.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-minCount.sql diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index 5b98933baa22..1d00d9f9635c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -428,7 +428,7 @@ private static void chainFilters( } } - private static void equalColumns( + static void equalColumns( final TypedStatement.Builder on, final List pairs, final String previous, @@ -532,7 +532,7 @@ private static void joinLine(final OntologySelectText select, final Join join, f } } - private static String alias(final int index) { + static String alias(final int index) { return "t" + index; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java index f74bc889fa05..d6c8f2617456 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java @@ -62,6 +62,13 @@ OntologySelectText fromDistinct(final OntologyConceptQueryDialect dialect) { return new OntologySelectText(sql, dialect, lineBreak + NESTED_INDENT); } + /** A derived table after {@code FROM} that holds {@code inner}, indented, under {@code alias}. */ + void fromStatement(final TypedStatement inner, final String alias) { + sql.sql(lineBreak + "FROM (" + lineBreak + NESTED_INDENT); + sql.nested(inner, lineBreak + NESTED_INDENT); + closeDerived(alias); + } + /** Closes the derived table that {@link #fromDistinct} opened and names it. */ void closeDerived(final String alias) { sql.sql(lineBreak + ") " + alias); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java new file mode 100644 index 000000000000..8eb1577a4e30 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java @@ -0,0 +1,250 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.service.ontology.OntologyConceptSqlGenerator.alias; +import static org.openmetadata.service.ontology.OntologyConceptSqlGenerator.equalColumns; + +import java.util.List; +import org.openmetadata.service.ontology.OntologyCheckProbe.FewerValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.MoreValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.NoRecord; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideList; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; +import org.openmetadata.service.ontology.OntologyCheckProbe.Reach; +import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.sql.TypedStatement; + +/** + * Writes the statements of a generated test from its probe + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). One statement lists the keys of + * the records in violation, and the other counts the rows of that list. Both start from the + * identity table of the class and keep only its records, so a row that is no record is never + * counted, and a record is counted once however many rows hold it. + */ +final class OntologyShapeCheckSql { + private static final String IDENTITY = alias(0); + private static final String HOLDER = alias(1); + private static final String VALUES = "k"; + private static final String VIOLATIONS = "c"; + private static final String COUNT = "COUNT(*) AS violations"; + private static final String DISTINCT = "DISTINCT "; + private static final String INNER_JOIN = "JOIN"; + private static final String LEFT_JOIN = "LEFT JOIN"; + private static final String AND = " AND "; + private static final String IS_NOT_NULL = " IS NOT NULL"; + + private OntologyShapeCheckSql() {} + + /** + * The statements of one generated test. + * + * @param count one row with one number: the records in violation + * @param keys one row for each record in violation, with its key + */ + record Statements(TypedStatement count, TypedStatement keys) {} + + /** One list of keys while it is written. */ + private static final class Draft { + private final Reach reach; + private final TypedStatement.Builder sql = TypedStatement.builder(); + private final OntologySelectText select; + + /** The alias of the table that holds the property. */ + private final String holder; + + Draft(final Reach reach) { + this.reach = reach; + this.select = new OntologySelectText(sql, reach.family().dialect()); + this.holder = reach.joinsHolder() ? HOLDER : IDENTITY; + } + + List> key() { + return reach.identity().table().keyPaths(); + } + } + + static Statements write(final OntologyCheckProbe probe) { + final TypedStatement keys = keys(probe); + final TypedStatement.Builder count = TypedStatement.builder(); + final OntologySelectText select = + new OntologySelectText(count, probe.reach().family().dialect()); + select.selectAll().sql(COUNT); + select.fromStatement(keys, VIOLATIONS); + return new Statements(count.build(), keys); + } + + private static TypedStatement keys(final OntologyCheckProbe probe) { + final Draft draft = new Draft(probe.reach()); + switch (probe) { + case FewerValues fewer -> fewerValues(draft, fewer); + case MoreValues more -> moreValues(draft, more); + case OutsideList outside -> outsideList(draft, outside); + case OutsideRange outside -> outsideRange(draft, outside); + case NoRecord none -> noRecord(draft, none); + } + return draft.sql.build(); + } + + /** + * Every record is kept, with or without a row that holds a value, and a record has one row for + * each different value. A value is a row whose value columns are all non-null. + */ + private static void fewerValues(final Draft draft, final FewerValues probe) { + final OntologySelectText values = distinctValues(draft, probe.columns(), LEFT_JOIN); + records(values, draft); + final TypedStatement.Builder having = grouped(draft).sql("SUM(CASE WHEN "); + for (int index = 0; index < probe.columns().size(); index++) { + having.sql((index == 0 ? "" : AND) + VALUES + ".v" + index + IS_NOT_NULL); + } + having.sql(" THEN 1 ELSE 0 END) < " + probe.count()); + } + + /** Only the records with a value are kept, with one row for each different value. */ + private static void moreValues(final Draft draft, final MoreValues probe) { + final OntologySelectText values = distinctValues(draft, probe.columns(), INNER_JOIN); + records(values, draft); + probe.columns().forEach(column -> values.where().column(draft.holder, column).sql(IS_NOT_NULL)); + grouped(draft).sql("COUNT(*) > " + probe.count()); + } + + /** + * Opens the list of keys over a derived table of the different values of each record, and + * returns the writer of that table after its {@code FROM}. + */ + private static OntologySelectText distinctValues( + final Draft draft, final List> columns, final String join) { + keyList(draft.select.selectAll(), draft, false); + final OntologySelectText values = draft.select.fromDistinct(draft.reach.family().dialect()); + keyList(draft.sql, draft, true); + for (int index = 0; index < columns.size(); index++) { + draft.sql.sql(", ").column(draft.holder, columns.get(index)).sql(" AS v" + index); + } + from(values, draft, join); + return values; + } + + /** Closes the derived table of values and groups its rows by record, ready for the test. */ + private static TypedStatement.Builder grouped(final Draft draft) { + draft.select.closeDerived(VALUES); + keyList(draft.select.clause("GROUP BY"), draft, false); + return draft.select.clause("HAVING"); + } + + /** + * The key columns: read from the identity table and named {@code k0}, {@code k1} and so on, or + * read back under those names from the derived table of values. + */ + private static void keyList( + final TypedStatement.Builder sql, final Draft draft, final boolean fromIdentity) { + final List> key = draft.key(); + for (int part = 0; part < key.size(); part++) { + sql.sql(part == 0 ? "" : ", "); + if (fromIdentity) { + sql.column(IDENTITY, key.get(part)).sql(" AS k" + part); + } else { + sql.sql(VALUES + ".k" + part); + } + } + } + + private static void outsideList(final Draft draft, final OutsideList probe) { + final TypedStatement.Builder value = valueOfRecords(draft, probe.column()); + if (probe.allowed().isEmpty()) { + value.sql(IS_NOT_NULL); + } else { + value.sql(" NOT IN ").values(probe.allowed()); + } + } + + private static void outsideRange(final Draft draft, final OutsideRange probe) { + final boolean both = probe.min().isPresent() && probe.max().isPresent(); + final TypedStatement.Builder where = recordsWithHolder(draft).where().sql(both ? "(" : ""); + probe.min().ifPresent(min -> where.column(draft.holder, probe.column()).sql(" < ").value(min)); + where.sql(both ? " OR " : ""); + probe.max().ifPresent(max -> where.column(draft.holder, probe.column()).sql(" > ").value(max)); + where.sql(both ? ")" : ""); + } + + /** The keys of the records, ready for a test of one column of the table that holds it. */ + private static TypedStatement.Builder valueOfRecords( + final Draft draft, final List column) { + return recordsWithHolder(draft).where().column(draft.holder, column); + } + + /** The different keys of the records, each joined to the rows that hold the property. */ + private static OntologySelectText recordsWithHolder(final Draft draft) { + keyList(draft.select.selectAll().sql(DISTINCT), draft, true); + from(draft.select, draft, INNER_JOIN); + records(draft.select, draft); + return draft.select; + } + + /** + * A value that no record of the target class has: the join onto the identity table of that + * class finds no row that its row filter keeps and whose key holds no null. + */ + private static void noRecord(final Draft draft, final NoRecord probe) { + final String target = alias(draft.reach.joinsHolder() ? 2 : 1); + keyList(draft.select.selectAll().sql(DISTINCT), draft, true); + from(draft.select, draft, INNER_JOIN); + targetRecords(draft, probe, target); + records(draft.select, draft); + probe + .on() + .forEach( + pair -> draft.select.where().column(draft.holder, pair.previous()).sql(IS_NOT_NULL)); + draft.select.where().column(target, probe.on().getFirst().joined()).sql(" IS NULL"); + } + + private static void targetRecords(final Draft draft, final NoRecord probe, final String alias) { + final ReadTable target = probe.target(); + final TypedStatement.Builder on = + draft.select.join(LEFT_JOIN, target.table().fullyQualifiedName(), alias); + equalColumns(on, probe.on(), draft.holder, alias); + if (target.filter() != null) { + target.filter().appendTo(on.sql(AND), alias); + } + final List> joined = probe.on().stream().map(JoinPair::joined).toList(); + // A key column that the join compares is non-null in every row the join finds. + target.table().keyPaths().stream() + .filter(part -> !joined.contains(part)) + .forEach(part -> on.sql(AND).column(alias, part).sql(IS_NOT_NULL)); + } + + /** The identity table, then the table that holds the property when that is another table. */ + private static void from(final OntologySelectText select, final Draft draft, final String join) { + final Reach reach = draft.reach; + select.from(reach.identity().table().fullyQualifiedName(), IDENTITY); + if (reach.joinsHolder()) { + final ReadTable holder = reach.holder(); + final TypedStatement.Builder on = + select.join(join, holder.table().fullyQualifiedName(), HOLDER); + equalColumns(on, reach.keyPairs(), IDENTITY, HOLDER); + if (holder.filter() != null) { + holder.filter().appendTo(on.sql(AND), HOLDER); + } + } + } + + /** Only the rows of the identity table that are records. */ + private static void records(final OntologySelectText select, final Draft draft) { + final ReadTable identity = draft.reach.identity(); + draft.key().forEach(part -> select.where().column(IDENTITY, part).sql(IS_NOT_NULL)); + if (identity.filter() != null) { + identity.filter().appendTo(select.where(), IDENTITY); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java index 7e08e8f4458d..6260feff983a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java @@ -116,6 +116,21 @@ public Builder contains(final TypedValue text) { return this; } + /** + * Every part of {@code inner}, as a statement inside this one. Each line of the inner + * statement starts where {@code lineBreak} ends, so a nested statement reads as nested. + */ + public Builder nested(final TypedStatement inner, final String lineBreak) { + for (final Part part : inner.parts) { + if (part instanceof Part.Sql written) { + sql(written.text().replace("\n", lineBreak)); + } else { + parts.add(part); + } + } + return this; + } + public TypedStatement build() { return new TypedStatement(parts); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java index 72a66f78c458..f1df0f0239a6 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java @@ -25,10 +25,12 @@ import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; import static org.openmetadata.service.ontology.OntologyMappingShapes.contributing; import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; -import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; -import static org.openmetadata.service.ontology.OntologyMappingShapes.relation; import static org.openmetadata.service.ontology.OntologyMappingShapes.table; -import static org.openmetadata.service.ontology.OntologyMappingShapes.text; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.FILTERED_TARGET; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.TWO_COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literal; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; import java.net.URI; import java.util.List; @@ -55,7 +57,6 @@ import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; -import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; import org.openmetadata.service.ontology.OntologyPartOutcome.Check; @@ -78,57 +79,6 @@ class OntologyShapeCheckCompilerTest { private static final String EMAIL_LINK = "<#E::table::warehouse.sales.shop.customers::columns::email>"; - /** A shipment names its account with two columns, the two-column key of the account table. */ - private static final Shape TWO_COLUMN_RELATION = - new Shape( - "twoColumnRelation", - List.of( - table("shipments", List.of(integer("id"), text("tenant"), integer("customer"))), - table( - "crm_customers", - List.of(text("tenant_id"), integer("customer_id"), text("name")))), - List.of("Shipment", "Account"), - List.of(relation("shippedTo", "Shipment", "Account")), - List.of( - identity( - "Shipment", - "shipments", - List.of("id"), - null, - new ColumnBindingSpec( - "shippedTo", - "tenant", - new JoinSpec( - "crm_customers", - OntologyJoinStatus.CONFIRMED, - List.of("tenant", "customer"), - List.of("tenant_id", "customer_id")))), - identity("Account", "crm_customers", List.of("tenant_id", "customer_id"), null)), - List.of()); - - /** A membership is held by a person, and people share a filtered table with other parties. */ - private static final Shape FILTERED_TARGET = - new Shape( - "filteredTarget", - List.of( - table("parties", List.of(integer("id"), text("kind"), text("name"))), - table("memberships", List.of(integer("id"), integer("party_id")))), - List.of("Membership", "Person"), - List.of(relation("heldBy", "Membership", "Person")), - List.of( - identity( - "Person", - "parties", - List.of("id"), - new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person")), - identity( - "Membership", - "memberships", - List.of("id"), - null, - OntologyMappingShapes.joined("heldBy", "party_id", "parties", "id"))), - List.of()); - private static OntologyShapeCheckModel customers() { return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, POSTGRES); } @@ -160,18 +110,6 @@ private static OntologyShapeCheckModel nameInTwoTables() { bound("customerName", "city")))); } - private static OntologyShapeValue literal(final String value) { - return new OntologyShapeValue().withLiteral(new OntologyLiteral().withValue(value)); - } - - private static List literals(final String... values) { - return List.of(values).stream().map(OntologyShapeCheckCompilerTest::literal).toList(); - } - - private static OntologyLiteral limit(final String value) { - return new OntologyLiteral().withValue(value); - } - private static TestCaseParameterValue parameter(final String name, final String value) { return new TestCaseParameterValue().withName(name).withValue(value); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java new file mode 100644 index 000000000000..c90fe107223b --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java @@ -0,0 +1,110 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; +import org.openmetadata.service.ontology.OntologyShapeCheckGoldens.Golden; + +/** + * Holds every generated shape check to the SQL text that a person read and committed: nine engine + * families, the six mapping shapes and each part that compiles to a query. The test reads the + * files and never writes one. + */ +class OntologyShapeCheckGoldenTest { + private static final int FAMILIES = 9; + private static final int PARTS_OF_THE_SHAPES = 21; + private static final List NOT_WRITTEN_FOR_CLICKHOUSE = + List.of( + "columnRelation-placedBy-class", + "compositeKey-accountTier-minCount", + "linkTable-contains-class", + "linkTable-contains-minCount", + "repeatedContribution-addressCity-minCount"); + + static List goldens() { + return OntologyShapeCheckGoldens.all(); + } + + @ParameterizedTest + @MethodSource("goldens") + void aCountQueryIsTheTextOfItsGoldenFile(final Golden golden) throws IOException { + try (InputStream file = + OntologyShapeCheckGoldenTest.class.getResourceAsStream("/" + golden.resource())) { + assertNotNull(file, "No golden file " + golden.resource()); + assertEquals(new String(file.readAllBytes(), StandardCharsets.UTF_8), golden.text()); + } + } + + @ParameterizedTest + @MethodSource("goldens") + void aCountQueryCountsTheRowsOfTheKeyList(final Golden golden) { + assertEquals( + "SELECT COUNT(*) AS violations\nFROM (\n " + + golden.keys().replace("\n", "\n ") + + "\n) c\n", + golden.text()); + } + + @Test + void everyGoldenFileBelongsToACheck() throws IOException, URISyntaxException { + final Path directory = + Path.of( + OntologyShapeCheckGoldenTest.class + .getResource("/" + OntologyShapeCheckGoldens.DIRECTORY) + .toURI()); + try (Stream files = Files.walk(directory)) { + assertEquals( + goldens().stream().map(Golden::resource).sorted().toList(), + files + .filter(Files::isRegularFile) + .map(file -> OntologyShapeCheckGoldens.DIRECTORY + "/" + directory.relativize(file)) + .map(path -> path.replace('\\', '/')) + .sorted() + .toList()); + } + assertEquals( + FAMILIES * PARTS_OF_THE_SHAPES - NOT_WRITTEN_FOR_CLICKHOUSE.size(), goldens().size()); + } + + @Test + void aPartWithNoQueryIsOneThatKeepsUnmatchedRowsOnClickHouse() { + final List refused = + OntologyShapeCheckGoldens.asked().stream().filter(golden -> !golden.isGenerated()).toList(); + assertEquals( + NOT_WRITTEN_FOR_CLICKHOUSE.stream() + .map(name -> OntologyShapeCheckGoldens.DIRECTORY + "/clickhouse/" + name + ".sql") + .toList(), + refused.stream().map(Golden::resource).sorted().toList()); + refused.forEach( + golden -> + assertEquals( + new NotEnforceable(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + golden.answer(), + golden.resource())); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenWriter.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenWriter.java new file mode 100644 index 000000000000..76bf6a042fae --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenWriter.java @@ -0,0 +1,45 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.openmetadata.service.ontology.OntologyShapeCheckGoldens.Golden; + +/** + * Writes the golden SQL files of the generated shape checks that do not exist yet. It never + * replaces a file: to write one again, delete it, run this class with the system property below, + * and read the new text before committing it. No test run starts this class, because its name + * matches no test pattern and it needs the property. + */ +class OntologyShapeCheckGoldenWriter { + @Test + @EnabledIfSystemProperty(named = "ontology.shapeCheck.goldens", matches = "write") + void writesTheGoldensThatDoNotExist() throws IOException { + final Path resources = Path.of(System.getProperty("basedir", "."), "src", "test", "resources"); + assertTrue(Files.isDirectory(resources), "Run it from the openmetadata-service module"); + for (final Golden golden : OntologyShapeCheckGoldens.all()) { + final Path file = resources.resolve(golden.resource()); + if (Files.notExists(file)) { + Files.createDirectories(file.getParent()); + Files.writeString(file, golden.text(), StandardOpenOption.CREATE_NEW); + } + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java new file mode 100644 index 000000000000..7cfe8a10733f --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java @@ -0,0 +1,174 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.ontology; + +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.function.UnaryOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test.Generated; +import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * The golden SQL of the generated shape checks: one file for each engine family, mapping shape + * and part that compiles to a query there. {@link OntologyShapeCheckGoldenWriter} writes a file + * that does not exist yet, and {@link OntologyShapeCheckGoldenTest} only reads them. + */ +final class OntologyShapeCheckGoldens { + static final String DIRECTORY = "ontology/shape-checks"; + + private OntologyShapeCheckGoldens() {} + + /** + * One part of a constraint on one property of a class of a shape. + * + * @param part the name of the part, as the file name holds it + * @param states what the constraint states for that part + */ + record Asked( + Shape shape, + String type, + String property, + String part, + UnaryOperator states) { + String name() { + return shape.name() + "-" + property + "-" + part; + } + } + + /** One part as one engine family checks it. */ + record Golden(SqlEngineFamily family, Asked asked) { + /** The path of the file under the test resources. */ + String resource() { + return String.format( + "%s/%s/%s.sql", DIRECTORY, family.name().toLowerCase(Locale.ROOT), asked.name()); + } + + OntologyPartOutcome answer() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel( + asked.shape(), OntologyStatementGoldens.SERVICE_TYPES.get(family)); + return model.answer(asked.type(), asked.states().apply(model.on(asked.property()))); + } + + boolean isGenerated() { + return answer() instanceof OntologyPartOutcome.Check; + } + + /** The text of the file: the count query for a person to read, and a line break. */ + String text() { + return family.finish(statements().count()).sql() + "\n"; + } + + /** The query that lists the keys of the records in violation. */ + String keys() { + return family.finish(statements().keys()).sql(); + } + + private Statements statements() { + final OntologyPartOutcome.Check check = (OntologyPartOutcome.Check) answer(); + final Generated generated = (Generated) check.checks().getFirst().test(); + return OntologyShapeCheckSql.write(generated.probe()); + } + + @Override + public String toString() { + return resource(); + } + } + + /** Every part of every shape on every family, whether or not it compiles to a query there. */ + static List asked() { + final List goldens = new ArrayList<>(); + for (final SqlEngineFamily family : OntologyStatementGoldens.SERVICE_TYPES.keySet()) { + parts().forEach(asked -> goldens.add(new Golden(family, asked))); + } + return goldens; + } + + /** The parts that compile to a query, each of which has a golden file. */ + static List all() { + return asked().stream().filter(Golden::isGenerated).toList(); + } + + /** The parts that a query checks, for each of the six mapping shapes. */ + static List parts() { + final List parts = new ArrayList<>(); + parts.addAll(valueParts(UNFILTERED_IDENTITY, "Customer", "customerEmail", 1)); + parts.addAll(valueParts(FILTERED_IDENTITY, "Person", "personName", 1)); + parts.addAll(valueParts(COMPOSITE_KEY, "Account", "accountTier", 1)); + parts.addAll(valueParts(REPEATED_CONTRIBUTION, "Customer", "addressCity", 2)); + parts.addAll(relationParts(COLUMN_RELATION, "placedBy", "Customer")); + parts.add( + new Asked( + COLUMN_RELATION, + "Order", + "orderTotal", + "range", + constraint -> + constraint.withMinInclusive(limit("0")).withMaxInclusive(limit("100.50")))); + parts.addAll(relationParts(LINK_TABLE, "contains", "Product")); + parts.add( + new Asked( + LINK_TABLE, + "Order", + "itemQuantity", + "range", + constraint -> constraint.withMinInclusive(limit("1")))); + parts.add( + new Asked( + LINK_TABLE, + "Order", + "orderChannel", + "in", + constraint -> constraint.withIn(literals("web", "store")))); + return List.copyOf(parts); + } + + /** The counts and the list of a text property. */ + private static List valueParts( + final Shape shape, final String type, final String property, final int count) { + return List.of( + new Asked(shape, type, property, "minCount", constraint -> constraint.withMinCount(count)), + new Asked(shape, type, property, "maxCount", constraint -> constraint.withMaxCount(count)), + new Asked( + shape, type, property, "in", constraint -> constraint.withIn(literals("a", "b")))); + } + + /** The counts of a relation of the order class, and the class its values must be records of. */ + private static List relationParts( + final Shape shape, final String relation, final String target) { + final String type = "Order"; + return List.of( + new Asked(shape, type, relation, "minCount", constraint -> constraint.withMinCount(1)), + new Asked(shape, type, relation, "maxCount", constraint -> constraint.withMaxCount(1)), + new Asked( + shape, + type, + relation, + "class", + constraint -> constraint.withClassIri(shape.iri(target)))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java index b67eafe3445f..2516a274972e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java @@ -13,6 +13,13 @@ package org.openmetadata.service.ontology; +import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; +import static org.openmetadata.service.ontology.OntologyMappingShapes.joined; +import static org.openmetadata.service.ontology.OntologyMappingShapes.relation; +import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; + import java.net.URI; import java.util.ArrayList; import java.util.HashMap; @@ -26,13 +33,20 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.ontology.OntologyMappingReader.Bindings; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; import org.openmetadata.service.ontology.OntologyPartOutcome.Check; import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; @@ -48,6 +62,58 @@ */ final class OntologyShapeCheckModel { static final String CONSTRAINT_ID = "c1"; + + /** A shipment names its account with two columns, the two-column key of the account table. */ + static final Shape TWO_COLUMN_RELATION = + new Shape( + "twoColumnRelation", + List.of( + table("shipments", List.of(integer("id"), text("tenant"), integer("customer"))), + table( + "crm_customers", + List.of(text("tenant_id"), integer("customer_id"), text("name")))), + List.of("Shipment", "Account"), + List.of(relation("shippedTo", "Shipment", "Account")), + List.of( + identity( + "Shipment", + "shipments", + List.of("id"), + null, + new ColumnBindingSpec( + "shippedTo", + "tenant", + new JoinSpec( + "crm_customers", + OntologyJoinStatus.CONFIRMED, + List.of("tenant", "customer"), + List.of("tenant_id", "customer_id")))), + identity("Account", "crm_customers", List.of("tenant_id", "customer_id"), null)), + List.of()); + + /** A membership is held by a person, and people share a filtered table with other parties. */ + static final Shape FILTERED_TARGET = + new Shape( + "filteredTarget", + List.of( + table("parties", List.of(integer("id"), text("kind"), text("name"))), + table("memberships", List.of(integer("id"), integer("party_id")))), + List.of("Membership", "Person"), + List.of(relation("heldBy", "Membership", "Person")), + List.of( + identity( + "Person", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person")), + identity( + "Membership", + "memberships", + List.of("id"), + null, + joined("heldBy", "party_id", "parties", "id"))), + List.of()); + private final Shape shape; private final OntologyMappingShapeModel mapping; private final Set boundOnInverse = new HashSet<>(); @@ -63,6 +129,19 @@ final class OntologyShapeCheckModel { this.mapping = new OntologyMappingShapeModel(shape, serviceType, bindings); } + static OntologyShapeValue literal(final String value) { + return new OntologyShapeValue().withLiteral(limit(value)); + } + + static List literals(final String... values) { + return List.of(values).stream().map(OntologyShapeCheckModel::literal).toList(); + } + + /** A literal with no datatype, as a bound of a range or a member of a list. */ + static OntologyLiteral limit(final String value) { + return new OntologyLiteral().withValue(value); + } + /** The tables and binding rows under the facts. A test changes a table through it. */ OntologyMappingShapeModel mapping() { return mapping; diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java new file mode 100644 index 000000000000..f2840f129d49 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java @@ -0,0 +1,254 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; +import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; +import static org.openmetadata.service.ontology.OntologyMappingShapes.relation; +import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.FILTERED_TARGET; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.TWO_COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test.Generated; +import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * The text of the generated shape checks that the golden files of the six mapping shapes do not + * hold: a join of several columns, a filtered table on the far side of a join, a bound on one side + * and a list with no member. + */ +class OntologyShapeCheckSqlTest { + private static final String POSTGRES = "Postgres"; + + /** An order names its customer by email, which is not the key of the customer table. */ + private static final Shape JOIN_OFF_THE_KEY = + new Shape( + "joinOffTheKey", + List.of( + table("customers", List.of(integer("id"), text("email"))), + table("orders", List.of(integer("id"), text("customer_email")))), + List.of("Order", "Customer"), + List.of(relation("placedBy", "Order", "Customer")), + List.of( + identity("Customer", "customers", List.of("id"), null), + identity( + "Order", + "orders", + List.of("id"), + null, + new ColumnBindingSpec( + "placedBy", + "customer_email", + new JoinSpec( + "customers", + OntologyJoinStatus.CONFIRMED, + List.of("customer_email"), + List.of("email"))))), + List.of()); + + private static String keys( + final OntologyShapeCheckModel model, final String type, final OntologyShapeConstraint part) { + return SqlEngineFamily.POSTGRES.finish(statements(model, type, part).keys()).sql(); + } + + private static Statements statements( + final OntologyShapeCheckModel model, final String type, final OntologyShapeConstraint part) { + final Generated generated = (Generated) model.check(type, part).test(); + return OntologyShapeCheckSql.write(generated.probe()); + } + + private static OntologyShapeCheckModel shape(final Shape shape) { + return new OntologyShapeCheckModel(shape, POSTGRES); + } + + /** The addresses of the customers with a row filter on the table that holds them. */ + private static OntologyShapeCheckModel filteredAddresses() { + return new OntologyShapeCheckModel( + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + identity("Customer", "customers", List.of("id"), null, bound("customerName", "name")), + new BindingSpec( + "Customer", + "customer_addresses", + OntologyBindingRole.CONTRIBUTING, + List.of("customer_id"), + new FilterSpec("country", OntologyRowFilterOperator.NOT_EQUALS, "XX"), + List.of(bound("addressCity", "city"))))); + } + + @Test + void classOverAJoinOfTwoColumnsComparesBothAndAsksBothForAValue() { + final OntologyShapeCheckModel model = shape(TWO_COLUMN_RELATION); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.shipments t0 + LEFT JOIN shop.crm_customers t1 ON t1.tenant_id = t0.tenant AND t1.customer_id = t0.customer + WHERE t0.id IS NOT NULL + AND t0.tenant IS NOT NULL + AND t0.customer IS NOT NULL + AND t1.tenant_id IS NULL""", + keys( + model, + "Shipment", + model.on("shippedTo").withClassIri(TWO_COLUMN_RELATION.iri("Account")))); + } + + @Test + void minCountOfARelationOfTwoColumnsCountsTheRowsWhereBothHoldAValue() { + final OntologyShapeCheckModel model = shape(TWO_COLUMN_RELATION); + assertEquals( + """ + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.tenant AS v0, t0.customer AS v1 + FROM shop.shipments t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL AND k.v1 IS NOT NULL THEN 1 ELSE 0 END) < 1""", + keys(model, "Shipment", model.on("shippedTo").withMinCount(1))); + } + + @Test + void classCarriesTheRowFilterOfTheClassItsValuesMustBeRecordsOf() { + final OntologyShapeCheckModel model = shape(FILTERED_TARGET); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.memberships t0 + LEFT JOIN shop.parties t1 ON t1.id = t0.party_id AND t1.kind = 'person' + WHERE t0.id IS NOT NULL + AND t0.party_id IS NOT NULL + AND t1.id IS NULL""", + keys(model, "Membership", model.on("heldBy").withClassIri(FILTERED_TARGET.iri("Person")))); + } + + @Test + void classOverAJoinOffTheKeyAsksTheKeyOfTheFoundRowForAValue() { + final OntologyShapeCheckModel model = shape(JOIN_OFF_THE_KEY); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + LEFT JOIN shop.customers t1 ON t1.email = t0.customer_email AND t1.id IS NOT NULL + WHERE t0.id IS NOT NULL + AND t0.customer_email IS NOT NULL + AND t1.email IS NULL""", + keys(model, "Order", model.on("placedBy").withClassIri(JOIN_OFF_THE_KEY.iri("Customer")))); + } + + @Test + void rangeWithOnlyAnUpperBoundComparesOnce() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.total > 100""", + keys(model, "Order", model.on("orderTotal").withMaxInclusive(limit("100")))); + } + + @Test + void listWithNoMemberIsBrokenByEveryValue() { + final OntologyShapeCheckModel model = shape(UNFILTERED_IDENTITY); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL""", + keys(model, "Customer", model.on("customerEmail").withIn(List.of()))); + } + + @Test + void maxCountZeroFindsEveryRecordWithAValue() { + final OntologyShapeCheckModel model = shape(UNFILTERED_IDENTITY); + assertEquals( + """ + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 0""", + keys(model, "Customer", model.on("customerEmail").withMaxCount(0))); + } + + @Test + void rowFilterOfATableThatHoldsThePropertyIsPartOfItsJoin() { + final OntologyShapeCheckModel model = filteredAddresses(); + assertEquals( + """ + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id AND t1.country <> 'XX' + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1""", + keys(model, "Customer", model.on("addressCity").withMinCount(1))); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id AND t1.country <> 'XX' + WHERE t0.id IS NOT NULL + AND t1.city NOT IN ('London')""", + keys(model, "Customer", model.on("addressCity").withIn(literals("London")))); + } + + @Test + void countQueryHoldsTheKeyListAndNothingThatOrdersOrLimitsIt() { + final OntologyShapeCheckModel model = new OntologyShapeCheckModel(COLUMN_RELATION, "Mssql"); + final Statements statements = + statements(model, "Order", model.on("orderTotal").withMinInclusive(limit("0"))); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[total] < 0 + ) c""", + SqlEngineFamily.TSQL.finish(statements.count()).sql()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java index 7b4ed8e45ab6..0b10fb7a5170 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java @@ -33,7 +33,7 @@ final class OntologyStatementGoldens { static final String DIRECTORY = OntologyMappingShapes.GOLDEN_STATEMENTS; /** The service type whose statements stand for its engine family. */ - private static final Map SERVICE_TYPES = serviceTypes(); + static final Map SERVICE_TYPES = serviceTypes(); private OntologyStatementGoldens() {} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java index 0bc0159ce3c8..59a36565d795 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java @@ -73,6 +73,29 @@ void aNameThatHoldsAControlCharacterIsRefusedWhenTheStatementIsBuilt(final Strin assertEquals(400, refusal.getResponse().getStatus()); } + @Test + void aNestedStatementIndentsItsLinesAndKeepsItsNamesAndValues() { + final Column note = new Column().withName("note").withDataType(ColumnDataType.VARCHAR); + final TypedStatement inner = + TypedStatement.builder() + .sql("SELECT t0.id\nFROM x t0\nWHERE ") + .column("t0", List.of("note")) + .sql(" = ") + .value(TypedValues.value(note, "a b")) + .build(); + + assertEquals( + "SELECT COUNT(*)\nFROM (\n SELECT t0.id\n FROM x t0\n WHERE t0.note = 'a b'\n) c", + SqlEngineFamily.TRINO + .finish( + TypedStatement.builder() + .sql("SELECT COUNT(*)\nFROM (\n ") + .nested(inner, "\n ") + .sql("\n) c") + .build()) + .sql()); + } + @Test void aColumnIsItsAliasAndEachSegmentOfItsPathAsAName() { assertEquals( diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..1d73a27d81e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND (t0.`total` < 0 OR t0.`total` > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..1872950eb8dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`id` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..808ce2a45354 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..e8ba12c522f7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..7c7d69698321 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..697bc219f126 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..068ea33528ad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..8e7b1685b7a9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..52be2b6fcd02 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6f2c6387e28a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-class.sql new file mode 100644 index 000000000000..16eabdcfe8f8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + LEFT JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + AND t2.`sku` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..ee5641bff7e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..893f5946b728 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..705f31232957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`quantity` < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..a0b9ef55ac3d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`channel` NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..175572d640ce --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..79a6a85a0798 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..49196ce3ee90 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..ff8d659ee01d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..6099ce177166 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..01056703deae --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..1d73a27d81e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND (t0.`total` < 0 OR t0.`total` > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..808ce2a45354 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..e8ba12c522f7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..7c7d69698321 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..697bc219f126 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..8e7b1685b7a9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..52be2b6fcd02 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6f2c6387e28a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..ee5641bff7e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..705f31232957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`quantity` < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..a0b9ef55ac3d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`channel` NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..175572d640ce --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..79a6a85a0798 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..ff8d659ee01d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..6099ce177166 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..01056703deae --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..1d73a27d81e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND (t0.`total` < 0 OR t0.`total` > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..1872950eb8dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`id` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..808ce2a45354 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..e8ba12c522f7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..7c7d69698321 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..697bc219f126 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..068ea33528ad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..8e7b1685b7a9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..52be2b6fcd02 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6f2c6387e28a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-class.sql new file mode 100644 index 000000000000..16eabdcfe8f8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + LEFT JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + AND t2.`sku` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..ee5641bff7e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..893f5946b728 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..705f31232957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`quantity` < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..a0b9ef55ac3d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`channel` NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..175572d640ce --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..79a6a85a0798 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..49196ce3ee90 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..ff8d659ee01d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..6099ce177166 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..01056703deae --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..0424efab4920 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND (t0.total < 0 OR t0.total > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..e8b526e25b83 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + LEFT JOIN shop.customers t1 ON t1.id = t0.customer_id + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.id IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..ca0de2e9e236 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..f6df07377880 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..a0a8702e4ad4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..c5fd69b43c18 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..783fe4c0a7c9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..3b59b222c3c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..ee64c4d60a6a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6e9bc87dd775 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-class.sql new file mode 100644 index 000000000000..ceab9398db9a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + LEFT JOIN shop.products t2 ON t2.sku = t1.product_sku + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + AND t2.sku IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..13d702c9be7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..7cb768754e5f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..d3ebc94092bb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.quantity < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..741fa3a54ae8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.channel NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..c3bc8bfd4570 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..dbbfbf1c9562 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..e62692145e27 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..e5e6417bd8b3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..1651cc3a9726 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..134119552105 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..0424efab4920 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND (t0.total < 0 OR t0.total > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..e8b526e25b83 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + LEFT JOIN shop.customers t1 ON t1.id = t0.customer_id + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.id IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..ca0de2e9e236 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..f6df07377880 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..a0a8702e4ad4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..c5fd69b43c18 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..783fe4c0a7c9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..3b59b222c3c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..ee64c4d60a6a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6e9bc87dd775 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-class.sql new file mode 100644 index 000000000000..ceab9398db9a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + LEFT JOIN shop.products t2 ON t2.sku = t1.product_sku + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + AND t2.sku IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..13d702c9be7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..7cb768754e5f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..d3ebc94092bb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.quantity < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..741fa3a54ae8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.channel NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..c3bc8bfd4570 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..dbbfbf1c9562 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..e62692145e27 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..e5e6417bd8b3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..1651cc3a9726 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..134119552105 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..0a95cedfa6a2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + AND (t0."total" < 0 OR t0."total" > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..1214f1bcd739 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + LEFT JOIN "shop"."customers" t1 ON t1."id" = t0."customer_id" + WHERE t0."id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + AND t1."id" IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..8d78e30cbf0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."customer_id" AS v0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..2d784e1d3711 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."customer_id" AS v0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..33784973dd20 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."customer_id" AS k1 + FROM "shop"."crm_customers" t0 + JOIN "shop"."crm_customer_profile" t1 ON t1."tenant" = t0."tenant_id" AND t1."customer" = t0."customer_id" + WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + AND t1."tier" NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..d921104b6824 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."customer_id" AS k1, t1."tier" AS v0 + FROM "shop"."crm_customers" t0 + JOIN "shop"."crm_customer_profile" t1 ON t1."tenant" = t0."tenant_id" AND t1."customer" = t0."customer_id" + WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + AND t1."tier" IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..b673ef120e81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."customer_id" AS k1, t1."tier" AS v0 + FROM "shop"."crm_customers" t0 + LEFT JOIN "shop"."crm_customer_profile" t1 ON t1."tenant" = t0."tenant_id" AND t1."customer" = t0."customer_id" + WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..4c68226a8ef9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + AND t0."name" NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..374bc85ecd26 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."name" AS v0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + AND t0."name" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..15158e99d787 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."name" AS v0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-class.sql new file mode 100644 index 000000000000..ca421c084a7b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + LEFT JOIN "shop"."products" t2 ON t2."sku" = t1."product_sku" + WHERE t0."id" IS NOT NULL + AND t1."product_sku" IS NOT NULL + AND t2."sku" IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..4f9b6d9f50cc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t1."product_sku" AS v0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."product_sku" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..a378cd7d7e3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t1."product_sku" AS v0 + FROM "shop"."orders" t0 + LEFT JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..241bcb990638 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."quantity" < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..5c334b22eec4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + AND t0."channel" NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..70192d7dc05e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."customers" t0 + JOIN "shop"."customer_addresses" t1 ON t1."customer_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."city" NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..aca3068ba3d6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t1."city" AS v0 + FROM "shop"."customers" t0 + JOIN "shop"."customer_addresses" t1 ON t1."customer_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."city" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..c5c3ae499ed2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t1."city" AS v0 + FROM "shop"."customers" t0 + LEFT JOIN "shop"."customer_addresses" t1 ON t1."customer_id" = t0."id" + WHERE t0."id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..998436d538a7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."customers" t0 + WHERE t0."id" IS NOT NULL + AND t0."email" NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..724ca54fd8c0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."email" AS v0 + FROM "shop"."customers" t0 + WHERE t0."id" IS NOT NULL + AND t0."email" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..bf982a855cd2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."email" AS v0 + FROM "shop"."customers" t0 + WHERE t0."id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..1d73a27d81e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND (t0.`total` < 0 OR t0.`total` > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..1872950eb8dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`id` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..808ce2a45354 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..e8ba12c522f7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..7c7d69698321 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..697bc219f126 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..068ea33528ad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..8e7b1685b7a9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..52be2b6fcd02 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6f2c6387e28a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-class.sql new file mode 100644 index 000000000000..16eabdcfe8f8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + LEFT JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + AND t2.`sku` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..ee5641bff7e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..893f5946b728 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..705f31232957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`quantity` < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..a0b9ef55ac3d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`channel` NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..175572d640ce --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..79a6a85a0798 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..49196ce3ee90 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..ff8d659ee01d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..6099ce177166 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..01056703deae --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..0424efab4920 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND (t0.total < 0 OR t0.total > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..e8b526e25b83 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + LEFT JOIN shop.customers t1 ON t1.id = t0.customer_id + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.id IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..ca0de2e9e236 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..f6df07377880 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..a0a8702e4ad4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..c5fd69b43c18 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..783fe4c0a7c9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..3b59b222c3c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..ee64c4d60a6a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6e9bc87dd775 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-class.sql new file mode 100644 index 000000000000..ceab9398db9a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + LEFT JOIN shop.products t2 ON t2.sku = t1.product_sku + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + AND t2.sku IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..13d702c9be7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..7cb768754e5f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..d3ebc94092bb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.quantity < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..741fa3a54ae8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.channel NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..c3bc8bfd4570 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..dbbfbf1c9562 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..e62692145e27 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..e5e6417bd8b3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..1651cc3a9726 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..134119552105 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..b87f095c8a04 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND (t0.[total] < 0 OR t0.[total] > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..73882b6e7d84 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + LEFT JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id] + WHERE t0.[id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + AND t1.[id] IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..f0a84689a648 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[customer_id] AS v0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..7a46e4b035b1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[customer_id] AS v0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..27d65332f916 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[customer_id] AS k1 + FROM [shop].[crm_customers] t0 + JOIN [shop].[crm_customer_profile] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[customer] = t0.[customer_id] + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + AND t1.[tier] NOT IN (N'a', N'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..78f7bc2e3c41 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[customer_id] AS k1, t1.[tier] AS v0 + FROM [shop].[crm_customers] t0 + JOIN [shop].[crm_customer_profile] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[customer] = t0.[customer_id] + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + AND t1.[tier] IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..5129f52ebf0f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[customer_id] AS k1, t1.[tier] AS v0 + FROM [shop].[crm_customers] t0 + LEFT JOIN [shop].[crm_customer_profile] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[customer] = t0.[customer_id] + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..624ff507bf51 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + AND t0.[name] NOT IN (N'a', N'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..9f07851c3248 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[name] AS v0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + AND t0.[name] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..5eb1fbc91391 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[name] AS v0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-class.sql new file mode 100644 index 000000000000..82c8e62d2327 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + LEFT JOIN [shop].[products] t2 ON t2.[sku] = t1.[product_sku] + WHERE t0.[id] IS NOT NULL + AND t1.[product_sku] IS NOT NULL + AND t2.[sku] IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..e8ffc7525f05 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS v0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[product_sku] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..f1bb8d5d8c59 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS v0 + FROM [shop].[orders] t0 + LEFT JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..d56f372abfd3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[quantity] < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..74e5327eb72e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[channel] NOT IN (N'web', N'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..3d8fd667b32f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[customers] t0 + JOIN [shop].[customer_addresses] t1 ON t1.[customer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[city] NOT IN (N'a', N'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..d07ae9cd8996 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[city] AS v0 + FROM [shop].[customers] t0 + JOIN [shop].[customer_addresses] t1 ON t1.[customer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[city] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..4ccb13e53841 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[city] AS v0 + FROM [shop].[customers] t0 + LEFT JOIN [shop].[customer_addresses] t1 ON t1.[customer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..890cbcf6696e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[customers] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[email] NOT IN (N'a', N'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..ed917185d238 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[email] AS v0 + FROM [shop].[customers] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[email] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..53b4f6fab4f2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[email] AS v0 + FROM [shop].[customers] t0 + WHERE t0.[id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c From 173beaaaf455ef3b153408b4701b6239ce2fad59 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 17:32:17 -0800 Subject: [PATCH 077/203] Answer how the shapes of a class are checked on its tables GET /v1/ontologyConcepts/{id}/shapeChecks returns, for each part of each constraint of the shapes that target a class, the test that finds exactly the records that break it, or says that the table bindings hold it, that the property is not mapped, or why no exact test exists. It creates no test and runs no statement. Each kind of input is read once for the answer, whatever the number of shapes and constraints. The binding rows are read between two equal reads of the binding revisions, so the revision that a check names is the one its rows belong to. The compile runs the same for every caller. A constraint that rests on a table the caller may not view answers hidden for each part and names no table. --- .../jdbi3/OntologyConceptBindingStore.java | 41 +- .../service/jdbi3/OntologyReferenceDAO.java | 11 + .../ontology/OntologyBindingAccess.java | 44 ++- .../ontology/OntologyShapeCheckAnswer.java | 203 ++++++++++ .../ontology/OntologyShapeCheckCompiler.java | 17 +- .../ontology/OntologyShapeCheckFacts.java | 7 +- .../ontology/OntologyShapeCheckReader.java | 371 ++++++++++++++++++ .../ontology/OntologyStatementService.java | 28 ++ .../service/ontology/OntologyVersion.java | 204 ++++++++++ .../ontology/OntologyConceptResource.java | 24 ++ .../OntologyShapeCheckAnswerTest.java | 290 ++++++++++++++ .../OntologyShapeCheckCompilerTest.java | 23 ++ .../ontology/OntologyShapeCheckModel.java | 19 +- 13 files changed, 1263 insertions(+), 19 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index a391431025b4..3a9010bde2f6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -18,6 +18,8 @@ import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyBindingAssetType; import org.openmetadata.schema.type.OntologyConceptBindings; @@ -180,20 +182,51 @@ public List contributingRows(final UUID conceptId, final int limit) * statement. A release answers for a class that was deleted from the draft after it was sealed. */ public List workingConcepts(final UUID ontologyId, final Collection iris) { - final var concepts = dao.ontologyConceptDAO(); + return working(dao.ontologyConceptDAO(), ontologyId, iris); + } + + /** The working property rows of one ontology, as {@link #workingConcepts} reads class rows. */ + public List workingProperties( + final UUID ontologyId, final Collection iris) { + return working(dao.ontologyPropertyDAO(), ontologyId, iris); + } + + private static List working( + final OntologyMemberDAO members, final UUID ontologyId, final Collection iris) { return iris.isEmpty() ? List.of() - : concepts + : members .findDeclarationsIncludingDeleted( - concepts.getTableName(), + members.getTableName(), ontologyId, iris.stream().map(iri -> DigestUtils.md5Hex(iri.toString())).toList(), WORKING_ROWS_PER_IRI * iris.size()) .stream() - .map(json -> JsonUtils.readValue(json, OntologyConcept.class)) + .map(json -> JsonUtils.readValue(json, members.getEntityClass())) .toList(); } + /** + * The live shapes of one ontology that name the class as their target or in a constraint, in + * name order, in one statement. + */ + public List shapesNamingClass( + final UUID ontologyId, final URI classIri, final int limit) { + return dao + .ontologyReferenceDAO() + .shapesNamingClass(ontologyId, DigestUtils.sha256Hex(classIri.toString()), limit) + .stream() + .map(json -> JsonUtils.readValue(json, OntologyShape.class)) + .toList(); + } + + /** The live classes with these ids, in one statement. */ + public List liveConcepts(final Collection ids) { + return ids.isEmpty() + ? List.of() + : dao.ontologyConceptDAO().findEntitiesByIds(List.copyOf(ids), Include.NON_DELETED); + } + /** One page of an ontology's table rows in concept then asset id order, after a position. */ public List tableRows( final UUID ontologyId, final BindingPosition after, final int limit) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java index a292edbf0f9e..81a7f4ab6ecc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java @@ -163,6 +163,17 @@ List shapesNaming( @Bind("limit") int limit, @Define("locking") String locking); + @SqlQuery( + "SELECT s.json FROM ontology_shape_entity s JOIN ontology_reference r " + + "ON r.sourceId = s.id AND r.ontologyId = s.ontologyId " + + "WHERE s.ontologyId = :ontologyId AND s.deleted = FALSE " + + "AND r.sourceType = 'ontologyShape' AND r.role = 'CLASS_EXPRESSION' " + + "AND r.iriHash = :iriHash ORDER BY s.name, s.id LIMIT :limit") + List shapesNamingClass( + @BindUUID("ontologyId") UUID ontologyId, + @Bind("iriHash") String iriHash, + @Bind("limit") int limit); + @SqlQuery( "SELECT a.json FROM ontology_axiom_entity a JOIN ontology_reference r " + "ON r.sourceId = a.id AND r.ontologyId = a.ontologyId " diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java index 8c6176fd9e45..8bf5d0cb0104 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java @@ -1,5 +1,6 @@ package org.openmetadata.service.ontology; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -121,6 +122,38 @@ Map viewableTables(final Access access, final Collection ids) return tables; } + /** + * The live tables among {@code ids}, whoever asks, with what the caller may view. + * + * @param live every table that exists, by id, with its columns and declared constraints + * @param viewable the ids of the tables the caller may view + */ + record TableViews(Map live, Set viewable) {} + + /** + * The live tables among {@code ids}, read in one statement whoever asks, and the ids of those + * the caller may view. An answer that must be the same for every caller is built from all of + * them, and what the caller may not view is masked afterwards. + */ + TableViews tableViews(final Access access, final Collection ids) { + return tableViews(access, repositories.apply(Entity.TABLE), ids.stream().distinct().toList()); + } + + private > TableViews tableViews( + final Access access, final EntityRepository repository, final List ids) { + if (ids.isEmpty()) { + return new TableViews(Map.of(), Set.of()); + } + final List tables = + repository.get( + access.uriInfo(), ids, fields(repository, TABLE_COUNT_FIELDS), Include.NON_DELETED); + final Map live = new HashMap<>(); + tables.forEach(table -> live.put(table.getId(), (Table) table)); + final Set viewable = new HashSet<>(); + viewableAmong(access, repository, tables).forEach(table -> viewable.add(table.getId())); + return new TableViews(live, viewable); + } + /** The released definitions of one type that the caller may view, by id. */ Map> viewable( final Access access, final String type, final List released) { @@ -174,14 +207,22 @@ private > void loadViewable( return; } final List entities = repository.get(access.uriInfo(), ids, fields, Include.NON_DELETED); + viewableAmong(access, repository, entities) + .forEach(entity -> viewable.put(entity.getId(), entity)); + } + + /** The entities of one batch that the caller may view. */ + private > List viewableAmong( + final Access access, final EntityRepository repository, final List entities) { final var tags = BulkFieldHydrator.forTags(repository, entities); + final List viewable = new ArrayList<>(); for (final T entity : entities) { try { authorizer.authorize( access.securityContext(), new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), new ResourceContext<>(repository.getEntityType(), entity, repository, tags)); - viewable.put(entity.getId(), entity); + viewable.add(entity); } catch (final AuthorizationException hidden) { LOG.debug( "Binding target {} {} is hidden from the reader", @@ -189,6 +230,7 @@ private > void loadViewable( entity.getId()); } } + return viewable; } private > T authorized( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java new file mode 100644 index 000000000000..409a1deb48ed --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java @@ -0,0 +1,203 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.service.ontology.OntologyBuiltinTest.parameter; + +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotMapped; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyPartOutcome.Test; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledConstraint; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledPart; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledShape; +import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * Writes the answer a caller gets from what the shape check compile settled + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). The compile is the same for every + * caller. What a caller may not view is masked here, in one step after it: a constraint that rests + * on a table the caller may not view answers {@code hidden} for each part it states, and says + * nothing else about it. + */ +final class OntologyShapeCheckAnswer { + static final String SQL_EXPRESSION = "sqlExpression"; + static final String STRATEGY = "strategy"; + static final String OPERATOR = "operator"; + static final String THRESHOLD = "threshold"; + + /** The statement returns one number, and the test passes when that number is at most zero. */ + private static final String COUNT = "COUNT"; + + private static final String AT_MOST = "<="; + private static final String NO_VIOLATION = "0"; + + /** No id, part name or column name holds a control character, so these two part them. */ + private static final String FIELD_SEPARATOR = "\u001f"; + + private static final String PATH_SEPARATOR = "\u001e"; + + private final OntologyShapeCheckFacts facts; + private final Set hidden; + + private OntologyShapeCheckAnswer(final OntologyShapeCheckFacts facts, final Set hidden) { + this.facts = facts; + this.hidden = hidden; + } + + /** The part of one constraint of one shape that a test checks. */ + private record Named(UUID shapeId, String constraintId, OntologyShapePart part) {} + + /** + * The answer for each shape. + * + * @param hidden the ids of the tables the caller may not view + */ + static List shapes( + final OntologyShapeCheckFacts facts, + final List shapes, + final Set hidden) { + final OntologyShapeCheckAnswer answer = new OntologyShapeCheckAnswer(facts, hidden); + return OntologyShapeCheckCompiler.compile(facts, shapes).stream().map(answer::shape).toList(); + } + + private OntologyCheckedShape shape(final CompiledShape compiled) { + final OntologyShape shape = compiled.shape(); + return new OntologyCheckedShape() + .withId(shape.getId()) + .withName(shape.getName()) + .withSeverity(shape.getSeverity()) + .withConstraints( + compiled.constraints().stream() + .map(constraint -> constraint(shape.getId(), constraint)) + .toList()); + } + + private OntologyCheckedConstraint constraint(final UUID shapeId, final CompiledConstraint found) { + final String id = found.constraint().getId(); + final boolean masked = found.rests().stream().anyMatch(hidden::contains); + return new OntologyCheckedConstraint() + .withId(id) + .withPath(found.constraint().getPath()) + .withParts( + masked + ? masked(found.parts()) + : found.parts().stream() + .map(part -> part(new Named(shapeId, id, part.part()), part.outcome())) + .toList()); + } + + /** One entry for each part, so the number of answers the tables gave is not told either. */ + private static List masked(final List parts) { + return parts.stream() + .map(CompiledPart::part) + .distinct() + .map(part -> entry(part, OntologyShapeCheckOutcome.HIDDEN)) + .toList(); + } + + private OntologyCheckedPart part(final Named named, final OntologyPartOutcome outcome) { + return switch (outcome) { + case Check check -> entry(named.part(), OntologyShapeCheckOutcome.CHECK) + .withChecks(check.checks().stream().map(test -> check(named, test)).toList()); + case HeldByMapping held -> entry(named.part(), OntologyShapeCheckOutcome.HELD_BY_MAPPING); + case NotMapped none -> entry(named.part(), OntologyShapeCheckOutcome.NOT_MAPPED); + case NotEnforceable refused -> entry(named.part(), OntologyShapeCheckOutcome.NOT_ENFORCEABLE) + .withReason(refused.reason()); + }; + } + + private static OntologyCheckedPart entry( + final OntologyShapePart part, final OntologyShapeCheckOutcome outcome) { + return new OntologyCheckedPart().withPart(part).withOutcome(outcome); + } + + private OntologyShapeCheck check(final Named named, final TableCheck found) { + final Table table = found.place().holder().table(); + final OntologyShapeCheck check = + new OntologyShapeCheck() + .withIdentity(identity(named, found)) + .withTable(table.getEntityReference()) + .withColumns(found.columns()) + .withReadBindings(found.read().stream().map(this::read).toList()); + return switch (found.test()) { + case Test.Builtin builtin -> check + .withTestDefinition(builtin.definition()) + .withEntityLink(builtin.entityLink()) + .withParameterValues(builtin.parameters()); + case Test.Generated generated -> generated(check, table, generated.probe()); + }; + } + + /** + * The name of a check. It holds no value of the constraint, so a changed bound keeps the name, + * and it holds the bound column, so two columns of one table are two checks. + */ + private String identity(final Named named, final TableCheck found) { + return DigestUtils.sha256Hex( + String.join( + FIELD_SEPARATOR, + named.shapeId().toString(), + named.constraintId(), + named.part().value(), + facts.subject().id().toString(), + found.place().holder().row().assetId().toString(), + String.join(PATH_SEPARATOR, found.place().binding().getColumnPath()))); + } + + private OntologyShapeCheckBinding read(final BindingRow row) { + return new OntologyShapeCheckBinding() + .withConceptId(row.conceptId()) + .withAssetId(row.assetId()) + .withRevision(facts.revisions().get(row.conceptId())); + } + + /** + * Both statements are finished by the engine family of the table. The test runs the count in + * the form with every colon escaped, because the runner reads {@code :name} as a parameter. The + * list of keys is the form a person reads. + */ + private static OntologyShapeCheck generated( + final OntologyShapeCheck check, final Table table, final OntologyCheckProbe probe) { + final Statements statements = OntologyShapeCheckSql.write(probe); + final SqlEngineFamily family = probe.reach().family(); + return check + .withTestDefinition(OntologyBuiltinTest.CUSTOM_SQL) + .withEntityLink(OntologyBuiltinTest.tableLink(table)) + .withParameterValues( + List.of( + parameter(SQL_EXPRESSION, family.finish(statements.count()).escapedSql()), + parameter(STRATEGY, COUNT), + parameter(OPERATOR, AT_MOST), + parameter(THRESHOLD, NO_VIOLATION))) + .withInspectionQuery(family.finish(statements.keys()).sql()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java index 1a0e25f30c0b..d7c6df86e067 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java @@ -71,7 +71,7 @@ record CompiledShape(OntologyShape shape, List constraints) * One constraint with the answer for each part it states. * * @param rests the ids of the tables the answer rests on: the identity table of the class, each - * table that holds the property, and each table a join of the property arrives at + * table that binds the property, and each table a join of the property arrives at * @param parts one entry for each part, or one for each different answer when the tables that * hold the property do not agree */ @@ -128,13 +128,20 @@ private CompiledConstraint constraint(final OntologyShapeConstraint constraint) .forEach(outcome -> parts.add(new CompiledPart(part, outcome))); } }); - return new CompiledConstraint(constraint, rests(places), List.copyOf(parts)); + return new CompiledConstraint(constraint, rests(property), List.copyOf(parts)); } - private Set rests(final List places) { + /** + * A table with no role is among them when it binds the property, because the answer says that + * the class binds the property there. + */ + private Set rests(final OntologyProperty property) { final Set rests = new LinkedHashSet<>(); - facts.subject().identity().ifPresent(identity -> rests.add(identity.row().assetId())); - for (final Place place : places) { + final Subject subject = facts.subject(); + subject.identity().ifPresent(identity -> rests.add(identity.row().assetId())); + final List bindings = + property == null ? List.of() : subject.bindings(property.getId()); + for (final Place place : bindings) { rests.add(place.holder().row().assetId()); if (place.binding().getJoin() != null && place.binding().getJoin().getTargetAssetId() != null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java index 2967ab421f04..2354f57f3b72 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java @@ -71,9 +71,14 @@ List places(final UUID propertyId) { .toList(); } + /** Every column the class binds the property to, in a table of any role or of none. */ + List bindings(final UUID propertyId) { + return tables.stream().flatMap(table -> bound(table, propertyId)).toList(); + } + /** True when the class binds the property in a column of any table, whatever its role. */ boolean binds(final UUID propertyId) { - return tables.stream().flatMap(table -> bound(table, propertyId)).findAny().isPresent(); + return !bindings(propertyId).isEmpty(); } private static Stream bound(final MappedTable table, final UUID propertyId) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java new file mode 100644 index 000000000000..f98801b510ad --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java @@ -0,0 +1,371 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyRecordMapping.conflict; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyBindingAccess.TableViews; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Target; + +/** + * Reads what the shape check compile needs + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). Each kind is read once for the + * whole answer, whatever the number of shapes and constraints. The kinds are the shapes that + * target the class, the properties their constraints are about, the classes their {@code class} + * parts name, the binding rows between two reads of the binding revisions, and the tables those + * rows name. + * + *

    Two questions cost further reads, and only when a constraint asks them. A relation that the + * class binds nowhere is looked for on its declared inverse. A class that a {@code class} part + * names, and whose identity binding has a row filter, is checked for a subclass with an identity + * binding on the same table. + */ +final class OntologyShapeCheckReader { + /** An answer reads at most this many table bindings of the class, whatever their role. */ + static final int MOST_TABLES = OntologyConceptQueryService.TABLE_BINDINGS_READ; + + private static final int BINDING_READ_ATTEMPTS = 3; + + /** The rows of each class that can hold the inverse of a relation: one statement reads them. */ + private static final int JOIN_HOLDERS_READ = OntologyMappingReader.MAX_CONTRIBUTING_TABLES + 1; + + /** The classes bound to one table that are looked at for a subclass of a class. */ + private static final int MOST_CLASSES_ON_A_TABLE = 100; + + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess catalog; + + OntologyShapeCheckReader( + final OntologyConceptBindingStore store, final OntologyBindingAccess catalog) { + this.store = store; + this.catalog = catalog; + } + + /** The class an answer is about, in the version that is read. */ + record Asked(UUID id, URI iri, UUID ontologyId, OntologyVersion version) {} + + /** + * Everything one answer reads. + * + * @param shapes the shapes that target the class, in name order + * @param hidden the ids of the tables that exist and that the caller may not view + */ + record Read(List shapes, OntologyShapeCheckFacts facts, Set hidden) {} + + /** + * The binding rows of one answer. + * + * @param subject the table rows of the class, its identity table first + * @param targets the identity table row of each class a {@code class} part names, by class id + */ + private record Rows( + Map revisions, List subject, Map targets) {} + + /** + * What the rows of other classes say about the class. + * + * @param inverseHolders the tables that bind the declared inverse of a relation, by the id of + * the relation, for each relation the class binds nowhere + * @param sharing the ids of the classes a {@code class} part names that have a subclass with an + * identity binding on their own identity table + */ + private record Others(Map> inverseHolders, Set sharing) {} + + Read read(final Access access, final Asked asked) { + final List shapes = shapes(asked); + final Map properties = + byIri( + asked + .version() + .propertiesNamed( + store, asked.ontologyId(), named(shapes, OntologyShapeConstraint::getPath)), + OntologyProperty::getIri); + final Map classes = + byIri( + asked + .version() + .classesNamed( + store, asked.ontologyId(), named(shapes, OntologyShapeConstraint::getClassIri)), + OntologyConcept::getIri); + final Rows rows = rows(asked, classes.values().stream().map(OntologyConcept::getId).toList()); + final Others others = + new Others( + inverseHolders(asked, properties.values(), rows.subject()), + sharing(asked, classes.values(), rows.targets())); + final TableViews tables = catalog.tableViews(access, assets(rows, others)); + return new Read( + shapes, + new OntologyShapeCheckFacts( + subject(asked, rows, tables), + properties, + targets(classes, rows, others, tables), + boundOnInverse(others, tables), + rows.revisions()), + hidden(tables)); + } + + private List shapes(final Asked asked) { + return asked.version().shapesTargeting(store, asked.ontologyId(), asked.iri()).stream() + .sorted(Comparator.comparing(OntologyShape::getName).thenComparing(OntologyShape::getId)) + .toList(); + } + + /** The IRIs that the constraints of the shapes name in one of their fields. */ + private static Set named( + final List shapes, final Function field) { + return shapes.stream() + .flatMap(shape -> listOrEmpty(shape.getConstraints()).stream()) + .map(field) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + private static Map byIri(final List definitions, final Function iri) { + final Map byIri = new LinkedHashMap<>(); + definitions.forEach(definition -> byIri.putIfAbsent(iri.apply(definition), definition)); + return byIri; + } + + /** + * Reads the binding rows between two reads of the binding revisions. A binding write commits its + * rows and its revision in one transaction, so two equal revision reads mean that no write + * landed between them, and every row belongs to the revision that is returned with it. + */ + private Rows rows(final Asked asked, final List targets) { + final Set classes = new LinkedHashSet<>(targets); + classes.add(asked.id()); + for (int attempt = 0; attempt < BINDING_READ_ATTEMPTS; attempt++) { + final Map revisions = store.revisions(classes); + final List subject = + store.identityFirstTables(List.of(asked.id()), MOST_TABLES + 1); + final Map identity = + store.identityRows(targets).stream() + .collect(Collectors.toMap(BindingRow::conceptId, Function.identity())); + if (revisions.equals(store.revisions(classes))) { + return new Rows(revisions, identityFirst(asked, subject), identity); + } + } + throw conflict("The table bindings changed while the answer was built. Ask again"); + } + + /** + * A class that binds more tables than one answer reads gets no answer, because a binding left + * out could hold a property and change what a count over its values must read. + */ + private static List identityFirst(final Asked asked, final List rows) { + if (rows.size() > MOST_TABLES) { + throw conflict("Class %s binds more than %d tables", asked.iri(), MOST_TABLES); + } + return rows.stream() + .sorted(Comparator.comparing(row -> row.role() != OntologyBindingRole.IDENTITY)) + .toList(); + } + + /** + * For each relation of the constraints that the class binds in no table, the tables in which a + * class of the domain of its declared inverse, or of its own range, binds that inverse. Only an + * identity table or a contributing table counts, as only those hold a join that is read. + */ + private Map> inverseHolders( + final Asked asked, + final Collection properties, + final List subject) { + final List unbound = + properties.stream().filter(property -> isUnboundWithInverse(property, subject)).toList(); + if (unbound.isEmpty()) { + return Map.of(); + } + final Map inverses = + byIri( + asked + .version() + .propertiesNamed( + store, + asked.ontologyId(), + unbound.stream().map(OntologyProperty::getInverse).distinct().toList()), + OntologyProperty::getIri); + final List rows = + store.joinHolderTables( + classIds(asked, unbound.stream().flatMap(relation -> ends(relation, inverses))), + JOIN_HOLDERS_READ); + final Map> holders = new HashMap<>(); + for (final OntologyProperty relation : unbound) { + final OntologyProperty inverse = inverses.get(relation.getInverse()); + if (inverse != null && inverse.getKind() == OntologyPropertyKind.OBJECT) { + holders.put(relation.getId(), binding(rows, inverse.getId())); + } + } + return holders; + } + + private static boolean isUnboundWithInverse( + final OntologyProperty property, final List subject) { + return property.getKind() == OntologyPropertyKind.OBJECT + && property.getInverse() != null + && !property.getInverse().equals(property.getIri()) + && binding(subject, property.getId()).isEmpty(); + } + + /** The classes that can bind the inverse of a relation: its domain, or the range of the relation. */ + private static Stream ends( + final OntologyProperty relation, final Map inverses) { + final OntologyProperty inverse = inverses.get(relation.getInverse()); + return inverse == null + ? Stream.empty() + : Stream.concat( + listOrEmpty(inverse.getDomain()).stream(), listOrEmpty(relation.getRange()).stream()); + } + + private List classIds(final Asked asked, final Stream iris) { + return asked + .version() + .classesNamed(store, asked.ontologyId(), iris.distinct().toList()) + .stream() + .map(OntologyConcept::getId) + .toList(); + } + + /** The ids of the tables among {@code rows} that bind the property in a column. */ + private static Set binding(final List rows, final UUID propertyId) { + return rows.stream() + .filter( + row -> + listOrEmpty(row.columns()).stream() + .map(OntologyColumnBinding::getPropertyId) + .anyMatch(propertyId::equals)) + .map(BindingRow::assetId) + .collect(Collectors.toSet()); + } + + /** + * The classes of the {@code class} parts whose records a test would cut short: the identity + * binding has a row filter, and a subclass has its identity binding on the same table. A table + * that more classes bind than are looked at counts as shared, which only ever withholds a test. + */ + private Set sharing( + final Asked asked, + final Collection classes, + final Map identity) { + final Set sharing = new HashSet<>(); + for (final OntologyConcept type : classes) { + final BindingRow row = identity.get(type.getId()); + if (row != null && row.rowFilter() != null && sharesTable(asked, type, row)) { + sharing.add(type.getId()); + } + } + return sharing; + } + + private boolean sharesTable(final Asked asked, final OntologyConcept type, final BindingRow row) { + final List onTable = + store.forAssetAfter(row.assetId(), null, MOST_CLASSES_ON_A_TABLE + 1); + final List others = + onTable.stream() + .filter(other -> other.role() == OntologyBindingRole.IDENTITY) + .map(BindingRow::conceptId) + .filter(id -> !id.equals(type.getId())) + .toList(); + return onTable.size() > MOST_CLASSES_ON_A_TABLE + || (!others.isEmpty() + && asked.version().anySubclassOf(store, asked.ontologyId(), others, type.getIri())); + } + + /** The id of every table an answer can rest on or name. */ + private static Set assets(final Rows rows, final Others others) { + final Set assets = new LinkedHashSet<>(); + for (final BindingRow row : rows.subject()) { + assets.add(row.assetId()); + listOrEmpty(row.columns()).stream() + .map(OntologyColumnBinding::getJoin) + .filter(join -> join != null && join.getTargetAssetId() != null) + .forEach(join -> assets.add(join.getTargetAssetId())); + } + rows.targets().values().forEach(row -> assets.add(row.assetId())); + others.inverseHolders().values().forEach(assets::addAll); + return assets; + } + + /** A binding whose table no longer exists is no binding of the class here. */ + private static Subject subject(final Asked asked, final Rows rows, final TableViews tables) { + final List mapped = new ArrayList<>(); + for (final BindingRow row : rows.subject()) { + if (tables.live().containsKey(row.assetId())) { + mapped.add(new MappedTable(tables.live().get(row.assetId()), row)); + } + } + return new Subject(asked.id(), asked.iri(), List.copyOf(mapped)); + } + + private static Map targets( + final Map classes, + final Rows rows, + final Others others, + final TableViews tables) { + final Map targets = new HashMap<>(); + classes.forEach( + (iri, type) -> { + final BindingRow row = rows.targets().get(type.getId()); + final boolean held = row != null && tables.live().containsKey(row.assetId()); + targets.put( + iri, + new Target( + type.getId(), + held ? new MappedTable(tables.live().get(row.assetId()), row) : null, + others.sharing().contains(type.getId()))); + }); + return targets; + } + + private static Set boundOnInverse(final Others others, final TableViews tables) { + return others.inverseHolders().entrySet().stream() + .filter(holders -> holders.getValue().stream().anyMatch(tables.live()::containsKey)) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + } + + private static Set hidden(final TableViews tables) { + return tables.live().keySet().stream() + .filter(id -> !tables.viewable().contains(id)) + .collect(Collectors.toSet()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java index 243deee42823..2003d0bb5e75 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java @@ -32,6 +32,7 @@ import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; import org.openmetadata.schema.api.data.OntologyFindStatementRequest; import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; +import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.api.data.OntologyStatementBindingRevision; import org.openmetadata.schema.api.data.OntologyStatementDirection; import org.openmetadata.schema.api.data.OntologyStatementEngineFamily; @@ -63,6 +64,8 @@ import org.openmetadata.service.ontology.OntologyRelationPath.End; import org.openmetadata.service.ontology.OntologyRelationPath.Ends; import org.openmetadata.service.ontology.OntologyRelationPath.Held; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Asked; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Read; import org.openmetadata.service.ontology.OntologyVersion.Wanted; import org.openmetadata.service.ontology.sql.FinishedStatement; import org.openmetadata.service.security.Authorizer; @@ -78,6 +81,9 @@ * relation, the binding rows between two revision reads, the tables twice (which exist, then the * ones the reader may view), the bound properties, and the release members when it reads a * release. + * + *

    It also says how the shapes that target a class are checked on the tables the class binds + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered), from the same class and version. */ public final class OntologyStatementService { private static final String CLASS = "Class"; @@ -98,6 +104,7 @@ public interface DraftGate { private final CollectionDAO dao; private final OntologyBindingAccess catalog; private final OntologyMappingReader mapping; + private final OntologyShapeCheckReader shapes; private final DraftGate draftGate; public OntologyStatementService( @@ -110,6 +117,7 @@ public OntologyStatementService( this.dao = dao; this.catalog = new OntologyBindingAccess(authorizer, repositories); this.mapping = new OntologyMappingReader(store, catalog); + this.shapes = new OntologyShapeCheckReader(store, catalog); this.draftGate = draftGate; } @@ -246,6 +254,26 @@ public OntologyStatementPlan aggregate( } } + /** + * How each part of each constraint of the shapes that target the class is checked on the tables + * the class binds. The answer creates no test and runs no statement. + */ + public OntologyShapeChecks shapeChecks( + final Access access, final UUID classId, final OntologyStatementVersion version) { + try (final var ignored = FreshReadScope.enter()) { + final Subject subject = subject(access, classId, version); + final Read read = + shapes.read( + access, + new Asked(subject.id(), subject.iri(), subject.ontologyId(), subject.version())); + return new OntologyShapeChecks() + .withConceptId(subject.id()) + .withClassIri(subject.iri()) + .withVersion(subject.version().read()) + .withShapes(OntologyShapeCheckAnswer.shapes(read.facts(), read.shapes(), read.hidden())); + } + } + private OntologyStatementPlan count(final Access access, final Subject subject) { final Bindings bindings = mapping.bindings(List.of(subject.id()), List.of()); final Tables tables = mapping.tables(access, bindings.rows()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java index 362b11f7a9de..826f52db5b5e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -14,19 +14,28 @@ package org.openmetadata.service.ontology; import java.net.URI; +import java.util.ArrayDeque; +import java.util.ArrayList; import java.util.Collection; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.function.Function; +import java.util.function.Predicate; import java.util.stream.Collectors; import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.api.data.OntologyStatementVersion; import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyReleaseMember; @@ -51,6 +60,12 @@ * is read through the working rows, which must be live. */ sealed interface OntologyVersion { + /** One statement reads at most this many of the shapes of a draft that name one class. */ + int MOST_SHAPES_NAMING_A_CLASS = 1000; + + /** The shape members of a release are read this many at a time. */ + int SHAPE_MEMBERS_READ = 1000; + /** The definition a statement looks for, and what to do when it belongs to another ontology. */ record Wanted( String entityType, @@ -79,6 +94,24 @@ Map viewableProperties( */ Optional classNamed(OntologyConceptBindingStore store, UUID ontologyId, List iris); + /** The shapes this version holds whose target is the class {@code iri}, in any order. */ + List shapesTargeting(OntologyConceptBindingStore store, UUID ontologyId, URI iri); + + /** The properties this version declares with one of {@code iris}. */ + List propertiesNamed( + OntologyConceptBindingStore store, UUID ontologyId, Collection iris); + + /** The classes this version declares with one of {@code iris}. */ + List classesNamed( + OntologyConceptBindingStore store, UUID ontologyId, Collection iris); + + /** + * True when this version declares one of the classes {@code candidates} as a subclass of the + * class {@code iri}, however many named subclass steps apart. + */ + boolean anySubclassOf( + OntologyConceptBindingStore store, UUID ontologyId, Collection candidates, URI iri); + /** The active release of {@code ontology}, or a 404 that says it has none. */ static OntologyVersion release(final CollectionDAO dao, final EntityReference ontology) { final OntologyState state = dao.ontologyStateDAO().get(ontology.getId()); @@ -135,6 +168,50 @@ public Optional classNamed( final OntologyConceptBindingStore store, final UUID ontologyId, final List iris) { return store.liveConcepts(ontologyId, iris).stream().findFirst().map(OntologyConcept::getId); } + + /** + * One statement reads the live shapes that name the class, as a target or in a constraint. A + * class that more shapes name than one statement reads gets no answer, because a shape left + * out would be a constraint left unchecked. + */ + @Override + public List shapesTargeting( + final OntologyConceptBindingStore store, final UUID ontologyId, final URI iri) { + final List naming = + store.shapesNamingClass(ontologyId, iri, MOST_SHAPES_NAMING_A_CLASS + 1); + if (naming.size() > MOST_SHAPES_NAMING_A_CLASS) { + throw OntologyRecordMapping.conflict( + "More than %d shapes name class %s", MOST_SHAPES_NAMING_A_CLASS, iri); + } + return naming.stream().filter(shape -> iri.equals(shape.getTargetConcept())).toList(); + } + + @Override + public List propertiesNamed( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return store.liveProperties(ontologyId, iris); + } + + @Override + public List classesNamed( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return store.liveConcepts(ontologyId, iris); + } + + @Override + public boolean anySubclassOf( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection candidates, + final URI iri) { + return store.liveConcepts(candidates).stream() + .filter(candidate -> ontologyId.equals(candidate.getOntology().getId())) + .anyMatch(candidate -> store.ancestors(candidate).contains(iri.toString())); + } } /** A sealed release, whose members are stored payloads that never change. */ @@ -167,6 +244,133 @@ public Optional classNamed( .map(OntologyConcept::getId); } + /** The shape members of the release, read a page at a time, since no index names a target. */ + @Override + public List shapesTargeting( + final OntologyConceptBindingStore store, final UUID ontologyId, final URI iri) { + final List targeting = new ArrayList<>(); + String after = ""; + List page; + do { + page = + dao.ontologyReleaseDAO() + .listMembers(release.getId(), MemberKind.SHAPE.value(), after, SHAPE_MEMBERS_READ); + for (final OntologyReleaseMember member : page) { + final OntologyShape shape = + (OntologyShape) OntologyReleaseReader.definition(release, member); + if (iri.equals(shape.getTargetConcept())) { + targeting.add(shape); + } + after = member.getMemberId().toString(); + } + } while (page.size() == SHAPE_MEMBERS_READ); + return List.copyOf(targeting); + } + + @Override + public List propertiesNamed( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return released( + MemberKind.PROPERTY, + store.workingProperties(ontologyId, iris).stream().map(OntologyProperty::getId).toList(), + OntologyProperty.class, + property -> iris.contains(property.getIri())); + } + + @Override + public List classesNamed( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return released( + MemberKind.CONCEPT, + store.workingConcepts(ontologyId, iris).stream().map(OntologyConcept::getId).toList(), + OntologyConcept.class, + concept -> iris.contains(concept.getIri())); + } + + /** + * The subclass steps come from the axioms of the release, so the answer is the released one + * whatever the draft changed since. The release is read whole, through the cache that every + * whole read of a sealed release shares. + */ + @Override + public boolean anySubclassOf( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection candidates, + final URI iri) { + final List members = + new OntologyReleaseReader(dao) + .read(release, unchecked -> {}).stream() + .map(member -> OntologyReleaseReader.definition(release, member)) + .toList(); + final Set starts = + members.stream() + .filter(OntologyConcept.class::isInstance) + .map(OntologyConcept.class::cast) + .filter(type -> candidates.contains(type.getId())) + .map(type -> type.getIri().toString()) + .collect(Collectors.toSet()); + return reaches(namedParents(members), starts, iri.toString()); + } + + /** The named parents that the subclass axioms give each class, by the IRI of the class. */ + private static Map> namedParents(final List members) { + final Map> parents = new HashMap<>(); + for (final OntologyDefinition member : members) { + if (member instanceof OntologyAxiom axiom && axiom.getSubjectIri() != null) { + final Set named = + parents.computeIfAbsent(axiom.getSubjectIri().toString(), subject -> new HashSet<>()); + OntologyClassHierarchy.namedParents(axiom) + .forEach(parent -> named.add(parent.toString())); + } + } + return parents; + } + + /** True when a walk up the named parents from one of {@code starts} arrives at {@code iri}. */ + private static boolean reaches( + final Map> parents, final Set starts, final String iri) { + final Set visited = new HashSet<>(starts); + final Deque pending = new ArrayDeque<>(starts); + while (!pending.isEmpty()) { + for (final String parent : parents.getOrDefault(pending.pop(), Set.of())) { + if (visited.add(parent)) { + pending.push(parent); + } + } + } + return visited.contains(iri); + } + + /** + * The members of one kind with these ids that the release declares with a wanted IRI, in one + * statement. The ids come from the working rows, deleted ones too, so a definition is found + * as it was released whatever the draft lost since. + */ + private List released( + final MemberKind kind, + final List ids, + final Class type, + final Predicate wanted) { + final List memberIds = ids.stream().distinct().map(UUID::toString).toList(); + final List releaseIds = List.of(release.getId().toString()); + final List members = + memberIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + memberIds, + chunk -> + dao.ontologyReleaseDAO().listMemberPayloads(releaseIds, kind.value(), chunk)); + return members.stream() + .map(member -> type.cast(OntologyReleaseReader.definition(release, member))) + .filter(wanted) + .toList(); + } + /** The member of this release with the id, or empty when the release lacks it. */ Optional member(final MemberKind kind, final UUID id) { return Optional.ofNullable( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyConceptResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyConceptResource.java index 459c04288e3d..ab700b3abdc2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyConceptResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyConceptResource.java @@ -14,6 +14,7 @@ package org.openmetadata.service.resources.ontology; import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.json.JsonPatch; import jakarta.validation.Valid; @@ -46,7 +47,9 @@ import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; import org.openmetadata.schema.api.data.OntologyFindStatementRequest; import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; +import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementVersion; import org.openmetadata.schema.api.data.RestoreEntity; import org.openmetadata.schema.api.data.UpdateOntologyConceptBinding; import org.openmetadata.schema.entity.data.OntologyConcept; @@ -318,6 +321,27 @@ public OntologyStatementPlan aggregateStatement( return statements.aggregate(new Access(uriInfo, securityContext), id, request); } + @GET + @Path("/{id}/shapeChecks") + @Operation( + operationId = "getOntologyShapeChecks", + summary = "Say how the shapes of a class are checked on its tables", + description = + "For each part of each constraint of the shapes that target the class, returns the data" + + " quality test that finds exactly the records that break it, or says that the table" + + " bindings already hold it, that the property is not mapped, or why no exact test" + + " exists. Nothing is created, scheduled or run.") + public OntologyShapeChecks shapeChecks( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @Parameter(description = "The ontology version to read: its active release, or its draft") + @QueryParam("version") + @DefaultValue("release") + final OntologyStatementVersion version) { + return statements.shapeChecks(new Access(uriInfo, securityContext), id, version); + } + @GET @Path("/name/{fqn}") @Operation(operationId = "getOntologyConceptByName", summary = "Get an ontology concept by name") diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java new file mode 100644 index 000000000000..9ad0439be3ca --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java @@ -0,0 +1,290 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import java.net.URI; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.utils.JsonUtils; + +/** + * The answer as a caller reads it: one kind of entry for each outcome, a test as a request to + * create a test case takes it, and nothing about a constraint that rests on a table the caller + * may not view. + */ +class OntologyShapeCheckAnswerTest { + private static final String POSTGRES = "Postgres"; + + /** The reference of a table that no catalog holds, so it names no entity type. */ + private static final String CUSTOMERS_TABLE = + "{\"id\":\"7cc39a8b-6fb0-313c-b68f-2dc9b46b50d5\",\"name\":\"customers\"," + + "\"fullyQualifiedName\":\"warehouse.sales.shop.customers\"," + + "\"displayName\":\"customers\",\"deleted\":false}"; + + private static final String CUSTOMER_BINDING = + "{\"conceptId\":\"25c48fe2-1541-3ad0-9724-3f720ced92d6\"," + + "\"assetId\":\"7cc39a8b-6fb0-313c-b68f-2dc9b46b50d5\",\"revision\":1}"; + + private static OntologyShapeCheckModel customers() { + return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, POSTGRES); + } + + /** The parts of the one constraint, as the caller who may not view {@code hidden} reads them. */ + private static List parts( + final OntologyShapeCheckModel model, + final String type, + final OntologyShapeConstraint constraint, + final Set hidden) { + return shapes(model, type, hidden, constraint) + .getFirst() + .getConstraints() + .getFirst() + .getParts(); + } + + private static List shapes( + final OntologyShapeCheckModel model, + final String type, + final Set hidden, + final OntologyShapeConstraint... constraints) { + return OntologyShapeCheckAnswer.shapes( + model.facts(type), List.of(model.targeting(type, constraints)), hidden); + } + + private static OntologyShapeCheck check( + final OntologyShapeCheckModel model, + final String type, + final OntologyShapeConstraint constraint) { + return parts(model, type, constraint, Set.of()).getFirst().getChecks().getFirst(); + } + + @Test + void aColumnTestIsWrittenAsARequestToCreateATestCaseTakesIt() { + final OntologyShapeCheckModel model = + customers().primaryKey("customers", "id").notNull("customers", "email"); + assertEquals( + "[{\"part\":\"in\",\"outcome\":\"check\",\"checks\":[{" + + "\"identity\":\"5f601e0183676bea515c7d2a3fc65c264a4e6358b42df7a0382c8e9b80572854\"," + + "\"table\":" + + CUSTOMERS_TABLE + + ",\"columns\":[[\"email\"]]," + + "\"testDefinition\":\"columnValuesToBeInSet\"," + + "\"entityLink\":\"<#E::table::warehouse.sales.shop.customers::columns::email>\"," + + "\"parameterValues\":[{\"name\":\"allowedValues\",\"value\":\"[\\\"a\\\",\\\"b\\\"]\"}," + + "{\"name\":\"matchEnum\",\"value\":\"true\"}]," + + "\"readBindings\":[" + + CUSTOMER_BINDING + + "]}]}]", + JsonUtils.pojoToJson( + parts( + model, + "Customer", + model.on("customerEmail").withIn(literals("a", "b")), + Set.of()))); + } + + @Test + void aGeneratedTestRunsItsCountWithColonsEscapedAndListsItsKeysAsAPersonReadsThem() { + final OntologyShapeCheckModel model = customers(); + assertEquals( + "[{\"part\":\"in\",\"outcome\":\"check\",\"checks\":[{" + + "\"identity\":\"5f601e0183676bea515c7d2a3fc65c264a4e6358b42df7a0382c8e9b80572854\"," + + "\"table\":" + + CUSTOMERS_TABLE + + ",\"columns\":[[\"email\"]]," + + "\"testDefinition\":\"tableCustomSQLQuery\"," + + "\"entityLink\":\"<#E::table::warehouse.sales.shop.customers>\"," + + "\"parameterValues\":[{\"name\":\"sqlExpression\",\"value\":\"" + + "SELECT COUNT(*) AS violations\\nFROM (\\n" + + " SELECT DISTINCT t0.id AS k0\\n FROM shop.customers t0\\n" + + " WHERE t0.id IS NOT NULL\\n AND t0.email NOT IN ('mailto\\\\:a', 'b')\\n) c\"}," + + "{\"name\":\"strategy\",\"value\":\"COUNT\"}," + + "{\"name\":\"operator\",\"value\":\"<=\"}," + + "{\"name\":\"threshold\",\"value\":\"0\"}]," + + "\"inspectionQuery\":\"SELECT DISTINCT t0.id AS k0\\nFROM shop.customers t0\\n" + + "WHERE t0.id IS NOT NULL\\n AND t0.email NOT IN ('mailto:a', 'b')\"," + + "\"readBindings\":[" + + CUSTOMER_BINDING + + "]}]}]", + JsonUtils.pojoToJson( + parts( + model, + "Customer", + model.on("customerEmail").withIn(literals("mailto:a", "b")), + Set.of()))); + } + + @Test + void anAnswerWithoutATestSaysWhichKindItIsAndAReasonOnlyWhenItIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + assertEquals( + "[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}," + + "{\"part\":\"pattern\",\"outcome\":\"notEnforceable\",\"reason\":\"tableNotSimple\"}]", + JsonUtils.pojoToJson( + parts( + model, + "Customer", + model.on("customerEmail").withMinCount(0).withPattern("^[0-9]+$"), + Set.of()))); + assertEquals( + "[{\"part\":\"maxCount\",\"outcome\":\"notMapped\"}]", + JsonUtils.pojoToJson( + parts( + model, + "Customer", + new OntologyShapeConstraint() + .withId("c2") + .withPath(URI.create("https://example.org/unfilteredIdentity#unbound")) + .withMaxCount(1), + Set.of()))); + } + + @Test + void aCheckIsNamedByWhatItChecksAndNotByAValueOfTheConstraint() { + final OntologyShapeCheckModel model = customers(); + final String listed = + check(model, "Customer", model.on("customerEmail").withIn(literals("a"))).getIdentity(); + assertEquals("5f601e0183676bea515c7d2a3fc65c264a4e6358b42df7a0382c8e9b80572854", listed); + assertEquals( + listed, + check(model, "Customer", model.on("customerEmail").withIn(literals("a", "b", "c"))) + .getIdentity()); + assertEquals( + "327d378c098bf5ae96b85be4b07fcc63093278a62dff2c38bb518f295604baf0", + check(model, "Customer", model.on("customerEmail").withMinCount(1)).getIdentity()); + } + + @Test + void aCheckOnALinkTableBelongsToItAndNamesTheRevisionOfEveryBindingItRead() { + final OntologyShapeCheckModel model = new OntologyShapeCheckModel(LINK_TABLE, POSTGRES); + final OntologyShapeCheck check = + check(model, "Order", model.on("contains").withClassIri(LINK_TABLE.iri("Product"))); + assertEquals( + "45a138d09a62daec111a6beb791f69f0d112a8e63be1f3e55fb9ef13500b145c", check.getIdentity()); + assertEquals("warehouse.sales.shop.order_items", check.getTable().getFullyQualifiedName()); + assertEquals("<#E::table::warehouse.sales.shop.order_items>", check.getEntityLink()); + assertEquals(List.of(List.of("product_sku")), check.getColumns()); + assertEquals( + "[{\"conceptId\":\"3709c2f7-5944-3e4d-b2da-78de8278487b\"," + + "\"assetId\":\"b5ad3863-fafc-3abc-8825-22d9088467a4\",\"revision\":1}," + + "{\"conceptId\":\"3709c2f7-5944-3e4d-b2da-78de8278487b\"," + + "\"assetId\":\"4a6b56cc-2fb6-31ef-8e8c-0cf153c56336\",\"revision\":1}," + + "{\"conceptId\":\"ad7613c7-65d8-3f2f-a0b6-17f1b0497611\"," + + "\"assetId\":\"9d471789-03f5-3b02-a136-5d5206dff661\",\"revision\":2}]", + JsonUtils.pojoToJson(check.getReadBindings())); + } + + @Test + void aConstraintOnAHiddenIdentityTableSaysOnlyHiddenForEachPart() { + final OntologyShapeCheckModel model = customers(); + final Set hidden = Set.of(model.mapping().id("customers")); + assertEquals( + "[{\"id\":\"c740db69-5948-3a3f-8958-af47e77417cb\",\"name\":\"shape\"," + + "\"severity\":\"Violation\",\"constraints\":[" + + "{\"id\":\"c1\",\"path\":\"https://example.org/unfilteredIdentity#customerEmail\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"in\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/unfilteredIdentity#unbound\"," + + "\"parts\":[{\"part\":\"maxCount\",\"outcome\":\"hidden\"}]}]}]", + JsonUtils.pojoToJson( + shapes( + model, + "Customer", + hidden, + model.on("customerEmail").withMinCount(1).withIn(literals("a")), + new OntologyShapeConstraint() + .withId("c2") + .withPath(URI.create("https://example.org/unfilteredIdentity#unbound")) + .withMaxCount(1)))); + } + + @Test + void aHiddenTableThatHoldsOnePropertyHidesOnlyTheConstraintsOnThatProperty() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel(REPEATED_CONTRIBUTION, POSTGRES); + final List shapes = + shapes( + model, + "Customer", + Set.of(model.mapping().id("customer_addresses")), + model.on("addressCity").withMaxCount(1).withIn(literals("London")), + model.on("customerName").withId("c2").withMinCount(0)); + assertEquals( + "[{\"id\":\"c1\",\"path\":\"https://example.org/repeatedContribution#addressCity\"," + + "\"parts\":[{\"part\":\"maxCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"in\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/repeatedContribution#customerName\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}]}]", + JsonUtils.pojoToJson(shapes.getFirst().getConstraints())); + } + + @Test + void aHiddenTableThatAJoinReachesHidesEveryPartOfTheRelation() { + final OntologyShapeCheckModel model = new OntologyShapeCheckModel(COLUMN_RELATION, POSTGRES); + final List shapes = + shapes( + model, + "Order", + Set.of(model.mapping().id("customers")), + model.on("placedBy").withMinCount(1).withClassIri(COLUMN_RELATION.iri("Customer")), + model.on("orderTotal").withId("c2").withMinCount(0)); + assertEquals( + "[{\"id\":\"c1\",\"path\":\"https://example.org/columnRelation#placedBy\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"class\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/columnRelation#orderTotal\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}]}]", + JsonUtils.pojoToJson(shapes.getFirst().getConstraints())); + } + + @Test + void aHiddenAnswerDoesNotTellHowManyAnswersTheTablesGave() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel( + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + OntologyMappingShapes.identity( + "Customer", + "customers", + List.of("id"), + null, + OntologyMappingShapes.bound("customerName", "name")), + OntologyMappingShapes.contributing( + "Customer", + "customer_addresses", + List.of("customer_id"), + OntologyMappingShapes.bound("customerName", "city")))) + .primaryKey("customers", "id"); + final OntologyShapeConstraint pattern = model.on("customerName").withPattern("^[0-9]+$"); + assertEquals(2, parts(model, "Customer", pattern, Set.of()).size()); + assertEquals( + "[{\"part\":\"pattern\",\"outcome\":\"hidden\"}]", + JsonUtils.pojoToJson( + parts(model, "Customer", pattern, Set.of(model.mapping().id("customer_addresses"))))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java index f1df0f0239a6..ae45021373f8 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java @@ -887,4 +887,27 @@ void constraintRestsOnTheIdentityTableTheHolderAndTheTableItsJoinReaches() { Set.of(model.mapping().id("orders")), model.compile("Order", model.on("productTitle").withMinCount(1)).rests()); } + + @Test + void constraintAlsoRestsOnATableWithNoRoleThatBindsItsProperty() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel( + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + identity( + "Customer", "customers", List.of("id"), null, bound("customerName", "name")), + new BindingSpec( + "Customer", + "customer_addresses", + null, + List.of(), + null, + List.of(bound("addressCity", "city"))))); + final OntologyShapeConstraint constraint = model.on("addressCity").withMinCount(1); + assertEquals(new NotMapped(), model.answer("Customer", constraint)); + assertEquals( + Set.of(model.mapping().id("customers"), model.mapping().id("customer_addresses")), + model.compile("Customer", constraint).rests()); + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java index 2516a274972e..07acd5367446 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java @@ -242,16 +242,19 @@ private Map targets(final Bindings bindings) { return targets; } + /** The shape named {@code shape} that targets the class and holds these constraints. */ + OntologyShape targeting(final String type, final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(mapping.id("shape")) + .withName("shape") + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withTargetConcept(mapping.iri(type)) + .withConstraints(List.of(constraints)); + } + /** The shape that holds only {@code constraint}, compiled for the class. */ CompiledConstraint compile(final String type, final OntologyShapeConstraint constraint) { - final OntologyShape held = - new OntologyShape() - .withId(mapping.id("shape")) - .withName("shape") - .withSeverity(OntologyShapeSeverity.VIOLATION) - .withTargetConcept(mapping.iri(type)) - .withConstraints(List.of(constraint)); - return OntologyShapeCheckCompiler.compile(facts(type), List.of(held)) + return OntologyShapeCheckCompiler.compile(facts(type), List.of(targeting(type, constraint))) .getFirst() .constraints() .getFirst(); From 75db6fbae15d61d9a8f805dd05fda3bdcf65dcb5 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 17:40:31 -0800 Subject: [PATCH 078/203] Send the key value cases for a text column through an in list Each key value case of the SQL value case file that is for one text column becomes the one value of an in list, once for each service type the case names. The statement of the check ends with the text the case expects, or the part has no exact test because the value does not fit the column. --- .../OntologyShapeCheckValueCasesTest.java | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java new file mode 100644 index 000000000000..84ee604fb982 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java @@ -0,0 +1,145 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.tests.TestCaseParameterValue; + +/** + * Sends each key value case of {@code ontology/sql-value-cases.json} that is for one text column + * through an {@code in} list on a text column, once for each service type the case names. A case + * says how its engine family writes the value, or that the value is refused. A check holds the + * written value in the statement it runs, and a refused value leaves the part with no exact test. + * + *

    The expected text of a case is the oracle. A case is never edited to make this test pass. + */ +class OntologyShapeCheckValueCasesTest { + private static final String CASES = "/ontology/sql-value-cases.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String KEY_VALUE = "keyValue"; + private static final String ONE_TEXT_COLUMN = "VARCHAR"; + private static final String RENDERED = "rendered"; + private static final String REFUSED = "refusedAtRequest"; + + /** One case on one service type of the engine family the case is for. */ + private record Run(JsonNode json, String serviceType) { + String outcome() { + return json.at("/expectedOutcome/kind").asText(); + } + + String input() { + return json.get("input").asText(); + } + + @Override + public String toString() { + return json.get("id").asText() + " " + serviceType; + } + } + + static Stream runs() throws IOException { + try (InputStream cases = OntologyShapeCheckValueCasesTest.class.getResourceAsStream(CASES)) { + final List runs = new ArrayList<>(); + for (final JsonNode json : JSON.readTree(cases)) { + if (KEY_VALUE.equals(json.get("path").asText()) + && ONE_TEXT_COLUMN.equals(json.get("columnType").asText())) { + json.get("serviceTypes").forEach(type -> runs.add(new Run(json, type.asText()))); + } + } + return runs.stream(); + } + } + + /** The {@code in} part of a constraint that lists the value of the case, on a text column. */ + private static OntologyCheckedPart listed(final Run run) { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel(UNFILTERED_IDENTITY, run.serviceType()); + return OntologyShapeCheckAnswer.shapes( + model.facts("Customer"), + List.of( + model.targeting( + "Customer", model.on("customerEmail").withIn(literals(run.input())))), + Set.of()) + .getFirst() + .getConstraints() + .getFirst() + .getParts() + .getFirst(); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("runs") + void aListedValueIsWrittenAsItsCaseSaysOrLeavesNoTest(final Run run) { + final OntologyCheckedPart part = listed(run); + switch (run.outcome()) { + case RENDERED -> assertTheCountHoldsTheWrittenValue(run, part); + case REFUSED -> assertNoTest(part); + default -> fail("No test covers " + run.outcome()); + } + } + + private static void assertTheCountHoldsTheWrittenValue( + final Run run, final OntologyCheckedPart part) { + assertEquals(OntologyShapeCheckOutcome.CHECK, part.getOutcome()); + final OntologyShapeCheck check = part.getChecks().getFirst(); + final String count = + check.getParameterValues().stream() + .filter(parameter -> parameter.getName().equals("sqlExpression")) + .map(TestCaseParameterValue::getValue) + .findFirst() + .orElseThrow(); + + assertEquals("tableCustomSQLQuery", check.getTestDefinition()); + assertTrue( + count.endsWith(" NOT IN (" + run.json().at("/expectedOutcome/text").asText() + ")\n) c"), + count); + } + + private static void assertNoTest(final OntologyCheckedPart part) { + assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, part.getOutcome()); + assertEquals(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN, part.getReason()); + assertNull(part.getChecks()); + } + + @Test + void theCaseFileHoldsThirtyEightKeyValuesForOneTextColumn() throws IOException { + final List runs = runs().toList(); + + assertEquals(138, runs.size()); + assertEquals(38, runs.stream().map(run -> run.json().get("id").asText()).distinct().count()); + assertEquals(92, runs.stream().filter(run -> RENDERED.equals(run.outcome())).count()); + assertEquals(46, runs.stream().filter(run -> REFUSED.equals(run.outcome())).count()); + } +} From 667b802a0c07e42a523934c647510c078219c5ef Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 18:33:53 -0800 Subject: [PATCH 079/203] Run the shape checks on rows in MySQL and Postgres Each generated test runs on rows that satisfy its constraint and on rows that break it, and must count exactly the records a case names. The answer is asserted whole for each outcome, for a reader who may not view a table, and for the version a request names. One request runs the same statements for forty constraints as for one. --- .../it/tests/OntologyShapeCheckAnswerIT.java | 471 +++++++++++++++++ .../it/tests/OntologyShapeCheckFixtures.java | 493 ++++++++++++++++++ .../it/tests/OntologyShapeCheckIT.java | 464 +++++++++++++++++ .../it/tests/OntologyShapeCheckReadsIT.java | 278 ++++++++++ .../it/tests/OntologyShapeCheckRightsIT.java | 365 +++++++++++++ 5 files changed, 2071 insertions(+) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java new file mode 100644 index 000000000000..a8b0fccf6e71 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java @@ -0,0 +1,471 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertStatus; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.CUSTOM_SQL; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.MEMBERS; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.PARTIES; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.addRows; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.answer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.assertCounts; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.check; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.countParameters; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declareKey; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identity; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.keyList; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.parameter; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.part; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.read; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.reference; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.row; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.CHECK; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.HELD_BY_MAPPING; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.NOT_ENFORCEABLE; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.NOT_MAPPED; +import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; +import static org.openmetadata.schema.api.data.OntologyShapePart.DATATYPE; +import static org.openmetadata.schema.api.data.OntologyShapePart.IN; +import static org.openmetadata.schema.api.data.OntologyShapePart.MAX_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.MIN_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.PATTERN; +import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; + +import java.net.URI; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyAxiom; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyAxiom; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyExpression; +import org.openmetadata.schema.type.OntologyExpressionKind; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.RelationProvenance; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * What {@code GET /v1/ontologyConcepts/{id}/shapeChecks} answers for each outcome: a column test of + * the catalog, a generated test, a part that the mapping holds, a property with no binding, a part + * with no exact test, and the version that a request names. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckAnswerIT extends BaseOntologyApprovalIT { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + private static final String TABLE_LINK = "<#E::table::%s>"; + private static final String COLUMN_LINK = "<#E::table::%s::columns::%s>"; + + /** One table whose declared key is its subject key, so each row is one record. */ + private static final Shape ACCOUNTS = + mapping( + "accounts", + List.of( + table( + "accounts", List.of(integer("id"), text("email"), text("nick"), integer("age")))), + List.of("Account"), + List.of( + data("accountNo", "Account"), + data("accountEmail", "Account"), + data("accountNick", "Account"), + data("accountAge", "Account"), + data("accountNote", "Account")), + identityTable( + "Account", + "accounts", + List.of("id"), + null, + bound("accountNo", "id"), + bound("accountEmail", "email"), + bound("accountNick", "nick"), + bound("accountAge", "age"))); + + /** The accounts table and the shape of its class, as the parts of an answer name them. */ + private record Accounts(OntologyShapeFixture fixture, OntologyShape shape) { + private String tableName() { + return fixture.table("accounts").getFullyQualifiedName(); + } + + private OntologyShapeCheckBinding binding() { + return read(fixture, "Account", "accounts", 1L); + } + + private OntologyShapeCheck test(final String column) { + return new OntologyShapeCheck() + .withTable(reference(fixture, "accounts")) + .withColumns(List.of(List.of(column))) + .withReadBindings(List.of(binding())); + } + + /** A test that the catalog defines for one column. */ + OntologyShapeCheck columnTest( + final String definition, final String column, final TestCaseParameterValue... parameters) { + return test(column) + .withTestDefinition(definition) + .withEntityLink(COLUMN_LINK.formatted(tableName(), column)) + .withParameterValues(List.of(parameters)); + } + + /** A generated test of the table, with the list of keys that its statement counts. */ + OntologyShapeCheck generated(final String column, final String count) { + return test(column) + .withTestDefinition(CUSTOM_SQL) + .withEntityLink(TABLE_LINK.formatted(tableName())) + .withParameterValues(countParameters(count)) + .withInspectionQuery(keyList(count)); + } + + /** A part that one test checks, which takes its name from what it checks. */ + OntologyCheckedPart checked( + final String constraint, final OntologyShapePart part, final OntologyShapeCheck test) { + final List column = test.getColumns().getFirst(); + return entry(part, CHECK) + .withChecks( + List.of(test.withIdentity(identity(shape, constraint, part, binding(), column)))); + } + + OntologyCheckedConstraint constraint( + final String id, final String property, final OntologyCheckedPart... parts) { + return new OntologyCheckedConstraint() + .withId(id) + .withPath(fixture.property(property).getIri()) + .withParts(List.of(parts)); + } + } + + private static OntologyCheckedPart entry( + final OntologyShapePart part, final OntologyShapeCheckOutcome outcome) { + return new OntologyCheckedPart().withPart(part).withOutcome(outcome); + } + + private static OntologyShapeCheckOutcome outcome( + final OntologyShapeChecks checks, final String constraint, final OntologyShapePart part) { + return part(checks, constraint, part).getOutcome(); + } + + private static OntologyShapeCheckReason reason( + final OntologyShapeChecks checks, final String constraint, final OntologyShapePart part) { + return part(checks, constraint, part).getReason(); + } + + @Test + void aTableWhoseRowsAreItsRecordsGetsTheColumnTestsOfTheCatalog(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "accounts"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + fixture.property("accountNote"); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyConcept account = fixture.type("Account"); + final Accounts accounts = + new Accounts( + fixture, + declare( + ontology, + fixture, + "AccountShape", + "Account", + on(fixture, "no-required", "accountNo").withMinCount(1), + on(fixture, "email-count", "accountEmail").withMinCount(1).withMaxCount(1), + on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b")), + on(fixture, "nick-listed", "accountNick").withIn(literals("x")), + on(fixture, "nick-pattern", "accountNick").withPattern("^[0-9]{3}$"), + on(fixture, "age-range", "accountAge") + .withDatatypeIri(URI.create(XSD + "integer")) + .withMinInclusive(limit("0")) + .withMaxInclusive(limit("120")), + on(fixture, "email-type", "accountEmail") + .withDatatypeIri(URI.create(XSD + "date")), + on(fixture, "note-required", "accountNote").withMinCount(1), + on(fixture, "nick-class", "accountNick").withClassIri(account.getIri()))); + final String id = fixture.name("id"); + final String countOfNick = + String.join( + "\n", + "SELECT COUNT(*) AS violations", + "FROM (", + " SELECT DISTINCT t0." + id + " AS k0", + " FROM " + fixture.from("accounts") + " t0", + " WHERE t0." + id + " IS NOT NULL", + " AND t0." + fixture.name("nick") + " NOT IN ('x')", + ") c"); + final OntologyCheckedPart notNull = + accounts.checked( + "email-count", MIN_COUNT, accounts.columnTest("columnValuesToBeNotNull", "email")); + final OntologyCheckedPart inSet = + accounts.checked( + "email-listed", + IN, + accounts.columnTest( + "columnValuesToBeInSet", + "email", + parameter("allowedValues", "[\"a\",\"b\"]"), + parameter("matchEnum", "true"))); + final OntologyCheckedPart listed = + accounts.checked("nick-listed", IN, accounts.generated("nick", countOfNick)); + final OntologyCheckedPart regex = + accounts.checked( + "nick-pattern", + PATTERN, + accounts.columnTest( + "columnValuesToMatchRegex", "nick", parameter("regex", "^[0-9]{3}$"))); + final OntologyCheckedPart between = + accounts.checked( + "age-range", + RANGE, + accounts.columnTest( + "columnValuesToBeBetween", + "age", + parameter("minValue", "0"), + parameter("maxValue", "120"))); + final List constraints = + List.of( + accounts.constraint("no-required", "accountNo", entry(MIN_COUNT, HELD_BY_MAPPING)), + accounts.constraint( + "email-count", "accountEmail", notNull, entry(MAX_COUNT, HELD_BY_MAPPING)), + accounts.constraint("email-listed", "accountEmail", inSet), + accounts.constraint("nick-listed", "accountNick", listed), + accounts.constraint("nick-pattern", "accountNick", regex), + accounts.constraint( + "age-range", "accountAge", entry(DATATYPE, HELD_BY_MAPPING), between), + accounts.constraint( + "email-type", + "accountEmail", + entry(DATATYPE, NOT_ENFORCEABLE) + .withReason(OntologyShapeCheckReason.DATATYPE_MISMATCH)), + accounts.constraint("note-required", "accountNote", entry(MIN_COUNT, NOT_MAPPED)), + accounts.constraint( + "nick-class", + "accountNick", + entry(CLASS, NOT_ENFORCEABLE) + .withReason(OntologyShapeCheckReason.NOT_A_RELATION))); + final OntologyShapeChecks expected = + new OntologyShapeChecks() + .withConceptId(account.getId()) + .withClassIri(account.getIri()) + .withVersion( + new OntologyStatementVersionRead() + .withKind(DRAFT) + .withWorkingRevision( + admin().ontologies().state(ontology.getId()).getWorkingRevision())) + .withShapes( + List.of( + new OntologyCheckedShape() + .withId(accounts.shape().getId()) + .withName("AccountShape") + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints(constraints))); + + assertEquals( + JsonUtils.readTree(JsonUtils.pojoToJson(expected)), + JsonUtils.readTree(answer(admin(), account, DRAFT))); + + // The nick column may hold a null, so its list is a generated test, and a null passes it. + final OntologyShapeCheck nick = check(checks(admin(), account, DRAFT), "nick-listed", IN); + assertCounts("0", List.of(), nick); + addRows(fixture, "accounts", row(1, "a", "x", 10), row(2, "b", null, 20)); + assertCounts("0", List.of(), nick); + addRows(fixture, "accounts", row(3, "a", "y", 30)); + assertCounts("1", List.of(List.of("3")), nick); + } + } + + @Test + void aSubclassOnTheFilteredTableOfTheNamedClassLeavesNoExactTest(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "subclass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, PARTIES)) { + fixture.bindAll(); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "placed-by", "placedBy").withClassIri(fixture.type("Person").getIri())); + assertEquals( + CHECK, outcome(checks(admin(), fixture.type("Order"), DRAFT), "placed-by", CLASS)); + + final OntologyAxiom subclass = + admin() + .ontologyAxioms() + .create( + new CreateOntologyAxiom() + .withName("organizationIsPerson") + .withDisplayName("organizationIsPerson") + .withDescription("An organization is a person before the law") + .withOntology(ontology.getFullyQualifiedName()) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(fixture.type("Organization").getIri()) + .withProvenance(RelationProvenance.MANUAL) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(fixture.type("Person").getIri())))); + final OntologyShapeChecks drafted = checks(admin(), fixture.type("Order"), DRAFT); + assertEquals(NOT_ENFORCEABLE, outcome(drafted, "placed-by", CLASS)); + assertEquals( + OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE, reason(drafted, "placed-by", CLASS)); + assertNull(part(drafted, "placed-by", CLASS).getChecks()); + + activate(ns, ontology); + admin().ontologyAxioms().delete(subclass.getId().toString()); + + // The release still holds the subclass step that the draft lost. + assertEquals( + OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE, + reason(checks(admin(), fixture.type("Order"), RELEASE), "placed-by", CLASS)); + assertEquals( + CHECK, outcome(checks(admin(), fixture.type("Order"), DRAFT), "placed-by", CLASS)); + } + } + + @Test + void aRelationBoundOnlyOnItsInverseIsNotEnforceableFromThisSide(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "inverse"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, PARTIES)) { + fixture.bindAll(); + final OntologyProperty places = + admin() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("places") + .withIri(PARTIES.iri("places")) + .withOntology(ontology.getFullyQualifiedName()) + .withKind(OntologyPropertyKind.OBJECT) + .withDomain(List.of(fixture.type("Person").getIri())) + .withRange(List.of(fixture.type("Order").getIri())) + .withInverse(fixture.property("placedBy").getIri())); + declare( + ontology, + fixture, + "PersonShape", + "Person", + new OntologyShapeConstraint() + .withId("places") + .withPath(places.getIri()) + .withMinCount(1) + .withMaxCount(5), + new OntologyShapeConstraint() + .withId("unknown") + .withPath(PARTIES.iri("neverDeclared")) + .withMinCount(1)); + + final OntologyShapeChecks checks = checks(admin(), fixture.type("Person"), DRAFT); + + assertEquals(NOT_ENFORCEABLE, outcome(checks, "places", MIN_COUNT)); + assertEquals(OntologyShapeCheckReason.BOUND_ON_INVERSE, reason(checks, "places", MIN_COUNT)); + assertEquals(OntologyShapeCheckReason.BOUND_ON_INVERSE, reason(checks, "places", MAX_COUNT)); + assertEquals(NOT_MAPPED, outcome(checks, "unknown", MIN_COUNT)); + } + } + + @Test + void anAnswerReadsTheVersionThatItsRequestNames(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "versions"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, MEMBERS)) { + fixture.bindAll(); + final OntologyShape released = + declare( + ontology, + fixture, + "ReleasedShape", + "Member", + on(fixture, "email-required", "memberEmail").withMinCount(1)); + final OntologyRelease release = current(activate(ns, ontology)); + declare( + ontology, + fixture, + "DraftedShape", + "Member", + on(fixture, "age-range", "memberAge").withMinInclusive(limit("0"))); + final OntologyConcept later = fixture.type("Later"); + final String lacks = + "Class https://example.org/members#Later is not in the active release of ontology " + + ontology.getFullyQualifiedName(); + + final OntologyShapeChecks byDefault = checks(admin(), fixture.type("Member"), null); + final OntologyShapeChecks drafted = checks(admin(), fixture.type("Member"), DRAFT); + + assertEquals( + new OntologyStatementVersionRead() + .withKind(RELEASE) + .withReleaseId(release.getId()) + .withReleaseRevision(release.getReleaseRevision()) + .withSemanticVersion(release.getSemanticVersion()), + byDefault.getVersion()); + assertEquals( + List.of(released.getId()), + byDefault.getShapes().stream().map(OntologyCheckedShape::getId).toList()); + assertEquals(byDefault, checks(admin(), fixture.type("Member"), RELEASE)); + assertEquals(DRAFT, drafted.getVersion().getKind()); + assertEquals( + List.of("DraftedShape", "ReleasedShape"), + drafted.getShapes().stream().map(OntologyCheckedShape::getName).toList()); + assertRefused(404, lacks, () -> checks(admin(), later, RELEASE)); + assertEquals(List.of(), checks(admin(), later, DRAFT).getShapes()); + assertStatus( + 400, + () -> + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologyConcepts/" + + fixture.type("Member").getId() + + "/shapeChecks?version=latest", + null)); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java new file mode 100644 index 000000000000..e4303c9584d6 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java @@ -0,0 +1,493 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; + +/** + * What the tests of {@code GET /v1/ontologyConcepts/{id}/shapeChecks} share: a mapping written as + * its tables, classes and bindings, the shapes of a class, the answer of the endpoint, and a check + * run against the database of the suite as the test runner would send it. + */ +final class OntologyShapeCheckFixtures { + static final String CUSTOM_SQL = "tableCustomSQLQuery"; + private static final String GOLDEN_CHECKS = "/ontology/shape-checks/%s/%s.sql"; + private static final String COUNT_OPENING = "SELECT COUNT(*) AS violations\nFROM (\n"; + private static final String COUNT_CLOSING = "\n) c"; + + /** One table with no declared key, so its rows are not its records one for one. */ + static final Shape MEMBERS = + mapping( + "members", + List.of( + table( + "members", + List.of(integer("id"), text("email"), integer("age")), + row(1, "ada@example.org", 30), + row(2, "grace@example.org", 40))), + List.of("Member"), + List.of(data("memberEmail", "Member"), data("memberAge", "Member")), + identityTable( + "Member", + "members", + List.of("id"), + null, + bound("memberEmail", "email"), + bound("memberAge", "age"))); + + /** People and organizations share one table, and an order names the person who placed it. */ + static final Shape PARTIES = + mapping( + "parties", + List.of( + table( + "parties", + List.of(integer("id"), text("kind"), text("name")), + row(1, "person", "Ada"), + row(2, "person", "Grace"), + row(10, "org", "Initech")), + table( + "orders", + List.of(integer("id"), integer("party_id"), decimal("total")), + row(100, 1, new BigDecimal("10.00")), + row(101, 1, new BigDecimal("20.00")), + row(102, 2, new BigDecimal("5.00")))), + List.of("Person", "Organization", "Order"), + List.of( + data("personName", "Person"), + data("organizationName", "Organization"), + relation("placedBy", "Order", "Person")), + identityTable( + "Person", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person"), + bound("personName", "name")), + identityTable( + "Organization", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "org"), + bound("organizationName", "name")), + identityTable( + "Order", + "orders", + List.of("id"), + null, + joined("placedBy", "party_id", "parties", "id"))); + + private OntologyShapeCheckFixtures() {} + + static ColumnSpec integer(final String name) { + return new ColumnSpec(name, ColumnDataType.INT); + } + + static ColumnSpec text(final String name) { + return new ColumnSpec(name, ColumnDataType.VARCHAR); + } + + static ColumnSpec decimal(final String name) { + return new ColumnSpec(name, ColumnDataType.DECIMAL); + } + + @SafeVarargs + static TableSpec table( + final String name, final List columns, final List... rows) { + return new TableSpec(name, columns, List.of(rows)); + } + + /** A row that may hold nulls, which {@code List.of} refuses. */ + static List row(final Object... values) { + return Arrays.asList(values); + } + + static PropertySpec data(final String name, final String domain) { + return new PropertySpec(name, false, domain, null); + } + + static PropertySpec relation(final String name, final String domain, final String range) { + return new PropertySpec(name, false, domain, range); + } + + static ColumnBindingSpec bound(final String property, final String column) { + return new ColumnBindingSpec(property, column, null); + } + + /** A relation held in one column, with a confirmed join onto one column of the target. */ + static ColumnBindingSpec joined( + final String property, final String column, final String target, final String parent) { + return joined(property, target, List.of(column), List.of(parent)); + } + + /** A relation with a confirmed join of several columns. The binding names the first of them. */ + static ColumnBindingSpec joined( + final String property, + final String target, + final List child, + final List parent) { + return new ColumnBindingSpec( + property, + child.getFirst(), + new JoinSpec(target, OntologyJoinStatus.CONFIRMED, child, parent)); + } + + static BindingSpec identityTable( + final String type, + final String table, + final List key, + final FilterSpec filter, + final ColumnBindingSpec... columns) { + return new BindingSpec( + type, table, OntologyBindingRole.IDENTITY, key, filter, List.of(columns)); + } + + static BindingSpec contributing( + final String type, + final String table, + final List key, + final ColumnBindingSpec... columns) { + return new BindingSpec( + type, table, OntologyBindingRole.CONTRIBUTING, key, null, List.of(columns)); + } + + /** A mapping with no statement to ask of it. */ + static Shape mapping( + final String name, + final List tables, + final List classes, + final List properties, + final BindingSpec... bindings) { + return new Shape(name, tables, classes, properties, List.of(bindings), List.of()); + } + + /** A literal with no datatype, as a bound of a range or a member of a list. */ + static OntologyLiteral limit(final String value) { + return new OntologyLiteral().withValue(value); + } + + static List literals(final String... values) { + return Arrays.stream(values) + .map(value -> new OntologyShapeValue().withLiteral(limit(value))) + .toList(); + } + + /** A constraint on one property of the mapping, ready for the parts a test states. */ + static OntologyShapeConstraint on( + final OntologyShapeFixture fixture, final String id, final String property) { + return new OntologyShapeConstraint().withId(id).withPath(fixture.property(property).getIri()); + } + + /** Saves a shape that targets one class of the mapping in the working draft. */ + static OntologyShape declare( + final Ontology ontology, + final OntologyShapeFixture fixture, + final String name, + final String type, + final OntologyShapeConstraint... constraints) { + return admin() + .ontologyShapes() + .create( + new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("What a record of " + type + " must satisfy") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(fixture.type(type).getIri()) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints(List.of(constraints))); + } + + /** The catalog declares a primary key of the table, and the columns that never hold a null. */ + static void declareKey( + final OntologyShapeFixture fixture, + final String tableName, + final List key, + final String... neverNull) { + final String id = fixture.table(tableName).getId().toString(); + final Table table = admin().tables().get(id, "tableConstraints"); + table.getColumns().stream() + .filter(column -> List.of(neverNull).contains(column.getName())) + .forEach(column -> column.setConstraint(ColumnConstraint.NOT_NULL)); + admin() + .tables() + .update( + id, + table.withTableConstraints( + List.of( + new TableConstraint() + .withConstraintType(TableConstraint.ConstraintType.PRIMARY_KEY) + .withColumns(key)))); + } + + /** Adds rows to a table that the fixture created in the database of the suite. */ + @SafeVarargs + static void addRows( + final OntologyShapeFixture fixture, final String tableName, final List... rows) { + final int width = fixture.shape().table(tableName).columns().size(); + final String insert = + "INSERT INTO " + + fixture.from(tableName) + + " VALUES (" + + String.join(", ", Collections.nCopies(width, "?")) + + ")"; + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> { + try (PreparedStatement row = handle.getConnection().prepareStatement(insert)) { + for (final List values : rows) { + for (int column = 0; column < width; column++) { + row.setObject(column + 1, values.get(column)); + } + row.executeUpdate(); + } + } catch (final SQLException failed) { + throw new IllegalStateException(insert, failed); + } + }); + } + + private static String path(final OntologyConcept type, final OntologyStatementVersion version) { + return "/v1/ontologyConcepts/" + + type.getId() + + "/shapeChecks" + + (version == null ? "" : "?version=" + version.value()); + } + + /** + * Asks how the shapes of a class are checked, as {@code client}. + * + * @param version the version to read, or null to name none + */ + static OntologyShapeChecks checks( + final OpenMetadataClient client, + final OntologyConcept type, + final OntologyStatementVersion version) { + return client + .getHttpClient() + .execute(HttpMethod.GET, path(type, version), null, OntologyShapeChecks.class); + } + + /** The body of the answer to {@link #checks}, as the server wrote it. */ + static String answer( + final OpenMetadataClient client, + final OntologyConcept type, + final OntologyStatementVersion version) { + return client.getHttpClient().executeForString(HttpMethod.GET, path(type, version), null); + } + + /** The entries of one part of the constraint with this id, in the first shape that holds it. */ + static List parts( + final OntologyShapeChecks checks, final String constraintId, final OntologyShapePart part) { + return checks.getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .filter(constraint -> constraint.getId().equals(constraintId)) + .findFirst() + .map(OntologyCheckedConstraint::getParts) + .orElseThrow() + .stream() + .filter(entry -> entry.getPart() == part) + .toList(); + } + + /** The one entry of a part that every table answers alike. */ + static OntologyCheckedPart part( + final OntologyShapeChecks checks, final String constraintId, final OntologyShapePart part) { + final List entries = parts(checks, constraintId, part); + assertEquals(1, entries.size(), () -> constraintId + " " + part + " " + entries); + return entries.getFirst(); + } + + /** The one test of a part that one table checks. */ + static OntologyShapeCheck check( + final OntologyShapeChecks checks, final String constraintId, final OntologyShapePart part) { + final OntologyCheckedPart entry = part(checks, constraintId, part); + assertEquals(1, entry.getChecks() == null ? 0 : entry.getChecks().size(), entry::toString); + return entry.getChecks().getFirst(); + } + + static String parameter(final OntologyShapeCheck check, final String name) { + return check.getParameterValues().stream() + .filter(parameter -> parameter.getName().equals(name)) + .map(TestCaseParameterValue::getValue) + .findFirst() + .orElseThrow(); + } + + static TestCaseParameterValue parameter(final String name, final String value) { + return new TestCaseParameterValue().withName(name).withValue(value); + } + + /** The parameters of a generated test around its statement. */ + static List countParameters(final String sqlExpression) { + return List.of( + parameter("sqlExpression", sqlExpression), + parameter("strategy", "COUNT"), + parameter("operator", "<="), + parameter("threshold", "0")); + } + + /** + * The number a generated test returns on the rows the tables hold now. The runner hands the + * statement to a reader of {@code :name} parameters, which reads {@code \:} as a colon, so the + * database gets the statement with its colons back. + */ + static String violations(final OntologyShapeCheck check) { + final List> rows = + OntologyShapeFixture.run(parameter(check, "sqlExpression").replace("\\:", ":")); + assertEquals(1, rows.size(), rows::toString); + assertEquals(1, rows.getFirst().size(), rows::toString); + return rows.getFirst().getFirst(); + } + + /** The keys of the records in violation on the rows the tables hold now, in key order. */ + static List> keys(final OntologyShapeCheck check) { + return OntologyShapeFixture.run(check.getInspectionQuery()).stream() + .sorted(Comparator.comparing(List::toString)) + .toList(); + } + + /** The test counts this many records in violation, and its list of keys names exactly them. */ + static void assertCounts( + final String expected, + final List> expectedKeys, + final OntologyShapeCheck check) { + assertEquals(expected, violations(check), check::getInspectionQuery); + assertEquals(expectedKeys, keys(check), check::getInspectionQuery); + } + + static OntologyShapeCheckBinding read( + final OntologyShapeFixture fixture, + final String type, + final String tableName, + final long revision) { + return new OntologyShapeCheckBinding() + .withConceptId(fixture.type(type).getId()) + .withAssetId(fixture.table(tableName).getId()) + .withRevision(revision); + } + + /** + * The name of a check: the SHA-256 of what it checks, each part kept from the next by a + * character that none of them holds. + * + * @param holder the binding of the table the check belongs to + */ + static String identity( + final OntologyShape shape, + final String constraintId, + final OntologyShapePart part, + final OntologyShapeCheckBinding holder, + final List columnPath) { + return DigestUtils.sha256Hex( + String.join( + "\u001f", + shape.getId().toString(), + constraintId, + part.value(), + holder.getConceptId().toString(), + holder.getAssetId().toString(), + String.join("\u001e", columnPath))); + } + + /** The table as an answer names it. */ + static EntityReference reference(final OntologyShapeFixture fixture, final String tableName) { + return admin().tables().get(fixture.table(tableName).getId().toString()).getEntityReference(); + } + + /** + * The golden count statement of one part of a mapping shape of the service module, as the engine + * family of this database writes it, with the tables of this fixture in place of the tables of + * the golden schema. + * + * @param name the file name without its extension, as {@code linkTable-contains-class} + */ + static String goldenCount(final OntologyShapeFixture fixture, final String name) { + final String resource = String.format(GOLDEN_CHECKS, fixture.family(), name); + String text; + try (InputStream file = OntologyShapeCheckFixtures.class.getResourceAsStream(resource)) { + text = new String(file.readAllBytes(), StandardCharsets.UTF_8).stripTrailing(); + } catch (final IOException unread) { + throw new UncheckedIOException(resource, unread); + } + final List tables = + fixture.shape().tables().stream() + .map(TableSpec::name) + .sorted(Comparator.comparing(String::length).reversed()) + .toList(); + for (final String table : tables) { + text = text.replace(goldenName(fixture, table), fixture.from(table)); + } + return text; + } + + private static String goldenName(final OntologyShapeFixture fixture, final String table) { + return "mysql".equals(fixture.family()) ? "`shop`.`" + table + "`" : "shop." + table; + } + + /** The list of keys that a count statement counts: its inner statement, one level out. */ + static String keyList(final String count) { + final String inner = + count.substring(COUNT_OPENING.length(), count.length() - COUNT_CLOSING.length()); + return inner.lines().map(line -> line.substring(2)).reduce((a, b) -> a + "\n" + b).orElse(""); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckIT.java new file mode 100644 index 000000000000..c5ce99da5045 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckIT.java @@ -0,0 +1,464 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.CUSTOM_SQL; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.MEMBERS; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.PARTIES; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.addRows; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.assertCounts; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.check; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.contributing; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.countParameters; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.joined; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.parameter; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.read; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.relation; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.row; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; +import static org.openmetadata.schema.api.data.OntologyShapePart.IN; +import static org.openmetadata.schema.api.data.OntologyShapePart.MAX_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.MIN_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; + +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Runs the generated tests of {@code GET /v1/ontologyConcepts/{id}/shapeChecks} on the database + * this suite runs on. Each test runs twice: on rows that satisfy its constraint, where it must + * count no record, and on rows that break it, where it must count exactly the records the case + * names and list their keys. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckIT extends BaseOntologyApprovalIT { + private static final List> NO_KEYS = List.of(); + private static final String MYSQL = "mysql"; + + /** Web orders only, each with the products a link table gives it. */ + private static final Shape BASKETS = + mapping( + "baskets", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "web"), + row(7, "internal")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt")), + table( + "order_items", + List.of(integer("order_id"), text("product_sku"), integer("quantity")), + row(1, "A-1", 2), + row(1, "A-1", 3), + row(2, "B-2", 1), + row(7, "ZZ-9", 0), + row(99, "ZZ-9", 0))), + List.of("Order", "Product"), + List.of( + data("orderChannel", "Order"), + data("productTitle", "Product"), + data("itemQuantity", "Order"), + relation("contains", "Order", "Product")), + identityTable( + "Order", + "orders", + List.of("id"), + new FilterSpec("channel", OntologyRowFilterOperator.EQUALS, "web"), + bound("orderChannel", "channel")), + identityTable( + "Product", "products", List.of("sku"), null, bound("productTitle", "title")), + contributing( + "Order", + "order_items", + List.of("order_id"), + bound("itemQuantity", "quantity"), + joined("contains", "product_sku", "products", "sku"))); + + /** A shipment names its account with two columns, the two-column key of the account table. */ + private static final Shape SHIPMENTS = + mapping( + "shipments", + List.of( + table( + "accounts", + List.of(text("tenant"), integer("account_no"), text("tier")), + row("eu", 1, "gold"), + row("us", 1, "silver")), + table( + "shipments", + List.of( + text("tenant"), + integer("shipment_no"), + text("account_tenant"), + integer("account_no")), + row("eu", 10, "eu", 1), + row("us", 11, "us", 1))), + List.of("Account", "Shipment"), + List.of(data("accountTier", "Account"), relation("shippedTo", "Shipment", "Account")), + identityTable( + "Account", + "accounts", + List.of("tenant", "account_no"), + null, + bound("accountTier", "tier")), + identityTable( + "Shipment", + "shipments", + List.of("tenant", "shipment_no"), + null, + joined( + "shippedTo", + "accounts", + List.of("account_tenant", "account_no"), + List.of("tenant", "account_no")))); + + @Test + void aNullIsNoValueAndARowWithoutAKeyIsNoRecord(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "members"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, MEMBERS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "MemberShape", + "Member", + on(fixture, "email-required", "memberEmail").withMinCount(1), + on(fixture, "email-once", "memberEmail").withMaxCount(1), + on(fixture, "email-listed", "memberEmail") + .withIn(literals("ada@example.org", "grace@example.org")), + on(fixture, "age-range", "memberAge") + .withMinInclusive(limit("0")) + .withMaxInclusive(limit("120"))); + + final OntologyShapeChecks checks = checks(admin(), fixture.type("Member"), DRAFT); + final OntologyShapeCheck required = check(checks, "email-required", MIN_COUNT); + final OntologyShapeCheck once = check(checks, "email-once", MAX_COUNT); + final OntologyShapeCheck listed = check(checks, "email-listed", IN); + final OntologyShapeCheck range = check(checks, "age-range", RANGE); + + final String id = fixture.name("id"); + final String countOfListed = + String.join( + "\n", + "SELECT COUNT(*) AS violations", + "FROM (", + " SELECT DISTINCT t0." + id + " AS k0", + " FROM " + fixture.from("members") + " t0", + " WHERE t0." + id + " IS NOT NULL", + " AND t0." + + fixture.name("email") + + " NOT IN ('ada@example.org', 'grace@example.org')", + ") c"); + assertEquals(CUSTOM_SQL, listed.getTestDefinition()); + assertEquals( + "<#E::table::" + fixture.table("members").getFullyQualifiedName() + ">", + listed.getEntityLink()); + assertEquals(countParameters(countOfListed), listed.getParameterValues()); + assertEquals(List.of(List.of("email")), listed.getColumns()); + for (final OntologyShapeCheck check : List.of(required, once, listed, range)) { + assertCounts("0", NO_KEYS, check); + } + + // Member 3 has no email. Member 4 has one in its second row. The row with no id is no member. + addRows( + fixture, + "members", + row(3, null, null), + row(4, null, 50), + row(4, "ada@example.org", 50), + row(null, "nobody@example.org", 500), + row(5, "intruder@example.org", 200), + row(6, "ada@example.org", 1), + row(6, "grace@example.org", 1), + row(7, "ada@example.org", 2), + row(7, "ada@example.org", 2)); + + assertCounts("1", List.of(List.of("3")), required); + assertCounts("1", List.of(List.of("6")), once); + assertCounts("1", List.of(List.of("5")), listed); + assertCounts("1", List.of(List.of("5")), range); + } + } + + @Test + void aRelationReachesOnlyTheRecordsOfTheClassItNamesOnASharedTable(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "parties"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PARTIES).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "placed-by", "placedBy") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(fixture.type("Person").getIri())); + declare( + ontology, + fixture, + "PersonShape", + "Person", + on(fixture, "name-listed", "personName").withIn(literals("Ada", "Grace"))); + + final OntologyShapeChecks orders = checks(admin(), fixture.type("Order"), DRAFT); + final OntologyShapeCheck placed = check(orders, "placed-by", MIN_COUNT); + final OntologyShapeCheck placedOnce = check(orders, "placed-by", MAX_COUNT); + final OntologyShapeCheck byPerson = check(orders, "placed-by", CLASS); + final OntologyShapeCheck named = + check(checks(admin(), fixture.type("Person"), DRAFT), "name-listed", IN); + + assertEquals( + List.of(read(fixture, "Order", "orders", 1L), read(fixture, "Person", "parties", 1L)), + byPerson.getReadBindings()); + assertEquals(fixture.table("orders").getId(), byPerson.getTable().getId()); + assertEquals(List.of(List.of("party_id")), byPerson.getColumns()); + // Ada placed two orders, and an order still has one person. Initech is no person. + for (final OntologyShapeCheck check : List.of(placed, placedOnce, byPerson, named)) { + assertCounts("0", NO_KEYS, check); + } + + // Order 103 names a party that no row holds, and order 104 an organization. + addRows( + fixture, + "orders", + row(103, 999, new BigDecimal("1.00")), + row(104, 10, new BigDecimal("1.00")), + row(105, null, new BigDecimal("1.00")), + row(106, 1, new BigDecimal("1.00")), + row(106, 2, new BigDecimal("1.00"))); + addRows(fixture, "parties", row(3, "person", "Mallory"), row(11, "org", "Globex")); + + assertCounts("1", List.of(List.of("105")), placed); + assertCounts("1", List.of(List.of("106")), placedOnce); + assertCounts("2", List.of(List.of("103"), List.of("104")), byPerson); + assertCounts("1", List.of(List.of("3")), named); + } + } + + @Test + void aLinkTableGivesARecordItsValuesAndAnOrphanRowGivesNone(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "baskets"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, BASKETS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "contains", "contains") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(fixture.type("Product").getIri()), + on(fixture, "quantity", "itemQuantity").withMinInclusive(limit("1"))); + + final OntologyShapeChecks checks = checks(admin(), fixture.type("Order"), DRAFT); + final OntologyShapeCheck some = check(checks, "contains", MIN_COUNT); + final OntologyShapeCheck one = check(checks, "contains", MAX_COUNT); + final OntologyShapeCheck products = check(checks, "contains", CLASS); + final OntologyShapeCheck quantity = check(checks, "quantity", RANGE); + + assertEquals(fixture.table("order_items").getId(), products.getTable().getId()); + assertEquals( + List.of( + read(fixture, "Order", "orders", 2L), + read(fixture, "Order", "order_items", 2L), + read(fixture, "Product", "products", 1L)), + products.getReadBindings()); + // The same link twice is one value. The rows of orders 7 and 99 belong to no record. + for (final OntologyShapeCheck check : List.of(some, one, products, quantity)) { + assertCounts("0", NO_KEYS, check); + } + + // Order 3 has a row that names no product, and order 6 has no row at all. + addRows(fixture, "orders", row(3, "web"), row(4, "web"), row(5, "web"), row(6, "web")); + addRows( + fixture, + "order_items", + row(2, "A-1", 1), + row(3, null, 1), + row(4, "X-0", 5), + row(5, "B-2", 0)); + + assertCounts("2", List.of(List.of("3"), List.of("6")), some); + assertCounts("1", List.of(List.of("2")), one); + assertCounts("1", List.of(List.of("4")), products); + assertCounts("1", List.of(List.of("5")), quantity); + } + } + + @Test + void aTwoColumnKeyAndATwoColumnJoinAreComparedColumnByColumn(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "shipments"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, SHIPMENTS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "ShipmentShape", + "Shipment", + on(fixture, "shipped-to", "shippedTo") + .withMinCount(1) + .withClassIri(fixture.type("Account").getIri())); + declare( + ontology, + fixture, + "AccountShape", + "Account", + on(fixture, "tier-listed", "accountTier").withIn(literals("gold", "silver"))); + + final OntologyShapeChecks shipments = checks(admin(), fixture.type("Shipment"), DRAFT); + final OntologyShapeCheck shipped = check(shipments, "shipped-to", MIN_COUNT); + final OntologyShapeCheck toAccount = check(shipments, "shipped-to", CLASS); + final OntologyShapeCheck tier = + check(checks(admin(), fixture.type("Account"), DRAFT), "tier-listed", IN); + + assertEquals( + List.of(List.of("account_tenant"), List.of("account_no")), toAccount.getColumns()); + for (final OntologyShapeCheck check : List.of(shipped, toAccount, tier)) { + assertCounts("0", NO_KEYS, check); + } + + // Shipment 12 names half an account, and shipment 13 an account of another tenant. + addRows( + fixture, + "shipments", + row("eu", 12, "eu", null), + row("eu", 13, "us", 2), + row(null, 14, "eu", 9)); + addRows(fixture, "accounts", row("eu", 2, "bronze"), row(null, 3, "bronze")); + + assertCounts("1", List.of(List.of("eu", "12")), shipped); + assertCounts("1", List.of(List.of("eu", "13")), toAccount); + assertCounts("1", List.of(List.of("eu", "2")), tier); + } + } + + @Test + void aListedValueWithAQuoteAndAColonComparesEqualToTheStoredValue(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "listed"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, MEMBERS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "MemberShape", + "Member", + on(fixture, "email-listed", "memberEmail") + .withIn(literals("ada@example.org", "grace@example.org", "O'Brien", "mailto:a :b"))); + + final OntologyShapeCheck listed = + check(checks(admin(), fixture.type("Member"), DRAFT), "email-listed", IN); + assertTrue( + parameter(listed, "sqlExpression").contains("'O''Brien', 'mailto\\:a \\:b')"), + () -> parameter(listed, "sqlExpression")); + assertTrue( + listed.getInspectionQuery().contains("'O''Brien', 'mailto:a :b')"), + listed::getInspectionQuery); + assertCounts("0", NO_KEYS, listed); + + addRows( + fixture, + "members", + row(3, "O'Brien", 1), + row(4, "mailto:a :b", 1), + row(5, "O''Brien", 1)); + + assertCounts("1", List.of(List.of("5")), listed); + } + } + + @Test + void aListedValueIsEqualToAStoredOneWhenTheDatabaseSaysSo(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "collation"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, MEMBERS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "MemberShape", + "Member", + on(fixture, "email-listed", "memberEmail") + .withIn(literals("ada@example.org", "grace@example.org"))); + final boolean mysql = MYSQL.equals(fixture.family()); + final OntologyShapeCheck listed = + check(checks(admin(), fixture.type("Member"), DRAFT), "email-listed", IN); + assertCounts("0", NO_KEYS, listed); + + addRows(fixture, "members", row(3, "ADA@EXAMPLE.ORG", 1)); + + // A Postgres text column tells the cases apart, and so does a MySQL column that compares + // bytes. The same statement on the same rows counts nothing once the column ignores case. + if (mysql) { + collate(fixture, "utf8mb4_bin"); + } + assertCounts("1", List.of(List.of("3")), listed); + if (mysql) { + collate(fixture, "utf8mb4_general_ci"); + assertCounts("0", NO_KEYS, listed); + } + } + } + + /** Gives the email column of the members table of a MySQL database another collation. */ + private static void collate(final OntologyShapeFixture fixture, final String collation) { + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> + handle.execute( + "ALTER TABLE " + + fixture.from("members") + + " MODIFY email VARCHAR(64) CHARACTER SET utf8mb4 COLLATE " + + collation)); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java new file mode 100644 index 000000000000..489e68af7510 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -0,0 +1,278 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.contributing; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.joined; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.relation; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.SqlQueryCounter; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.Entity; +import org.openmetadata.service.monitoring.RequestLatencyContext; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * How many statements {@code GET /v1/ontologyConcepts/{id}/shapeChecks} runs. Each kind of input is + * read once for the answer, so a class with five shapes and forty constraints is read in the + * statements of a class with one shape and one constraint. + */ +@Isolated("Counts the SQL statements that serve one request") +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { + private static final String SELECT = "select"; + private static final String SHAPES = "from ontology_shape_entity"; + private static final String PROPERTIES = "from ontology_property_entity"; + private static final String BINDING_ROWS = "from ontology_concept_binding"; + private static final String RELEASE_MEMBERS = "from ontology_release_member"; + private static final String SETTINGS = "from openmetadata_settings"; + + /** Every statement of one read of the draft, as an administrator, and of the active release. */ + private static final int DRAFT_STATEMENTS = 36; + + private static final int RELEASE_STATEMENTS = 44; + + /** An order class that binds five tables, and a relation that arrives at a sixth. */ + private static final Shape SIX_TABLES = + mapping( + "sixTables", + List.of( + table("orders", List.of(integer("id"), text("channel"))), + table("order_notes", List.of(integer("order_id"), text("note"))), + table("order_flags", List.of(integer("order_id"), text("flag"))), + table("order_tags", List.of(integer("order_id"), text("tag"))), + table( + "order_items", + List.of(integer("order_id"), text("product_sku"), integer("quantity"))), + table("products", List.of(text("sku"), text("title")))), + List.of("Order", "Product"), + List.of( + data("orderChannel", "Order"), + data("orderNote", "Order"), + data("orderFlag", "Order"), + data("orderTag", "Order"), + data("itemQuantity", "Order"), + data("productTitle", "Product"), + relation("contains", "Order", "Product")), + identityTable("Order", "orders", List.of("id"), null, bound("orderChannel", "channel")), + identityTable( + "Product", "products", List.of("sku"), null, bound("productTitle", "title")), + contributing("Order", "order_notes", List.of("order_id"), bound("orderNote", "note")), + contributing("Order", "order_flags", List.of("order_id"), bound("orderFlag", "flag")), + contributing("Order", "order_tags", List.of("order_id"), bound("orderTag", "tag")), + contributing( + "Order", + "order_items", + List.of("order_id"), + bound("itemQuantity", "quantity"), + joined("contains", "product_sku", "products", "sku"))); + + /** The statements of one request, as the server rendered them. */ + private record Reads(OntologyShapeChecks answer, List statements) { + long of(final String fragment) { + return statements.stream().filter(statement -> statement.contains(fragment)).count(); + } + + int constraints() { + return answer.getShapes().stream().mapToInt(shape -> shape.getConstraints().size()).sum(); + } + + /** The tables that the tests of the answer read, the table a relation arrives at included. */ + Set tables() { + return answer.getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .flatMap(constraint -> constraint.getParts().stream()) + .filter(part -> part.getChecks() != null) + .flatMap(part -> part.getChecks().stream()) + .flatMap(check -> check.getReadBindings().stream()) + .map(OntologyShapeCheckBinding::getAssetId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + } + + String listed() { + return String.join("\n", statements); + } + } + + /** A statement and the request that issued it. */ + private record Issued(RequestLatencyContext.RequestContext request, String statement) {} + + /** Asks once to fill what the server caches between requests, then records the next request. */ + private static Reads reads( + final OntologyShapeFixture fixture, final OntologyStatementVersion version) { + checks(admin(), fixture.type("Order"), version); + final List issued = Collections.synchronizedList(new ArrayList<>()); + try (var ignored = + SqlQueryCounter.forRequests( + Entity.getJdbi(), + SELECT, + statement -> + issued.add( + new Issued( + RequestLatencyContext.getContext(), plain(statement.getRenderedSql()))))) { + final OntologyShapeChecks answer = checks(admin(), fixture.type("Order"), version); + return new Reads(answer, ofTheRequestThatReadTheBindings(List.copyOf(issued))); + } + } + + /** + * The statements of the request that read the binding rows. Work that an earlier request left + * running keeps the context of that request, and it reads no binding. A server setting is cached + * for every request, and the request that finds the cached value lapsed reads it again, so a read + * of a setting is not a read for the answer. + */ + private static List ofTheRequestThatReadTheBindings(final List issued) { + final RequestLatencyContext.RequestContext answering = + issued.stream() + .filter(read -> read.statement().contains(BINDING_ROWS)) + .map(Issued::request) + .findFirst() + .orElseThrow(); + return issued.stream() + .filter(read -> read.request() == answering) + .map(Issued::statement) + .filter(statement -> statement.startsWith(SELECT) && !statement.contains(SETTINGS)) + .toList(); + } + + /** A statement in lower case, without the comment that names its method and on one line. */ + private static String plain(final String rendered) { + return rendered + .replaceAll("/\\*.*?\\*/", " ") + .replaceAll("\\s+", " ") + .trim() + .toLowerCase(Locale.ROOT); + } + + /** The first {@code count} of ten constraints that between them rest on all six tables. */ + private static OntologyShapeConstraint[] constraints( + final OntologyShapeFixture fixture, final int count) { + return List.of( + on(fixture, "product", "contains").withClassIri(fixture.type("Product").getIri()), + on(fixture, "channel", "orderChannel").withIn(literals("web", "store")), + on(fixture, "note", "orderNote").withMinCount(1), + on(fixture, "flag", "orderFlag").withMaxCount(1), + on(fixture, "tag", "orderTag").withIn(literals("new", "gift")), + on(fixture, "quantity", "itemQuantity").withMinInclusive(limit("1")), + on(fixture, "some", "contains").withMinCount(1), + on(fixture, "one", "contains").withMaxCount(1), + on(fixture, "noteOnce", "orderNote").withMaxCount(1), + on(fixture, "tagRequired", "orderTag").withMinCount(1)) + .subList(0, count) + .toArray(OntologyShapeConstraint[]::new); + } + + private static List sizes(final Reads reads) { + return List.of(reads.answer().getShapes().size(), reads.constraints(), reads.tables().size()); + } + + @Test + void fortyConstraintsInFiveShapesAreReadInTheStatementsOfOneConstraint(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "shapeReads"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, SIX_TABLES)) { + fixture.bindAll(); + declare(ontology, fixture, "Shape0", "Order", constraints(fixture, 1)); + final Reads one = reads(fixture, DRAFT); + for (int shape = 1; shape < 4; shape++) { + declare(ontology, fixture, "Shape" + shape, "Order", constraints(fixture, 10)); + } + declare(ontology, fixture, "Shape4", "Order", constraints(fixture, 9)); + + final Reads forty = reads(fixture, DRAFT); + + assertEquals(List.of(1, 1, 3), sizes(one)); + assertEquals(List.of(5, 40, 6), sizes(forty)); + assertEquals( + List.of(DRAFT_STATEMENTS, DRAFT_STATEMENTS), + List.of(one.statements().size(), forty.statements().size()), + forty::listed); + assertEquals(1, forty.of(SHAPES), forty::listed); + assertEquals(1, forty.of(PROPERTIES), forty::listed); + assertEquals(2, forty.of(BINDING_ROWS), forty::listed); + assertEquals(0, forty.of(RELEASE_MEMBERS), forty::listed); + } + } + + @Test + void aReleaseWithFortyConstraintsIsReadInTheStatementsOfAnyRelease(final TestNamespace ns) { + final Reads forty = released(ns, "fortyReleased", 5, 8); + + assertEquals(List.of(5, 40, 6), sizes(forty)); + assertReleaseReads(forty); + } + + @Test + void aReleaseWithOneConstraintIsReadInTheStatementsOfAnyRelease(final TestNamespace ns) { + final Reads one = released(ns, "oneReleased", 1, 1); + + assertEquals(List.of(1, 1, 3), sizes(one)); + assertReleaseReads(one); + } + + /** The statements of a read of the active release of a class with this many shapes. */ + private static Reads released( + final TestNamespace ns, final String name, final int shapes, final int constraints) { + final Ontology ontology = createOntology(ns, name); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, SIX_TABLES)) { + fixture.bindAll(); + for (int shape = 0; shape < shapes; shape++) { + declare(ontology, fixture, "Shape" + shape, "Order", constraints(fixture, constraints)); + } + activate(ns, ontology); + return reads(fixture, RELEASE); + } + } + + private static void assertReleaseReads(final Reads reads) { + assertEquals(RELEASE_STATEMENTS, reads.statements().size(), reads::listed); + assertEquals(0, reads.of(SHAPES), reads::listed); + assertEquals(1, reads.of(PROPERTIES), reads::listed); + assertEquals(2, reads.of(BINDING_ROWS), reads::listed); + assertEquals(4, reads.of(RELEASE_MEMBERS), reads::listed); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java new file mode 100644 index 000000000000..0a8972522619 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java @@ -0,0 +1,365 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.CUSTOM_SQL; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.answer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.countParameters; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.goldenCount; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identity; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.keyList; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.read; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.reference; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.CHECK; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.HIDDEN; +import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; +import static org.openmetadata.schema.api.data.OntologyShapePart.IN; +import static org.openmetadata.schema.api.data.OntologyShapePart.MAX_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.MIN_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.policies.Policy; +import org.openmetadata.schema.entity.teams.Role; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; + +/** + * Who gets an answer from {@code GET /v1/ontologyConcepts/{id}/shapeChecks}, and what a reader who + * may not view a table reads in it. The mapping is the link table shape, whose order class has an + * identity table, a link table that holds a relation, and a table the relation arrives at. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckRightsIT extends BaseOntologyApprovalIT { + private static final List TABLES = List.of("orders", "order_items", "products"); + + /** One shape of the order class with a constraint on each of its three properties. */ + private static OntologyShape orderShape( + final Ontology ontology, final OntologyShapeFixture fixture) { + return declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "channel", "orderChannel").withIn(literals("web", "store")), + on(fixture, "contains", "contains") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(fixture.type("Product").getIri()), + on(fixture, "quantity", "itemQuantity").withMinInclusive(limit("1"))); + } + + /** What an answer is about, and what the release it reads holds. */ + private record Scene(OntologyShapeFixture fixture, OntologyShape shape, OntologyRelease release) { + OntologyShapeCheckBinding orders() { + return read(fixture, "Order", "orders", 2L); + } + + OntologyShapeCheckBinding items() { + return read(fixture, "Order", "order_items", 2L); + } + + OntologyShapeCheckBinding products() { + return read(fixture, "Product", "products", 1L); + } + + /** The reader owns the named tables and no other table of the mapping, so views only them. */ + void show(final OpenMetadataClient reader, final Set visible) { + final EntityReference owner = readerReference(reader); + for (final String name : TABLES) { + final String id = fixture.table(name).getId().toString(); + final Table table = admin().tables().get(id, "owners"); + admin() + .tables() + .update(id, table.withOwners(visible.contains(name) ? List.of(owner) : List.of())); + } + } + + /** The whole answer for the order class, with these parts for its three constraints. */ + OntologyShapeChecks answer( + final List channel, + final List contains, + final List quantity) { + return new OntologyShapeChecks() + .withConceptId(fixture.type("Order").getId()) + .withClassIri(fixture.type("Order").getIri()) + .withVersion( + new OntologyStatementVersionRead() + .withKind(OntologyStatementVersion.RELEASE) + .withReleaseId(release.getId()) + .withReleaseRevision(release.getReleaseRevision()) + .withSemanticVersion(release.getSemanticVersion())) + .withShapes( + List.of( + new OntologyCheckedShape() + .withId(shape.getId()) + .withName("OrderShape") + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + List.of( + constraint("channel", "orderChannel", channel), + constraint("contains", "contains", contains), + constraint("quantity", "itemQuantity", quantity))))); + } + + private OntologyCheckedConstraint constraint( + final String id, final String property, final List parts) { + return new OntologyCheckedConstraint() + .withId(id) + .withPath(fixture.property(property).getIri()) + .withParts(parts); + } + + /** + * A part that one generated test checks, with the golden statement of the link table shape. + * + * @param column the bound column of the property on {@code tableName} + * @param read every binding the test read, the binding of {@code tableName} among them + */ + OntologyCheckedPart checked( + final String constraint, + final OntologyShapePart part, + final String golden, + final String tableName, + final String column, + final List read) { + final String count = goldenCount(fixture, golden); + final OntologyShapeCheckBinding holder = + read.stream() + .filter(binding -> binding.getAssetId().equals(fixture.table(tableName).getId())) + .findFirst() + .orElseThrow(); + return new OntologyCheckedPart() + .withPart(part) + .withOutcome(CHECK) + .withChecks( + List.of( + new OntologyShapeCheck() + .withIdentity(identity(shape, constraint, part, holder, List.of(column))) + .withTable(reference(fixture, tableName)) + .withColumns(List.of(List.of(column))) + .withTestDefinition(CUSTOM_SQL) + .withEntityLink( + "<#E::table::" + fixture.table(tableName).getFullyQualifiedName() + ">") + .withParameterValues(countParameters(count)) + .withInspectionQuery(keyList(count)) + .withReadBindings(read))); + } + + List channelChecked() { + return List.of( + checked( + "channel", IN, "linkTable-orderChannel-in", "orders", "channel", List.of(orders()))); + } + + List quantityChecked() { + return List.of( + checked( + "quantity", + RANGE, + "linkTable-itemQuantity-range", + "order_items", + "quantity", + List.of(orders(), items()))); + } + + List containsChecked() { + final List toProducts = List.of(orders(), items(), products()); + return List.of( + checked( + "contains", + MIN_COUNT, + "linkTable-contains-minCount", + "order_items", + "product_sku", + List.of(orders(), items())), + checked( + "contains", + MAX_COUNT, + "linkTable-contains-maxCount", + "order_items", + "product_sku", + List.of(orders(), items())), + checked( + "contains", + CLASS, + "linkTable-contains-class", + "order_items", + "product_sku", + toProducts)); + } + } + + private static List hidden(final OntologyShapePart... parts) { + final List entries = new ArrayList<>(); + for (final OntologyShapePart part : parts) { + entries.add(new OntologyCheckedPart().withPart(part).withOutcome(HIDDEN)); + } + return entries; + } + + /** The body is exactly the expected answer, and it names nothing of the hidden table. */ + private static void assertAnswer( + final OntologyShapeChecks expected, final String body, final Table... hidden) { + assertEquals(JsonUtils.readTree(JsonUtils.pojoToJson(expected)), JsonUtils.readTree(body)); + for (final Table table : hidden) { + assertFalse(body.contains(table.getName()), body); + assertFalse(body.contains(table.getId().toString()), body); + } + } + + @Test + void aReaderWhoMayNotViewATableReadsHiddenForEveryConstraintThatRestsOnIt( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenTables"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("checkTables" + ns.shortPrefix())) { + fixture.bindAll(); + final OntologyShape shape = orderShape(ontology, fixture); + final Scene scene = new Scene(fixture, shape, current(activate(ns, ontology))); + final OpenMetadataClient reader = ownerReader(access, Entity.TABLE); + final var order = fixture.type("Order"); + + assertAnswer( + scene.answer(scene.channelChecked(), scene.containsChecked(), scene.quantityChecked()), + answer(admin(), order, null)); + + scene.show(reader, Set.of("order_items", "products")); + assertAnswer( + scene.answer(hidden(IN), hidden(MIN_COUNT, MAX_COUNT, CLASS), hidden(RANGE)), + answer(reader, order, null), + fixture.table("orders"), + fixture.table("order_items"), + fixture.table("products")); + + scene.show(reader, Set.of("orders", "products")); + assertAnswer( + scene.answer(scene.channelChecked(), hidden(MIN_COUNT, MAX_COUNT, CLASS), hidden(RANGE)), + answer(reader, order, null), + fixture.table("order_items"), + fixture.table("products")); + + scene.show(reader, Set.of("orders", "order_items")); + assertAnswer( + scene.answer( + scene.channelChecked(), hidden(MIN_COUNT, MAX_COUNT, CLASS), scene.quantityChecked()), + answer(reader, order, null), + fixture.table("products")); + + scene.show(reader, Set.of("orders", "order_items", "products")); + assertAnswer( + scene.answer(scene.channelChecked(), scene.containsChecked(), scene.quantityChecked()), + answer(reader, order, null)); + } + } + + @Test + void aDraftReadTakesEditRightsAndAReleaseReadTakesAnActiveRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "checkVersionRights"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("checkDraft" + ns.shortPrefix())) { + fixture.bindAll(); + final OntologyShape shape = orderShape(ontology, fixture); + final OpenMetadataClient consumer = client(access.userToken("consumer", List.of())); + final String name = readerReference(consumer).getName(); + final var order = fixture.type("Order"); + + assertRefused( + 404, + "Ontology " + ontology.getFullyQualifiedName() + " has no active release", + () -> checks(consumer, order, null)); + assertRefused( + 403, + "Principal: CatalogPrincipal{name='" + name + "'} operations [EditAll] not allowed", + () -> checks(consumer, order, DRAFT)); + final Scene scene = new Scene(fixture, shape, current(activate(ns, ontology))); + + assertAnswer( + scene.answer(scene.channelChecked(), scene.containsChecked(), scene.quantityChecked()), + answer(consumer, order, RELEASE)); + assertRefused( + 403, + "Principal: CatalogPrincipal{name='" + name + "'} operations [EditAll] not allowed", + () -> checks(consumer, order, DRAFT)); + assertEquals(DRAFT, checks(admin(), order, DRAFT).getVersion().getKind()); + } + } + + @Test + void aReaderWhoMayNotViewTheClassIsRefusedOnEitherVersion(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "checkHiddenClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("checkClass" + ns.shortPrefix())) { + fixture.bindAll(); + orderShape(ontology, fixture); + activate(ns, ontology); + final Role denied = access.denyRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT); + final Policy policy = + admin().policies().get(denied.getPolicies().getFirst().getId().toString(), "rules"); + final OpenMetadataClient reader = client(access.userToken("reader", List.of(denied.getId()))); + final String refusal = + "Principal: CatalogPrincipal{name='" + + readerReference(reader).getName() + + "'} operation ViewBasic denied by role " + + denied.getName() + + ", policy " + + policy.getName() + + ", rule " + + policy.getRules().getFirst().getName(); + + for (final OntologyStatementVersion version : List.of(RELEASE, DRAFT)) { + assertRefused(403, refusal, () -> checks(reader, fixture.type("Order"), version)); + } + } + } +} From 2cbd4c427f7965d6628c53a15d4ec9092d2f90be Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 18:33:57 -0800 Subject: [PATCH 080/203] Record how an answer is read, refused and masked The record now says why a check never names a stale binding revision, that each kind of input is read once and how many statements that is, that an answer over too many tables or shapes is refused, and what a hidden constraint tells. --- ...ape-check-is-exact-or-it-is-not-offered.md | 40 +++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index a34beadfdfc7..80bffc5dfffc 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-11-23 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyShapeCheckCompilerTest`, `OntologyPortablePatternTest` +- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckReadsIT` (the reads) - **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) ## Context @@ -96,8 +96,9 @@ timestamp column. A range on a column whose values have no order the server know the threshold `0`, so the query returns one number and the test passes exactly when the number is 0. The strategy `ROWS` would bring one row for each violation to the runner. The count query has no `ORDER BY` and no row limit. A second query, `inspectionQuery`, lists the keys of the records in -violation for a person to read. Every column in both is qualified with its table alias, every table -is in one database, and no label, comment or name of an ontology term reaches the text. A value +violation for a person to read. It has no order and no row limit either, so a person who runs it on +a large table adds a limit. Every column in both is qualified with its table alias, every table is +in one database, and no label, comment or name of an ontology term reaches the text. A value reaches the text only as a typed value (ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). @@ -116,7 +117,8 @@ family has no such operator. A refused pattern is `notEnforceable`. identity table where the join arrives. The query counts the values that match no record of that class, so it carries the row filter of that binding and its non-null key. When a subclass of that class has its identity table on the same table and the binding of the class has a row filter, the -filter may leave out records of the subclass, and the part is `notEnforceable`. +filter may leave out records of the subclass, and the part is `notEnforceable`. The subclass steps +are the named ones of the version that is read, so a release answers as it was sealed. **`datatype` is settled by the column's type.** It supports `xsd:string`, `xsd:boolean`, `xsd:integer`, `xsd:decimal`, `xsd:double`, `xsd:float`, `xsd:date`, `xsd:time` and @@ -130,7 +132,7 @@ holds decimals. When every value of the column's type is a value of the datatype |---|---| | `noIdentityTable` | The class has no identity table, so it has no records. | | `severalTables` | `minCount` above 0 or `maxCount` on a property that the class binds in several places. The count would run over all of them at once. | -| `boundOnInverse` | The class does not bind the relation, and another class binds its inverse. | +| `boundOnInverse` | The class binds the relation in no table, and a class binds the inverse that the relation declares, in an identity table or a contributing table. | | `noJoin`, `joinNotConfirmed` | The relation has no join, or one that is only inferred. Only a confirmed join is read. | | `notARelation`, `notADataProperty` | `class` on a data property, or `datatype`, `range`, `in` or `pattern` on a relation. | | `targetClassNotOnJoin` | The class of the constraint has no identity table where the join arrives. | @@ -157,10 +159,34 @@ by a separator that none of them can hold. A check also lists the class, the tab revision of every binding it read. A check belongs to the table whose binding holds the property, the link table included. +**A check never names a stale revision.** A binding write commits its rows and its revision in one +transaction. The answer reads the revisions of the class and of every class a `class` part names, +then their binding rows, then the revisions again. When the two reads differ it starts over, and +after three attempts it answers 409. So every row that a check was compiled from belongs to the +revision the check names. A binding that does not exist has no revision to name: a subclass that +binds the filtered table later changes the answer, and a caller sees it when it asks again. + +**Each kind of input is read once.** After the class and the version, one request reads the shapes +that target the class, the properties their constraints name, the classes their `class` parts +name, the binding rows, and the tables those rows name. The number of statements does not grow +with the number of shapes or of constraints. For a class with 5 shapes, 40 constraints and 6 +tables, an administrator's request runs 36 `SELECT` statements from the draft and 44 from a +release, as many as for one shape with one constraint. Of these, 23 read the tables with what the +check of the right to view them needs. A server setting whose cached value has lapsed is read on +top of them. Two questions cost further reads, and only when a constraint asks them: the declared +inverse of a relation that the class binds nowhere, and a subclass on a filtered identity table +that a `class` part arrives at. + +**An answer is whole or it is refused.** A class that binds more than 100 tables, and a draft +class that more than 1,000 shapes name, get 409. An answer built from a part of them would leave a +constraint unchecked or a count short. + **What a caller may not view is masked after the compile.** The compile is the same for every caller. A constraint whose answer rests on a table the caller may not view, which is the identity -table, a table that binds the property or the table a join arrives at, has every part `hidden`, -with no check, no reason and no column. No table name appears anywhere else in the response. +table, a table that binds the property in whatever role, or the table a join arrives at, has every +part `hidden`, with no check, no reason and no column. A hidden constraint has one entry for each +part, so it does not tell how many tables answered. No table name appears anywhere else in the +response. ## Consequences From e0d3d143acfb45ec6b1f1ba290cceb312142562b Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 23 Nov 2026 19:12:18 -0800 Subject: [PATCH 081/203] Test the reads behind an answer about shape checks A binding write that lands while the rows are read makes the reader read them again, so a check never names a stale revision. Bindings that change on every read are refused, and so is a class that binds more tables, or that more shapes name, than one answer reads. The decision record names the test as a guard. --- ...ape-check-is-exact-or-it-is-not-offered.md | 2 +- .../OntologyShapeCheckReaderTest.java | 188 ++++++++++++++++++ 2 files changed, 189 insertions(+), 1 deletion(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index 80bffc5dfffc..d08bfae64be5 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-11-23 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckReadsIT` (the reads) +- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckReadsIT` (the reads) - **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) ## Context diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java new file mode 100644 index 000000000000..32828c5e3394 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java @@ -0,0 +1,188 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import jakarta.ws.rs.ClientErrorException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyBindingAccess.TableViews; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Asked; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Read; + +/** + * What an answer is read from: the binding revision its rows were read under, the shapes that + * target the class, and the classes that get no answer because one read cannot hold all of theirs. + */ +class OntologyShapeCheckReaderTest { + private static final UUID ORDER = UUID.fromString("00000000-0000-0000-0000-00000000000a"); + private static final UUID ONTOLOGY = UUID.fromString("00000000-0000-0000-0000-0000000000f0"); + private static final URI ORDER_IRI = URI.create("https://example.org/shop#Order"); + private static final URI PRODUCT_IRI = URI.create("https://example.org/shop#Product"); + private static final Asked DRAFT_ORDER = + new Asked(ORDER, ORDER_IRI, ONTOLOGY, new OntologyVersion.Draft(7L)); + + private final OntologyConceptBindingStore store = mock(OntologyConceptBindingStore.class); + private final OntologyBindingAccess catalog = mock(OntologyBindingAccess.class); + private final OntologyShapeCheckReader reader = new OntologyShapeCheckReader(store, catalog); + + /** Every table that is asked for exists, and the caller may view it. */ + @BeforeEach + void everyTableExists() { + when(catalog.tableViews(any(), anyCollection())) + .thenAnswer( + call -> { + final Map live = + call.>getArgument(1).stream() + .distinct() + .collect(Collectors.toMap(id -> id, id -> new Table().withId(id))); + return new TableViews(live, live.keySet()); + }); + } + + @Test + void anAnswerNamesTheRevisionItsRowsWereReadUnder() { + final BindingRow orders = row(1, OntologyBindingRole.IDENTITY); + final BindingRow items = row(2, OntologyBindingRole.CONTRIBUTING); + when(store.revisions(anyCollection())).thenReturn(Map.of(ORDER, 4L)); + when(store.identityFirstTables(List.of(ORDER), 101)).thenReturn(List.of(orders, items)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(Map.of(ORDER, 4L), read.facts().revisions()); + assertEquals(List.of(orders, items), rows(read)); + assertEquals(Set.of(), read.hidden()); + } + + @Test + void aBindingWriteThatLandsWhileTheRowsAreReadMakesTheReaderReadThemAgain() { + final BindingRow before = row(1, OntologyBindingRole.IDENTITY); + final BindingRow after = row(2, OntologyBindingRole.IDENTITY); + when(store.revisions(anyCollection())) + .thenReturn(Map.of(ORDER, 4L), Map.of(ORDER, 5L), Map.of(ORDER, 5L)); + when(store.identityFirstTables(List.of(ORDER), 101)) + .thenReturn(List.of(before), List.of(after)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(Map.of(ORDER, 5L), read.facts().revisions()); + assertEquals(List.of(after), rows(read)); + } + + @Test + void bindingsThatChangeOnEveryReadGiveNoAnswer() { + when(store.revisions(anyCollection())) + .thenReturn( + Map.of(ORDER, 1L), + Map.of(ORDER, 2L), + Map.of(ORDER, 3L), + Map.of(ORDER, 4L), + Map.of(ORDER, 5L), + Map.of(ORDER, 6L)); + + assertRefused( + "The table bindings changed while the answer was built. Ask again", + () -> reader.read(null, DRAFT_ORDER)); + } + + @Test + void aClassThatBindsMoreTablesThanAnAnswerReadsGivesNoAnswer() { + final List rows = new ArrayList<>(); + rows.add(row(1, OntologyBindingRole.IDENTITY)); + IntStream.rangeClosed(2, 101) + .forEach(table -> rows.add(row(table, OntologyBindingRole.CONTRIBUTING))); + when(store.identityFirstTables(List.of(ORDER), 101)).thenReturn(rows, rows.subList(0, 100)); + + assertRefused( + "Class https://example.org/shop#Order binds more than 100 tables", + () -> reader.read(null, DRAFT_ORDER)); + assertEquals(rows.subList(0, 100), rows(reader.read(null, DRAFT_ORDER))); + } + + @Test + void aDraftClassThatMoreShapesNameThanOneStatementReadsGivesNoAnswer() { + final List naming = + IntStream.rangeClosed(1, 1001) + .mapToObj(shape -> shape(shape, "s" + shape, PRODUCT_IRI)) + .toList(); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, 1001)) + .thenReturn(naming, naming.subList(0, 1000)); + + assertRefused( + "More than 1000 shapes name class https://example.org/shop#Order", + () -> reader.read(null, DRAFT_ORDER)); + assertEquals(List.of(), reader.read(null, DRAFT_ORDER).shapes()); + } + + @Test + void theShapesOfAnAnswerAreTheOnesThatTargetTheClassInNameOrder() { + final OntologyShape second = shape(1, "b", ORDER_IRI); + final OntologyShape first = shape(2, "a", ORDER_IRI); + final OntologyShape namesItInAConstraint = shape(3, "c", PRODUCT_IRI); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, 1001)) + .thenReturn(List.of(second, namesItInAConstraint, first)); + + assertEquals(List.of(first, second), reader.read(null, DRAFT_ORDER).shapes()); + } + + private static void assertRefused(final String message, final Runnable read) { + final ClientErrorException refused = assertThrows(ClientErrorException.class, read::run); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals(message, refused.getMessage()); + } + + /** The binding rows of the tables of the class that an answer was read from, in its order. */ + private static List rows(final Read read) { + return read.facts().subject().tables().stream().map(MappedTable::row).toList(); + } + + private static BindingRow row(final int table, final OntologyBindingRole role) { + return new BindingRow( + ORDER, + new UUID(0, table), + OntologyBindingAssetType.TABLE, + "hash" + table, + List.of(), + role, + List.of(List.of("id")), + null); + } + + private static OntologyShape shape(final int id, final String name, final URI target) { + return new OntologyShape().withId(new UUID(1, id)).withName(name).withTargetConcept(target); + } +} From e7dae11784e31be0d4f7c1d10fefba089f44bb61 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 12:29:47 -0800 Subject: [PATCH 082/203] Check every part of a shape with a generated query A check is now always the table test that runs a statement written for it. The column tests for a missing value, a listed value, a range and a pattern are no longer offered, and the conditions that only they needed are gone with them. A pattern gets a statement on the Postgres service type only. Each wildcard is written as every character but a line break, and the value is matched as text under the code point collation, so a range in a class goes by code point whatever the column says. A datatype is held only where no value that the engine stores in the column type can break it. The table of such types is now by engine family, and it drops the types that store NaN, infinity, the zero date, a time outside the day or a number that no boolean is. --- .../service/ontology/OntologyBuiltinTest.java | 99 ---- .../service/ontology/OntologyCheckGates.java | 42 +- .../service/ontology/OntologyCheckProbe.java | 11 +- .../ontology/OntologyDeclaredKeys.java | 26 +- .../ontology/OntologyHeldDatatypes.java | 138 +++++ .../service/ontology/OntologyPartOutcome.java | 18 +- .../ontology/OntologyPortablePattern.java | 53 +- .../OntologyShapeCardinalityRules.java | 48 +- .../ontology/OntologyShapeCheckAnswer.java | 69 ++- .../ontology/OntologyShapeCheckSql.java | 26 +- .../ontology/OntologyShapeValueRules.java | 267 ++------- .../service/ontology/sql/TypedStatement.java | 5 +- .../ontology/OntologyPortablePatternTest.java | 46 +- .../OntologyShapeCheckAnswerTest.java | 179 ++++-- .../OntologyShapeCheckCompilerTest.java | 529 +++++++++++++----- .../OntologyShapeCheckGoldenTest.java | 38 +- .../ontology/OntologyShapeCheckGoldens.java | 17 +- .../ontology/OntologyShapeCheckSqlTest.java | 48 +- .../ontology/sql/TypedStatementTest.java | 4 +- .../compositeKey-accountTier-pattern.sql | 9 + .../filteredIdentity-personName-pattern.sql | 8 + ...peatedContribution-addressCity-pattern.sql | 8 + ...filteredIdentity-customerEmail-pattern.sql | 7 + .../schema/api/data/ontologyShapeChecks.json | 22 +- 24 files changed, 1033 insertions(+), 684 deletions(-) delete mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBuiltinTest.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHeldDatatypes.java create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql create mode 100644 openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBuiltinTest.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBuiltinTest.java deleted file mode 100644 index bd20ebf61ec1..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBuiltinTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2026 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.ontology; - -import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.List; -import java.util.Set; -import org.openmetadata.common.utils.CommonUtil; -import org.openmetadata.schema.entity.data.Table; -import org.openmetadata.schema.tests.TestCaseParameterValue; -import org.openmetadata.schema.tests.TestDefinition; -import org.openmetadata.schema.type.Column; -import org.openmetadata.schema.type.ColumnDataType; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test; -import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; -import org.openmetadata.service.util.FullyQualifiedName; - -/** - * The column test definitions the catalog ships with that a shape check can use. Each reads the - * column data types its definition supports from the seed file the catalog loads the definition - * from, because creating a test on any other type is refused. - */ -enum OntologyBuiltinTest { - NOT_NULL("columnValuesToBeNotNull"), - IN_SET("columnValuesToBeInSet"), - BETWEEN("columnValuesToBeBetween"), - MATCH_REGEX("columnValuesToMatchRegex"); - - /** The table test that runs a statement written for the check. */ - static final String CUSTOM_SQL = "tableCustomSQLQuery"; - - private static final String SEED_FILE = "json/data/tests/%s.json"; - private static final String COLUMNS_FIELD = "columns"; - private final String definition; - private final Set supported; - - OntologyBuiltinTest(final String definition) { - this.definition = definition; - this.supported = Set.copyOf(listOrEmpty(seed(definition).getSupportedDataTypes())); - } - - private static TestDefinition seed(final String definition) { - try { - return JsonUtils.readValue( - CommonUtil.getResourceAsStream( - OntologyBuiltinTest.class.getClassLoader(), String.format(SEED_FILE, definition)), - TestDefinition.class); - } catch (final IOException unread) { - throw new UncheckedIOException(unread); - } - } - - /** - * True when the definition takes a test on the column: it is a column of the table itself and - * not a field inside one, and the definition supports its data type. - */ - boolean takes(final List path, final Column column) { - return path.size() == 1 && supported.contains(column.getDataType()); - } - - /** The test on one column of the table, with its parameters. */ - Test.Builtin on( - final Table table, final String column, final List parameters) { - final String link = - new EntityLink( - Entity.TABLE, - table.getFullyQualifiedName(), - COLUMNS_FIELD, - FullyQualifiedName.quoteName(column), - null) - .getLinkString(); - return new Test.Builtin(definition, link, parameters); - } - - /** The link of a test on the table as a whole. */ - static String tableLink(final Table table) { - return new EntityLink(Entity.TABLE, table.getFullyQualifiedName()).getLinkString(); - } - - static TestCaseParameterValue parameter(final String name, final String value) { - return new TestCaseParameterValue().withName(name).withValue(value); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java index 7e52ad946dcb..6ab972820896 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java @@ -36,7 +36,6 @@ import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; import org.openmetadata.service.ontology.OntologyPartOutcome.Check; import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test; import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; @@ -53,12 +52,8 @@ final class OntologyCheckGates { private OntologyCheckGates() {} - /** - * The records of a class: its identity table as a statement reads it. - * - * @param simple true when every row of the table is one record and every record is one row - */ - record Records(ReadTable identity, boolean simple) {} + /** The records of a class: its identity table as a statement reads it. */ + record Records(ReadTable identity) {} /** * How a statement gets from the records of a class to the table that holds a property. @@ -74,10 +69,7 @@ static boolean isRelation(final OntologyProperty property) { static OntologySettled records(final Subject subject) { return subject .identity() - .map( - identity -> - readTable(identity) - .map(read -> new Records(read, OntologyDeclaredKeys.isSimple(identity)))) + .map(identity -> readTable(identity).map(Records::new)) .orElseGet(() -> refused(OntologyShapeCheckReason.NO_IDENTITY_TABLE)); } @@ -201,23 +193,23 @@ static OntologySettled withOuterJoin(final Reach reach) { OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); } - /** One test on the table of a place, with every binding row it was built from. */ + /** + * One test on the table of a place, with every binding row it was built from: the tables its + * statement reads to reach its values, then each of {@code others}. + */ static OntologyPartOutcome check( final Place place, final List> columns, - final Test test, - final List read) { - final List rows = new ArrayList<>(read.stream().map(MappedTable::row).toList()); - if (!rows.contains(place.holder().row())) { - rows.add(place.holder().row()); + final OntologyCheckProbe probe, + final MappedTable... others) { + final Reach reach = probe.reach(); + final List rows = new ArrayList<>(List.of(reach.identity().table().row())); + if (reach.joinsHolder()) { + rows.add(reach.holder().table().row()); } - return new Check(List.of(new TableCheck(place, columns, test, List.copyOf(rows)))); - } - - /** The tables a generated test reads to reach its values. */ - static List read(final Reach reach) { - return reach.joinsHolder() - ? List.of(reach.identity().table(), reach.holder().table()) - : List.of(reach.identity().table()); + for (final MappedTable other : others) { + rows.add(other.row()); + } + return new Check(List.of(new TableCheck(place, columns, probe, List.copyOf(rows)))); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java index ac2219e1ed91..b84e961dc9ab 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java @@ -22,7 +22,7 @@ import org.openmetadata.service.ontology.sql.TypedValue; /** - * Which records of a class a generated test counts. The compile makes one only from a mapping it + * Which records of a class a test counts. The compile makes one only from a mapping it * has checked: every column a probe names is in its table, every filter and value is parsed, and * every table is in one database on an engine that statements are written for. {@link * OntologyShapeCheckSql} writes the statement and can refuse nothing. @@ -69,6 +69,15 @@ record OutsideRange( Reach reach, List column, Optional min, Optional max) implements OntologyCheckProbe {} + /** + * Records with a value in {@code column} that {@code pattern} does not match. The compile makes + * one for the Postgres service type only, and the statement is written in its syntax. + * + * @param pattern the regular expression as Postgres reads it, a text value of the column + */ + record Unmatched(Reach reach, List column, TypedValue pattern) + implements OntologyCheckProbe {} + /** * Records with a value of a relation that is no record of the class the relation must reach. * diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java index 3254c61ebb7e..c6cde820860b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java @@ -22,38 +22,24 @@ import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnConstraint; -import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; /** * What the keys that the catalog declares on a table say about the records a binding makes of its - * rows. A declaration is taken at its word: whether the engine checks the key is not asked - * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A primary key is declared by a - * table constraint, or by the column constraint on the one column that carries it. + * rows. A declaration is taken at its word, whether the database or a person made it and whether + * or not the engine enforces it (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A + * primary key is declared by a table constraint, or by the column constraint on the one column + * that carries it. */ final class OntologyDeclaredKeys { private OntologyDeclaredKeys() {} - /** - * True when every row of the table is one record of the class and every record is one row: the - * table is the identity table, its binding has no row filter, and the columns of its declared - * primary key are exactly its subject key. A test that reads the rows of such a table reads the - * records. - */ - static boolean isSimple(final MappedTable table) { - final List> key = table.keyPaths(); - return table.row().role() == OntologyBindingRole.IDENTITY - && table.row().rowFilter() == null - && !key.isEmpty() - && key.stream().allMatch(path -> path.size() == 1) - && primaryKeys(table.table()).contains(topLevel(key)); - } - /** * True when the table holds at most one row for each value of its subject key, because a - * declared primary or unique key lies inside the subject key columns. + * declared primary or unique key lies inside the subject key columns. A key with a column + * outside the subject key says nothing: two rows can share the subject key and differ there. */ static boolean oneRowPerKey(final MappedTable table) { final Set key = topLevel(table.keyPaths()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHeldDatatypes.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHeldDatatypes.java new file mode 100644 index 000000000000..599c7f59d524 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHeldDatatypes.java @@ -0,0 +1,138 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static java.util.Map.entry; + +import java.net.URI; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * The column types that store nothing but values of a datatype, by engine family + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). The catalog gives one name to types + * that differ between engines, so a line names the families on which every type of that name was + * read. A column of a service type with no family is held for no datatype. + * + *

    The lines that are missing are missing on purpose. A fixed-point column of Postgres stores + * {@code NaN}, and its dates and timestamps store {@code infinity}. The MySQL family stores a + * boolean as a number from -128 to 127, a time of {@code 25:00:00} and the zero date. A {@code + * TIMESTAMP} column of SQL Server is a row version. The Databricks source reads a {@code decimal} + * column as a type that the catalog names {@code INT}. A {@code FLOAT} column has 32 bits on one + * engine and 64 on another, so it can hold a number that no {@code xsd:float} is. {@code DOUBLE} + * also names a decimal floating-point type. Every text type stores control characters that {@code + * xsd:string} leaves out. + */ +final class OntologyHeldDatatypes { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + + private static final Set EVERY_FAMILY = EnumSet.allOf(SqlEngineFamily.class); + private static final Set WITH_A_BOOLEAN_TYPE = + EnumSet.complementOf(EnumSet.of(SqlEngineFamily.MYSQL, SqlEngineFamily.TSQL)); + private static final Set WITH_FINITE_FIXED_POINT = + EnumSet.complementOf(EnumSet.of(SqlEngineFamily.POSTGRES)); + private static final Set WITH_INT_FOR_WHOLE_NUMBERS_ONLY = + EnumSet.complementOf(EnumSet.of(SqlEngineFamily.SPARK)); + private static final Set WITH_CALENDAR_VALUES_ONLY = + EnumSet.of(SqlEngineFamily.BIGQUERY, SqlEngineFamily.TSQL); + + private static final Map> HOLDS_ONLY = + Map.ofEntries( + entry(XSD + "boolean", List.of(held(WITH_A_BOOLEAN_TYPE, ColumnDataType.BOOLEAN))), + entry( + XSD + "integer", + List.of( + held( + EVERY_FAMILY, + ColumnDataType.TINYINT, + ColumnDataType.BYTEINT, + ColumnDataType.SMALLINT, + ColumnDataType.BIGINT, + ColumnDataType.LARGEINT), + held(WITH_INT_FOR_WHOLE_NUMBERS_ONLY, ColumnDataType.INT), + withNoFraction( + WITH_FINITE_FIXED_POINT, ColumnDataType.DECIMAL, ColumnDataType.NUMERIC))), + entry( + XSD + "decimal", + List.of( + held( + EVERY_FAMILY, + ColumnDataType.TINYINT, + ColumnDataType.BYTEINT, + ColumnDataType.SMALLINT, + ColumnDataType.INT, + ColumnDataType.BIGINT, + ColumnDataType.LARGEINT), + held(WITH_FINITE_FIXED_POINT, ColumnDataType.DECIMAL, ColumnDataType.NUMERIC))), + entry(XSD + "double", List.of(held(EVERY_FAMILY, ColumnDataType.FLOAT))), + entry(XSD + "float", List.of()), + entry(XSD + "string", List.of()), + entry(XSD + "date", List.of(held(WITH_CALENDAR_VALUES_ONLY, ColumnDataType.DATE))), + entry(XSD + "time", List.of(held(WITH_CALENDAR_VALUES_ONLY, ColumnDataType.TIME))), + entry( + XSD + "dateTime", + List.of( + held(WITH_CALENDAR_VALUES_ONLY, ColumnDataType.DATETIME), + held(EnumSet.of(SqlEngineFamily.BIGQUERY), ColumnDataType.TIMESTAMP)))); + + private OntologyHeldDatatypes() {} + + /** + * One line of the table: on each of {@code families}, a column of one of {@code types} stores + * nothing but values of the datatype. + * + * @param noFraction true when that is so only for a column with a scale of zero + */ + private record Held( + Set families, Set types, boolean noFraction) { + boolean covers(final SqlEngineFamily family, final Column column) { + final boolean whole = column.getScale() != null && column.getScale() == 0; + return families.contains(family) + && types.contains(column.getDataType()) + && (!noFraction || whole); + } + } + + private static Held held( + final Set families, + final ColumnDataType first, + final ColumnDataType... rest) { + return new Held(families, EnumSet.of(first, rest), false); + } + + private static Held withNoFraction( + final Set families, + final ColumnDataType first, + final ColumnDataType... rest) { + return new Held(families, EnumSet.of(first, rest), true); + } + + /** True when the table has lines for the datatype, which may be none. */ + static boolean reads(final URI datatype) { + return HOLDS_ONLY.containsKey(datatype.toString()); + } + + /** True when every value that a column of a service of the type stores is of the datatype. */ + static boolean holdsOnly(final String serviceType, final URI datatype, final Column column) { + final List lines = HOLDS_ONLY.getOrDefault(datatype.toString(), List.of()); + return SqlEngineFamily.forServiceType(serviceType) + .filter(family -> lines.stream().anyMatch(line -> line.covers(family, column))) + .isPresent(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java index 9330b74fa4a1..6ce058fe68c6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java @@ -15,7 +15,6 @@ import java.util.List; import org.openmetadata.schema.api.data.OntologyShapeCheckReason; -import org.openmetadata.schema.tests.TestCaseParameterValue; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; @@ -38,20 +37,13 @@ record NotMapped() implements OntologyPartOutcome {} record NotEnforceable(OntologyShapeCheckReason reason) implements OntologyPartOutcome {} /** - * One test on the table that holds the property. + * One test on the table that holds the property: a statement written for the part, which counts + * the records in violation. * * @param columns the columns of that table whose values the test reads + * @param probe which records the statement counts * @param read every binding row the test was built from */ - record TableCheck(Place place, List> columns, Test test, List read) {} - - /** What runs: a test definition the catalog ships with, or a statement written for the part. */ - sealed interface Test { - /** A column test, as a request to create a test case takes it. */ - record Builtin(String definition, String entityLink, List parameters) - implements Test {} - - /** A statement that counts the records in violation. */ - record Generated(OntologyCheckProbe probe) implements Test {} - } + record TableCheck( + Place place, List> columns, OntologyCheckProbe probe, List read) {} } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java index a5b36e88b3f9..75db3efa8a62 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java @@ -13,13 +13,15 @@ package org.openmetadata.service.ontology; +import java.util.BitSet; +import java.util.Optional; import java.util.regex.Pattern; -import org.openmetadata.service.ontology.sql.SqlEngineFamily; /** - * The regular expressions that every engine a regex test runs on reads alike - * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). Engines differ in what they add to - * the common core, so a pattern is taken only when it stays inside it: + * The regular expressions that an engine can match as SHACL does + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). SHACL reads a pattern as the + * {@code matches} function of XPath does with no flag. Engines differ in what they add to a + * common core, so a pattern is taken only when it stays inside it: * *

      *
    • it starts with {@code ^} and ends with {@code $}, and holds no other anchor; @@ -33,34 +35,52 @@ * * An alternation outside a group is refused because {@code ^a|b$} anchors one branch each on an * engine that searches and both on an engine that matches the whole value. + * + *

      Postgres is the one engine that was run against every construct of the core. It reads one of + * them in another way: its {@code .} matches a line feed and a carriage return, and the one of + * XPath matches neither. So a pattern is written for Postgres with the class of every character + * but those two in place of each {@code .}. The rest it reads as XPath does. {@code $} matches at + * the very end only, a range in a class goes by code point whatever the collation, a negated + * class matches a line break, and a backslash before a punctuation character is that character. */ final class OntologyPortablePattern { - private static final Pattern LETTER = Pattern.compile("[A-Za-z]"); private static final Pattern COUNT = Pattern.compile("0|[1-9][0-9]{0,2}"); + private static final String ANY_BUT_A_LINE_BREAK = "[^\\n\\r]"; private static final String QUANTIFIERS = "?*+{"; private static final int MOST_REPEATS = 255; private static final char LAST_ASCII = '~'; private final String body; + + /** Where the body holds a {@code .} that stands for a character. */ + private final BitSet wildcards = new BitSet(); + private int at; private OntologyPortablePattern(final String body) { this.body = body; } - /** True when the engines of {@code family} match the pattern as every other family does. */ - static boolean reads(final String pattern, final SqlEngineFamily family) { - // REGEXP ignores the case of a letter under most collations of the MySQL family. - final boolean foldsCase = family == SqlEngineFamily.MYSQL && LETTER.matcher(pattern).find(); - return !foldsCase && isPortable(pattern); - } - - static boolean isPortable(final String pattern) { + /** + * The pattern as Postgres matches it the way XPath matches {@code pattern}, or empty when the + * pattern leaves the common core. + */ + static Optional forPostgres(final String pattern) { final int end = pattern.length() - 1; if (end < 1 || pattern.charAt(0) != '^' || pattern.charAt(end) != '$') { - return false; + return Optional.empty(); } final OntologyPortablePattern parser = new OntologyPortablePattern(pattern.substring(1, end)); - return parser.sequence() && parser.at == parser.body.length(); + final boolean portable = parser.sequence() && parser.at == parser.body.length(); + return portable ? Optional.of("^" + parser.withoutWildcards() + "$") : Optional.empty(); + } + + private String withoutWildcards() { + final StringBuilder written = new StringBuilder(); + for (int index = 0; index < body.length(); index++) { + written.append( + wildcards.get(index) ? ANY_BUT_A_LINE_BREAK : body.substring(index, index + 1)); + } + return written.toString(); } private boolean more() { @@ -80,6 +100,7 @@ private boolean sequence() { private boolean atom() { final char next = body.charAt(at); if (isPlain(next) || next == '.') { + wildcards.set(at, next == '.'); at++; return true; } @@ -95,7 +116,7 @@ private static boolean isPlain(final char character) { return character == ' ' || character <= LAST_ASCII && Character.isLetterOrDigit(character); } - /** A backslash before a punctuation character, which every engine reads as that character. */ + /** A backslash before a punctuation character, which is read as that character. */ private boolean escaped() { final boolean punctuation = at + 1 < body.length() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java index 9ac58320773a..17418f915668 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java @@ -17,11 +17,9 @@ import static org.openmetadata.service.ontology.OntologySettled.refused; import static org.openmetadata.service.ontology.OntologySettled.when; -import java.util.ArrayList; import java.util.List; import org.openmetadata.schema.api.data.OntologyShapeCheckReason; import org.openmetadata.schema.entity.data.OntologyProperty; -import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.OntologyColumnJoin; import org.openmetadata.service.ontology.OntologyCheckGates.Records; import org.openmetadata.service.ontology.OntologyCheckGates.Route; @@ -31,7 +29,6 @@ import org.openmetadata.service.ontology.OntologyCheckProbe.Reach; import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test; import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; @@ -68,12 +65,9 @@ static OntologySettled atLeast(final int count, final Value if (count == 1 && isKeyOfRecord(values)) { return of(new HeldByMapping()); } - if (count == 1 && takesNotNullTest(values)) { - return of(notNull(values)); - } return OntologyCheckGates.reach(values.route()) .then(reach -> reach.joinsHolder() ? OntologyCheckGates.withOuterJoin(reach) : of(reach)) - .map(reach -> generated(values, new FewerValues(reach, values.columns(), count))); + .map(reach -> check(values, new FewerValues(reach, values.columns(), count))); } /** Every record has at most {@code count} values. */ @@ -82,7 +76,7 @@ static OntologySettled atMost(final int count, final Values return of(new HeldByMapping()); } return OntologyCheckGates.reach(values.route()) - .map(reach -> generated(values, new MoreValues(reach, values.columns(), count))); + .map(reach -> check(values, new MoreValues(reach, values.columns(), count))); } /** A record is a row with no null in its key, so a value made of key columns is never absent. */ @@ -91,31 +85,9 @@ private static boolean isKeyOfRecord(final Values values) { && values.records().identity().table().keyPaths().containsAll(values.columns()); } - private static boolean takesNotNullTest(final Values values) { - final Place place = values.place(); - final Column column = - OntologyBindingRules.resolveColumn(place.holder().table(), values.columns().getFirst()); - return values.columns().size() == 1 - && values.records().simple() - && place.onIdentity() - && OntologyBuiltinTest.NOT_NULL.takes(values.columns().getFirst(), column); - } - - private static OntologyPartOutcome notNull(final Values values) { - final MappedTable table = values.place().holder(); - final Test test = - OntologyBuiltinTest.NOT_NULL.on( - table.table(), values.columns().getFirst().getFirst(), List.of()); - return OntologyCheckGates.check(values.place(), values.columns(), test, List.of(table)); - } - - private static OntologyPartOutcome generated( - final Values values, final OntologyCheckProbe probe) { - return OntologyCheckGates.check( - values.place(), - values.columns(), - new Test.Generated(probe), - OntologyCheckGates.read(probe.reach())); + private static OntologyPartOutcome check( + final Values values, final OntologyCheckProbe probe, final MappedTable... others) { + return OntologyCheckGates.check(values.place(), values.columns(), probe, others); } /** @@ -134,7 +106,7 @@ static OntologySettled reaches(final Values values, final T !(target.subclassSharesTable() && probe.target().filter() != null), probe, OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE)) - .map(probe -> generated(values, probe, target.identity())); + .map(probe -> check(values, probe, target.identity())); } private static OntologySettled arrival( @@ -159,12 +131,4 @@ private static OntologySettled antiJoin( .then(OntologyCheckGates::withOuterJoin) .map((final Reach reach) -> new NoRecord(reach, on, target)); } - - private static OntologyPartOutcome generated( - final Values values, final NoRecord probe, final MappedTable target) { - final List read = new ArrayList<>(OntologyCheckGates.read(probe.reach())); - read.add(target); - return OntologyCheckGates.check( - values.place(), values.columns(), new Test.Generated(probe), read); - } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java index 409a1deb48ed..fa9e51824300 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java @@ -13,8 +13,6 @@ package org.openmetadata.service.ontology; -import static org.openmetadata.service.ontology.OntologyBuiltinTest.parameter; - import java.util.List; import java.util.Set; import java.util.UUID; @@ -28,18 +26,20 @@ import org.openmetadata.schema.api.data.OntologyShapePart; import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.ontology.OntologyPartOutcome.Check; import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; import org.openmetadata.service.ontology.OntologyPartOutcome.NotMapped; import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test; import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledConstraint; import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledPart; import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledShape; import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; /** * Writes the answer a caller gets from what the shape check compile settled @@ -49,6 +49,9 @@ * nothing else about it. */ final class OntologyShapeCheckAnswer { + /** The table test that runs a statement written for the check. */ + static final String CUSTOM_SQL = "tableCustomSQLQuery"; + static final String SQL_EXPRESSION = "sqlExpression"; static final String STRATEGY = "strategy"; static final String OPERATOR = "operator"; @@ -140,21 +143,34 @@ private static OntologyCheckedPart entry( return new OntologyCheckedPart().withPart(part).withOutcome(outcome); } + /** + * One test as a request to create a test case takes it. Both statements are finished by the + * engine family of the table. The test runs the count in the form with every colon escaped, + * because the runner reads {@code :name} as a parameter. The list of keys is the form a person + * reads. + */ private OntologyShapeCheck check(final Named named, final TableCheck found) { final Table table = found.place().holder().table(); - final OntologyShapeCheck check = - new OntologyShapeCheck() - .withIdentity(identity(named, found)) - .withTable(table.getEntityReference()) - .withColumns(found.columns()) - .withReadBindings(found.read().stream().map(this::read).toList()); - return switch (found.test()) { - case Test.Builtin builtin -> check - .withTestDefinition(builtin.definition()) - .withEntityLink(builtin.entityLink()) - .withParameterValues(builtin.parameters()); - case Test.Generated generated -> generated(check, table, generated.probe()); - }; + final Statements statements = OntologyShapeCheckSql.write(found.probe()); + final SqlEngineFamily family = found.probe().reach().family(); + return new OntologyShapeCheck() + .withIdentity(identity(named, found)) + .withTable(table.getEntityReference()) + .withColumns(found.columns()) + .withTestDefinition(CUSTOM_SQL) + .withEntityLink(new EntityLink(Entity.TABLE, table.getFullyQualifiedName()).getLinkString()) + .withParameterValues( + List.of( + parameter(SQL_EXPRESSION, family.finish(statements.count()).escapedSql()), + parameter(STRATEGY, COUNT), + parameter(OPERATOR, AT_MOST), + parameter(THRESHOLD, NO_VIOLATION))) + .withInspectionQuery(family.finish(statements.keys()).sql()) + .withReadBindings(found.read().stream().map(this::read).toList()); + } + + private static TestCaseParameterValue parameter(final String name, final String value) { + return new TestCaseParameterValue().withName(name).withValue(value); } /** @@ -179,25 +195,4 @@ private OntologyShapeCheckBinding read(final BindingRow row) { .withAssetId(row.assetId()) .withRevision(facts.revisions().get(row.conceptId())); } - - /** - * Both statements are finished by the engine family of the table. The test runs the count in - * the form with every colon escaped, because the runner reads {@code :name} as a parameter. The - * list of keys is the form a person reads. - */ - private static OntologyShapeCheck generated( - final OntologyShapeCheck check, final Table table, final OntologyCheckProbe probe) { - final Statements statements = OntologyShapeCheckSql.write(probe); - final SqlEngineFamily family = probe.reach().family(); - return check - .withTestDefinition(OntologyBuiltinTest.CUSTOM_SQL) - .withEntityLink(OntologyBuiltinTest.tableLink(table)) - .withParameterValues( - List.of( - parameter(SQL_EXPRESSION, family.finish(statements.count()).escapedSql()), - parameter(STRATEGY, COUNT), - parameter(OPERATOR, AT_MOST), - parameter(THRESHOLD, NO_VIOLATION))) - .withInspectionQuery(family.finish(statements.keys()).sql()); - } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java index 8eb1577a4e30..9700cac3d9e3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java @@ -24,11 +24,12 @@ import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; import org.openmetadata.service.ontology.OntologyCheckProbe.Reach; import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; +import org.openmetadata.service.ontology.OntologyCheckProbe.Unmatched; import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; import org.openmetadata.service.ontology.sql.TypedStatement; /** - * Writes the statements of a generated test from its probe + * Writes the statements of a test from its probe * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). One statement lists the keys of * the records in violation, and the other counts the rows of that list. Both start from the * identity table of the class and keep only its records, so a row that is no record is never @@ -46,10 +47,13 @@ final class OntologyShapeCheckSql { private static final String AND = " AND "; private static final String IS_NOT_NULL = " IS NOT NULL"; + /** The Postgres collation that compares by code point and folds nothing. */ + private static final String CODE_POINT_COLLATION = "C"; + private OntologyShapeCheckSql() {} /** - * The statements of one generated test. + * The statements of one test. * * @param count one row with one number: the records in violation * @param keys one row for each record in violation, with its key @@ -93,6 +97,7 @@ private static TypedStatement keys(final OntologyCheckProbe probe) { case MoreValues more -> moreValues(draft, more); case OutsideList outside -> outsideList(draft, outside); case OutsideRange outside -> outsideRange(draft, outside); + case Unmatched unmatched -> unmatched(draft, unmatched); case NoRecord none -> noRecord(draft, none); } return draft.sql.build(); @@ -178,6 +183,23 @@ private static void outsideRange(final Draft draft, final OutsideRange probe) { where.sql(both ? ")" : ""); } + /** + * A null matches nothing and fails nothing, so it is no violation. The value is matched as text + * under the {@code C} collation: a {@code citext} column would fold case, an enumerated type has + * no match operator, and a nondeterministic collation refuses a regular expression. + */ + private static void unmatched(final Draft draft, final Unmatched probe) { + recordsWithHolder(draft) + .where() + .sql("NOT (CAST(") + .column(draft.holder, probe.column()) + .sql(" AS text) COLLATE ") + .name(CODE_POINT_COLLATION) + .sql(" ~ ") + .value(probe.pattern()) + .sql(")"); + } + /** The keys of the records, ready for a test of one column of the table that holds it. */ private static TypedStatement.Builder valueOfRecords( final Draft draft, final List column) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java index 6a0b01c8c668..0c755e1b1790 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java @@ -13,38 +13,29 @@ package org.openmetadata.service.ontology; -import static org.openmetadata.service.ontology.OntologyBuiltinTest.parameter; import static org.openmetadata.service.ontology.OntologySettled.of; import static org.openmetadata.service.ontology.OntologySettled.refused; import static org.openmetadata.service.ontology.OntologySettled.when; -import java.math.BigDecimal; import java.net.URI; -import java.util.ArrayList; import java.util.EnumSet; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.function.Predicate; import org.openmetadata.schema.api.data.OntologyShapeCheckReason; -import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; import org.openmetadata.schema.type.Column; -import org.openmetadata.schema.type.ColumnConstraint; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.OntologyLiteral; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.type.OntologyShapeValue; -import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.ontology.OntologyCheckGates.Records; import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideList; import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; +import org.openmetadata.service.ontology.OntologyCheckProbe.Unmatched; import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test; import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; -import org.openmetadata.service.ontology.sql.ParsedValue; -import org.openmetadata.service.ontology.sql.SqlEngineFamily; import org.openmetadata.service.ontology.sql.TypedValue; import org.openmetadata.service.ontology.sql.TypedValues; import org.openmetadata.service.ontology.sql.TypedValues.Kind; @@ -57,15 +48,9 @@ * the comparison is the engine's own. */ final class OntologyShapeValueRules { - private static final String MIN_VALUE = "minValue"; - private static final String MAX_VALUE = "maxValue"; - private static final String ALLOWED_VALUES = "allowedValues"; - private static final String MATCH_ENUM = "matchEnum"; - private static final String REGEX = "regex"; private static final String TRUE = "true"; private static final String FALSE = "false"; - private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; private static final String RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; /** The datatypes of a literal that carries a language tag, which no column value has. */ @@ -73,95 +58,41 @@ final class OntologyShapeValueRules { private static final Set ORDERED = EnumSet.of(Kind.WHOLE, Kind.DECIMAL, Kind.DATE, Kind.TIME, Kind.TIMESTAMP); - private static final Set NUMBERS = EnumSet.of(Kind.WHOLE, Kind.DECIMAL); - private static final Set LISTED_BY_A_COLUMN_TEST = EnumSet.of(Kind.TEXT, Kind.WHOLE); - private static final Set NEVER_NULL = - EnumSet.of(ColumnConstraint.NOT_NULL, ColumnConstraint.PRIMARY_KEY); - private static final Set WHOLE_TYPES = - EnumSet.of( - ColumnDataType.TINYINT, - ColumnDataType.BYTEINT, - ColumnDataType.SMALLINT, - ColumnDataType.INT, - ColumnDataType.BIGINT, - ColumnDataType.LARGEINT); - private static final Set FIXED_POINT_TYPES = - EnumSet.of(ColumnDataType.DECIMAL, ColumnDataType.NUMERIC, ColumnDataType.NUMBER); - - /** - * The columns whose every value is a value of a datatype, by datatype IRI. A fixed-point column - * with a scale of zero holds whole numbers only, and a whole-number column holds decimals. - */ - private static final Map> HOLDS_ONLY = - Map.of( - XSD + "string", - ofTypes( - ColumnDataType.VARCHAR, - ColumnDataType.CHAR, - ColumnDataType.STRING, - ColumnDataType.TEXT, - ColumnDataType.MEDIUMTEXT, - ColumnDataType.ENUM), - XSD + "boolean", - ofTypes(ColumnDataType.BOOLEAN), - XSD + "integer", - column -> WHOLE_TYPES.contains(column.getDataType()) || isFixedPoint(column, true), - XSD + "decimal", - column -> WHOLE_TYPES.contains(column.getDataType()) || isFixedPoint(column, false), - XSD + "double", - ofTypes(ColumnDataType.DOUBLE, ColumnDataType.FLOAT), - XSD + "float", - ofTypes(ColumnDataType.FLOAT), - XSD + "date", - ofTypes(ColumnDataType.DATE), - XSD + "time", - ofTypes(ColumnDataType.TIME), - XSD + "dateTime", - ofTypes(ColumnDataType.TIMESTAMP, ColumnDataType.TIMESTAMPZ, ColumnDataType.DATETIME)); + /** The one service type whose engine was run against every construct a pattern may use. */ + private static final String MATCHES_AS_SHACL_DOES = DatabaseServiceType.Postgres.value(); private OntologyShapeValueRules() {} /** The bounds of a range as values of the column. A range has at least one. */ - private record Bounds(Optional min, Optional max) { - boolean fitDoubles() { - return min.map(OntologyShapeValueRules::fitsADouble).orElse(true) - && max.map(OntologyShapeValueRules::fitsADouble).orElse(true); - } - } + private record Bounds(Optional min, Optional max) {} - private static Predicate ofTypes( - final ColumnDataType first, final ColumnDataType... rest) { - final Set types = EnumSet.of(first, rest); - return column -> types.contains(column.getDataType()); - } - - private static boolean isFixedPoint(final Column column, final boolean wholeOnly) { - final boolean noFraction = column.getScale() != null && column.getScale() == 0; - return FIXED_POINT_TYPES.contains(column.getDataType()) && (!wholeOnly || noFraction); - } - - /** Every value of the column is a value of the datatype, so nothing is left to test. */ + /** Every value that the column can store is a value of the datatype, so no test is needed. */ static OntologySettled datatype(final URI datatype, final Place place) { - final Predicate holdsOnly = HOLDS_ONLY.get(datatype.toString()); return OntologyCheckGates.column(place) .then( column -> - holdsOnly == null - ? refused(OntologyShapeCheckReason.DATATYPE_NOT_SUPPORTED) - : when( - holdsOnly.test(column), + OntologyHeldDatatypes.reads(datatype) + ? when( + OntologyHeldDatatypes.holdsOnly( + place.holder().serviceType(), datatype, column), new HeldByMapping(), - OntologyShapeCheckReason.DATATYPE_MISMATCH)); + OntologyShapeCheckReason.DATATYPE_MISMATCH) + : refused(OntologyShapeCheckReason.DATATYPE_NOT_SUPPORTED)); } /** Every value lies between the bounds of the constraint, which are part of the range. */ static OntologySettled range( final OntologyShapeConstraint constraint, final Records records, final Place place) { + final List path = place.binding().getColumnPath(); return OntologyCheckGates.column(place) + .then(column -> bounds(column, constraint)) .then( - column -> - bounds(column, constraint).then(bounds -> ranged(records, place, column, bounds))); + bounds -> + OntologyCheckGates.route(records, place) + .then(OntologyCheckGates::reach) + .map(reach -> new OutsideRange(reach, path, bounds.min(), bounds.max()))) + .map(probe -> check(place, probe)); } private static OntologySettled bounds( @@ -178,45 +109,18 @@ private static OntologySettled> bound( return literal == null ? of(Optional.empty()) : value(column, literal).map(Optional::of); } - private static OntologySettled ranged( - final Records records, final Place place, final Column column, final Bounds bounds) { - final List path = place.binding().getColumnPath(); - final boolean number = TypedValues.kind(column).filter(NUMBERS::contains).isPresent(); - if (number && bounds.fitDoubles() && takes(OntologyBuiltinTest.BETWEEN, records, place)) { - return of(columnTest(OntologyBuiltinTest.BETWEEN, place, between(bounds))); - } - return OntologyCheckGates.route(records, place) - .then(OntologyCheckGates::reach) - .map(reach -> generated(place, new OutsideRange(reach, path, bounds.min(), bounds.max()))); - } - - private static List between(final Bounds bounds) { - final List parameters = new ArrayList<>(); - bounds.min().ifPresent(min -> parameters.add(parameter(MIN_VALUE, min.source()))); - bounds.max().ifPresent(max -> parameters.add(parameter(MAX_VALUE, max.source()))); - return List.copyOf(parameters); - } - - /** The range test reads its bounds as doubles, so a bound must be one exactly. */ - private static boolean fitsADouble(final TypedValue bound) { - final BigDecimal exact = - switch (bound.parsed()) { - case ParsedValue.WholeNumber whole -> new BigDecimal(whole.value()); - case ParsedValue.DecimalNumber decimal -> decimal.value(); - default -> null; - }; - return exact != null - && Double.isFinite(exact.doubleValue()) - && new BigDecimal(exact.doubleValue()).compareTo(exact) == 0; - } - /** Every value is one of the listed literals. */ static OntologySettled in( final List list, final Records records, final Place place) { + final List path = place.binding().getColumnPath(); return OntologyCheckGates.column(place) + .then(column -> listed(column, list)) .then( - column -> - listed(column, list).then(values -> listTest(records, place, column, values))); + values -> + OntologyCheckGates.route(records, place) + .then(OntologyCheckGates::reach) + .map(reach -> new OutsideList(reach, path, values))) + .map(probe -> check(place, probe)); } private static OntologySettled> listed( @@ -228,75 +132,49 @@ private static OntologySettled> listed( list.stream().map(item -> value(column, item.getLiteral())).toList()); } - private static OntologySettled listTest( - final Records records, - final Place place, - final Column column, - final List values) { - final boolean listable = - TypedValues.kind(column).filter(LISTED_BY_A_COLUMN_TEST::contains).isPresent() - && NEVER_NULL.contains(column.getConstraint()) - && !values.isEmpty(); - if (listable && takes(OntologyBuiltinTest.IN_SET, records, place)) { - return of(columnTest(OntologyBuiltinTest.IN_SET, place, inSet(values))); - } - return OntologyCheckGates.route(records, place) - .then(OntologyCheckGates::reach) - .map( - reach -> - generated(place, new OutsideList(reach, place.binding().getColumnPath(), values))); - } - - /** - * The parameters of the set test. With {@code matchEnum} it fails for every row whose value is - * not listed, and without it for no row as long as one listed value occurs. - */ - private static List inSet(final List values) { - final List allowed = - values.stream() - .map( - value -> - value.parsed() instanceof ParsedValue.WholeNumber whole - ? (Object) whole.value() - : value.source()) - .toList(); - return List.of( - parameter(ALLOWED_VALUES, JsonUtils.pojoToJson(allowed)), parameter(MATCH_ENUM, TRUE)); - } - /** - * Every value matches the pattern. Only the regex test can say so, and it reads rows, so the - * table must be simple. + * Every value matches the pattern. An engine gets a statement only where it was run against + * every construct that {@link OntologyPortablePattern} lets through, so the service type is + * asked first and a pattern has one answer on every other one. */ static OntologySettled pattern( final String pattern, final Records records, final Place place) { + if (!MATCHES_AS_SHACL_DOES.equals(records.identity().table().serviceType())) { + return refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + } + final List path = place.binding().getColumnPath(); return OntologyCheckGates.column(place) - .then(column -> matched(pattern, records, place, column)) - .map( - family -> - columnTest( - OntologyBuiltinTest.MATCH_REGEX, place, List.of(parameter(REGEX, pattern)))); + .then(column -> matched(column, pattern)) + .then( + written -> + OntologyCheckGates.route(records, place) + .then(OntologyCheckGates::reach) + .map(reach -> new Unmatched(reach, path, written))) + .map(probe -> check(place, probe)); } - private static OntologySettled matched( - final String pattern, final Records records, final Place place, final Column column) { + /** + * The pattern as a text value that the engine matches the column with. A {@code CHAR} column + * pads its values with spaces, and nothing says whether a pattern is asked of the padding too. + */ + private static OntologySettled matched(final Column column, final String pattern) { final boolean text = TypedValues.kind(column).filter(Kind.TEXT::equals).isPresent(); - final List path = place.binding().getColumnPath(); - if (!text || !OntologyBuiltinTest.MATCH_REGEX.takes(path, column)) { + if (!text || column.getDataType() == ColumnDataType.CHAR) { return refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED); } - if (!place.onIdentity() || !records.simple()) { - return refused(OntologyShapeCheckReason.TABLE_NOT_SIMPLE); + return OntologyPortablePattern.forPostgres(pattern) + .flatMap(written -> text(column, written)) + .map(OntologySettled::of) + .orElseGet(() -> refused(OntologyShapeCheckReason.PATTERN_NOT_PORTABLE)); + } + + /** Empty when the text is longer than a statement takes. */ + private static Optional text(final Column column, final String text) { + try { + return Optional.of(TypedValues.value(column, text)); + } catch (final BadRequestException tooLong) { + return Optional.empty(); } - return SqlEngineFamily.forServiceType(place.holder().serviceType()) - .filter(family -> family != SqlEngineFamily.TSQL) - .map( - family -> - when( - OntologyPortablePattern.reads(pattern, family), - family, - OntologyShapeCheckReason.PATTERN_NOT_PORTABLE)) - .orElseGet(() -> refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED)); } /** One literal of a constraint as a value of the column. */ @@ -325,32 +203,7 @@ private static Object written(final Column column, final String text) { return text; } - /** True when a column test on the place reads exactly the records and the definition takes it. */ - private static boolean takes( - final OntologyBuiltinTest test, final Records records, final Place place) { - final List path = place.binding().getColumnPath(); - return place.onIdentity() - && records.simple() - && test.takes(path, OntologyBindingRules.resolveColumn(place.holder().table(), path)); - } - - private static OntologyPartOutcome columnTest( - final OntologyBuiltinTest test, - final Place place, - final List parameters) { - final List path = place.binding().getColumnPath(); - return OntologyCheckGates.check( - place, - List.of(path), - test.on(place.holder().table(), path.getFirst(), parameters), - List.of(place.holder())); - } - - private static OntologyPartOutcome generated(final Place place, final OntologyCheckProbe probe) { - return OntologyCheckGates.check( - place, - List.of(place.binding().getColumnPath()), - new Test.Generated(probe), - OntologyCheckGates.read(probe.reach())); + private static OntologyPartOutcome check(final Place place, final OntologyCheckProbe probe) { + return OntologyCheckGates.check(place, List.of(place.binding().getColumnPath()), probe); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java index 6260feff983a..36ee5b7fd808 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java @@ -54,8 +54,9 @@ public static final class Builder { * What statement text may hold. It has no quote, backslash, colon, semicolon, minus or slash, * so text can open no string, quoted name, bind parameter or comment and can end no statement. * A string or a quoted name reaches a statement only through {@link #value} and {@link #name}. + * The tilde is the match operator of a regular expression. */ - private static final Pattern WRITTEN_TEXT = Pattern.compile("[A-Za-z0-9_ ,.()*=<>\n]*"); + private static final Pattern WRITTEN_TEXT = Pattern.compile("[A-Za-z0-9_ ,.()*=<>~\n]*"); private final List parts = new ArrayList<>(); @@ -65,7 +66,7 @@ private Builder() {} public Builder sql(final String text) { if (!WRITTEN_TEXT.matcher(text).matches()) { throw new IllegalArgumentException( - "Statement text takes letters, digits, spaces, line breaks and _ , . ( ) * = < >." + "Statement text takes letters, digits, spaces, line breaks and _ , . ( ) * = < > ~." + " Pass a name to name() and a value to value()"); } parts.add(new Part.Sql(text)); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java index 4c3e0b4f0080..5bceedb14360 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java @@ -15,18 +15,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.Optional; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; -import org.openmetadata.service.ontology.sql.SqlEngineFamily; -/** Which regular expressions every engine reads alike, one pattern for each rule. */ +/** + * Which regular expressions are written for Postgres and how, one pattern for each rule. The + * integration tests run the written patterns on the engine. + */ class OntologyPortablePatternTest { @ParameterizedTest @ValueSource( strings = { "^$", "^abc 123$", - "^a.c$", "^a\\.b\\-c\\$\\^\\\\$", "^[a-z]$", "^[A-Z0-9 ]+$", @@ -39,8 +42,23 @@ class OntologyPortablePatternTest { "^(a|b)(c|d)$", "^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}$" }) - void acceptsAPatternInsideTheCommonCore(final String pattern) { - assertEquals(true, OntologyPortablePattern.isPortable(pattern), pattern); + void writesAPatternInsideTheCommonCoreAsItIsGiven(final String pattern) { + assertEquals(Optional.of(pattern), OntologyPortablePattern.forPostgres(pattern)); + } + + @ParameterizedTest + @CsvSource( + delimiterString = " => ", + value = { + "^a.c$ => ^a[^\\n\\r]c$", + "^.$ => ^[^\\n\\r]$", + "^.*$ => ^[^\\n\\r]*$", + "^a\\.b.$ => ^a\\.b[^\\n\\r]$", + "^(a|.)+.{2,3}$ => ^(a|[^\\n\\r])+[^\\n\\r]{2,3}$", + "^[a-z]+.[0-9]$ => ^[a-z]+[^\\n\\r][0-9]$" + }) + void writesAWildcardAsEveryCharacterButALineBreak(final String pattern, final String written) { + assertEquals(Optional.of(written), OntologyPortablePattern.forPostgres(pattern)); } @ParameterizedTest @@ -82,25 +100,13 @@ void acceptsAPatternInsideTheCommonCore(final String pattern) { "^[a-]$", "^[\\d]$", "^[a\\-z]$", + "^[.]$", "^[[:alpha:]]$", "^a_b$", "^café$", "^a\tb$" }) - void refusesAPatternThatEnginesReadDifferently(final String pattern) { - assertEquals(false, OntologyPortablePattern.isPortable(pattern), pattern); - } - - @ParameterizedTest - @ValueSource(strings = {"^[a-z]+$", "^A1$", "^x$"}) - void refusesALetterOnlyForTheMysqlFamily(final String pattern) { - assertEquals(false, OntologyPortablePattern.reads(pattern, SqlEngineFamily.MYSQL), pattern); - assertEquals(true, OntologyPortablePattern.reads(pattern, SqlEngineFamily.POSTGRES), pattern); - } - - @ParameterizedTest - @ValueSource(strings = {"^[0-9]{3}\\-[0-9]{4}$", "^1 2$"}) - void acceptsAPatternWithoutLettersForTheMysqlFamily(final String pattern) { - assertEquals(true, OntologyPortablePattern.reads(pattern, SqlEngineFamily.MYSQL), pattern); + void refusesAPatternOutsideTheCommonCore(final String pattern) { + assertEquals(Optional.empty(), OntologyPortablePattern.forPostgres(pattern), pattern); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java index 9ad0439be3ca..6337dc85fa8d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java @@ -18,6 +18,7 @@ import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; import java.net.URI; @@ -28,16 +29,26 @@ import org.openmetadata.schema.api.data.OntologyCheckedPart; import org.openmetadata.schema.api.data.OntologyCheckedShape; import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.utils.JsonUtils; /** - * The answer as a caller reads it: one kind of entry for each outcome, a test as a request to + * The answer as a caller reads it: one kind of entry for each outcome, every test as a request to * create a test case takes it, and nothing about a constraint that rests on a table the caller * may not view. */ class OntologyShapeCheckAnswerTest { private static final String POSTGRES = "Postgres"; + private static final String CUSTOM_SQL = "tableCustomSQLQuery"; + private static final String CUSTOMERS_LINK = "<#E::table::warehouse.sales.shop.customers>"; + + /** The parameters after the statement, which say that the test passes at 0 violations. */ + private static final String PASSES_AT_NO_VIOLATION = + "[{\"name\":\"strategy\",\"value\":\"COUNT\"}," + + "{\"name\":\"operator\",\"value\":\"<=\"}," + + "{\"name\":\"threshold\",\"value\":\"0\"}]"; /** The reference of a table that no catalog holds, so it names no entity type. */ private static final String CUSTOMERS_TABLE = @@ -82,33 +93,122 @@ private static OntologyShapeCheck check( return parts(model, type, constraint, Set.of()).getFirst().getChecks().getFirst(); } + private static String parameter(final OntologyShapeCheck check, final String name) { + return check.getParameterValues().stream() + .filter(parameter -> parameter.getName().equals(name)) + .map(TestCaseParameterValue::getValue) + .findFirst() + .orElseThrow(); + } + + private static String verdict(final OntologyShapeCheck check) { + return JsonUtils.pojoToJson(check.getParameterValues().subList(1, 4)); + } + @Test - void aColumnTestIsWrittenAsARequestToCreateATestCaseTakesIt() { + void minCountOneIsTheCustomQueryTestWhereTheRowsOfTheTableAreItsRecordsToo() { final OntologyShapeCheckModel model = customers().primaryKey("customers", "id").notNull("customers", "email"); + final OntologyShapeCheck check = + check(model, "Customer", model.on("customerEmail").withMinCount(1)); + assertEquals(CUSTOM_SQL, check.getTestDefinition()); + assertEquals(CUSTOMERS_LINK, check.getEntityLink()); assertEquals( - "[{\"part\":\"in\",\"outcome\":\"check\",\"checks\":[{" - + "\"identity\":\"5f601e0183676bea515c7d2a3fc65c264a4e6358b42df7a0382c8e9b80572854\"," - + "\"table\":" - + CUSTOMERS_TABLE - + ",\"columns\":[[\"email\"]]," - + "\"testDefinition\":\"columnValuesToBeInSet\"," - + "\"entityLink\":\"<#E::table::warehouse.sales.shop.customers::columns::email>\"," - + "\"parameterValues\":[{\"name\":\"allowedValues\",\"value\":\"[\\\"a\\\",\\\"b\\\"]\"}," - + "{\"name\":\"matchEnum\",\"value\":\"true\"}]," - + "\"readBindings\":[" - + CUSTOMER_BINDING - + "]}]}]", - JsonUtils.pojoToJson( - parts( - model, - "Customer", - model.on("customerEmail").withIn(literals("a", "b")), - Set.of()))); + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 + ) c""", + parameter(check, "sqlExpression")); + assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); + assertEquals(4, check.getParameterValues().size()); + } + + @Test + void inIsTheCustomQueryTestWhereTheColumnIsNeverNullAndTheRowsAreTheRecordsToo() { + final OntologyShapeCheckModel model = + customers().primaryKey("customers", "id").notNull("customers", "email"); + final OntologyShapeCheck check = + check(model, "Customer", model.on("customerEmail").withIn(literals("a", "b"))); + assertEquals(CUSTOM_SQL, check.getTestDefinition()); + assertEquals(CUSTOMERS_LINK, check.getEntityLink()); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email NOT IN ('a', 'b') + ) c""", + parameter(check, "sqlExpression")); + assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); + assertEquals(4, check.getParameterValues().size()); + } + + @Test + void rangeIsTheCustomQueryTestWhereTheRowsOfTheTableAreItsRecordsToo() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel(COLUMN_RELATION, POSTGRES).primaryKey("orders", "id"); + final OntologyShapeCheck check = + check( + model, + "Order", + model.on("orderTotal").withMinInclusive(limit("0")).withMaxInclusive(limit("1000.5"))); + assertEquals(CUSTOM_SQL, check.getTestDefinition()); + assertEquals("<#E::table::warehouse.sales.shop.orders>", check.getEntityLink()); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND (t0.total < 0 OR t0.total > 1000.5) + ) c""", + parameter(check, "sqlExpression")); + assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); + assertEquals(4, check.getParameterValues().size()); + } + + @Test + void patternIsTheCustomQueryTestWithItsColonsEscapedInTheCountOnly() { + final OntologyShapeCheckModel model = customers(); + final OntologyShapeCheck check = + check(model, "Customer", model.on("customerEmail").withPattern("^[a-z]+\\:.$")); + assertEquals(CUSTOM_SQL, check.getTestDefinition()); + assertEquals(CUSTOMERS_LINK, check.getEntityLink()); + assertEquals(List.of(List.of("email")), check.getColumns()); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+\\\\\\:[^\\\\n\\\\r]$') + ) c""", + parameter(check, "sqlExpression")); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+\\\\:[^\\\\n\\\\r]$')""", + check.getInspectionQuery()); + assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); + assertEquals("[" + CUSTOMER_BINDING + "]", JsonUtils.pojoToJson(check.getReadBindings())); } @Test - void aGeneratedTestRunsItsCountWithColonsEscapedAndListsItsKeysAsAPersonReadsThem() { + void aTestRunsItsCountWithColonsEscapedAndListsItsKeysAsAPersonReadsThem() { final OntologyShapeCheckModel model = customers(); assertEquals( "[{\"part\":\"in\",\"outcome\":\"check\",\"checks\":[{" @@ -143,12 +243,13 @@ void anAnswerWithoutATestSaysWhichKindItIsAndAReasonOnlyWhenItIsNotEnforceable() final OntologyShapeCheckModel model = customers(); assertEquals( "[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}," - + "{\"part\":\"pattern\",\"outcome\":\"notEnforceable\",\"reason\":\"tableNotSimple\"}]", + + "{\"part\":\"pattern\",\"outcome\":\"notEnforceable\"," + + "\"reason\":\"patternNotPortable\"}]", JsonUtils.pojoToJson( parts( model, "Customer", - model.on("customerEmail").withMinCount(0).withPattern("^[0-9]+$"), + model.on("customerEmail").withMinCount(0).withPattern("^\\d+$"), Set.of()))); assertEquals( "[{\"part\":\"maxCount\",\"outcome\":\"notMapped\"}]", @@ -265,21 +366,23 @@ void aHiddenTableThatAJoinReachesHidesEveryPartOfTheRelation() { void aHiddenAnswerDoesNotTellHowManyAnswersTheTablesGave() { final OntologyShapeCheckModel model = new OntologyShapeCheckModel( - REPEATED_CONTRIBUTION, - POSTGRES, - List.of( - OntologyMappingShapes.identity( - "Customer", - "customers", - List.of("id"), - null, - OntologyMappingShapes.bound("customerName", "name")), - OntologyMappingShapes.contributing( - "Customer", - "customer_addresses", - List.of("customer_id"), - OntologyMappingShapes.bound("customerName", "city")))) - .primaryKey("customers", "id"); + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + OntologyMappingShapes.identity( + "Customer", + "customers", + List.of("id"), + null, + OntologyMappingShapes.bound("customerName", "name")), + OntologyMappingShapes.contributing( + "Customer", + "customer_addresses", + List.of("customer_id"), + OntologyMappingShapes.bound("customerName", "city")))); + model.mapping().table("customer_addresses").getColumns().stream() + .filter(column -> column.getName().equals("city")) + .forEach(column -> column.setDataType(ColumnDataType.CHAR)); final OntologyShapeConstraint pattern = model.on("customerName").withPattern("^[0-9]+$"); assertEquals(2, parts(model, "Customer", pattern, Set.of()).size()); assertEquals( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java index ae45021373f8..835fb3aa061e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java @@ -40,8 +40,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.openmetadata.schema.api.data.OntologyShapeCheckReason; -import org.openmetadata.schema.tests.TestCaseParameterValue; import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.OntologyJoinStatus; @@ -55,6 +56,7 @@ import org.openmetadata.service.ontology.OntologyCheckProbe.NoRecord; import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideList; import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; +import org.openmetadata.service.ontology.OntologyCheckProbe.Unmatched; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; @@ -64,9 +66,9 @@ import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; import org.openmetadata.service.ontology.OntologyPartOutcome.NotMapped; import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test.Builtin; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test.Generated; import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedValue; /** * Every row of the rule that compiles a shape constraint into data quality checks @@ -76,8 +78,6 @@ class OntologyShapeCheckCompilerTest { private static final String POSTGRES = "Postgres"; private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; - private static final String EMAIL_LINK = - "<#E::table::warehouse.sales.shop.customers::columns::email>"; private static OntologyShapeCheckModel customers() { return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, POSTGRES); @@ -110,8 +110,8 @@ private static OntologyShapeCheckModel nameInTwoTables() { bound("customerName", "city")))); } - private static TestCaseParameterValue parameter(final String name, final String value) { - return new TestCaseParameterValue().withName(name).withValue(value); + private static OntologyShapeCheckModel customersOn(final String serviceType) { + return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, serviceType); } private static NotEnforceable refused(final OntologyShapeCheckReason reason) { @@ -120,7 +120,7 @@ private static NotEnforceable refused(final OntologyShapeCheckReason reason) { private static T probe( final Class kind, final TableCheck check) { - return assertInstanceOf(kind, assertInstanceOf(Generated.class, check.test()).probe()); + return assertInstanceOf(kind, check.probe()); } private static Column column( @@ -135,6 +135,10 @@ private static List tables(final List rows) { return rows.stream().map(BindingRow::assetFqnHash).toList(); } + private static List sources(final List values) { + return values.stream().map(TypedValue::source).toList(); + } + @Test void minCountZeroIsHeldByAnyMapping() { final OntologyShapeCheckModel simple = simpleCustomers(); @@ -162,10 +166,13 @@ void minCountOneOnASubjectKeyColumnIsHeld() { } @Test - void minCountOneOnOneColumnOfASimpleTableIsTheNotNullTest() { - final OntologyShapeCheckModel model = simpleCustomers(); + void minCountOneOnOneColumnCountsRecordsWithNoValueWhereTheRowsAreTheRecordsToo() { + final OntologyShapeCheckModel model = simpleCustomers().notNull("customers", "email"); final TableCheck check = model.check("Customer", model.on("customerEmail").withMinCount(1)); - assertEquals(new Builtin("columnValuesToBeNotNull", EMAIL_LINK, List.of()), check.test()); + final FewerValues probe = probe(FewerValues.class, check); + assertEquals(1, probe.count()); + assertEquals(List.of(List.of("email")), probe.columns()); + assertNull(probe.reach().holder()); assertEquals("customers", check.place().holder().table().getName()); assertEquals(List.of(List.of("email")), check.columns()); assertEquals(List.of("customers"), tables(check.read())); @@ -273,6 +280,16 @@ void maxCountWithoutSuchAKeyCountsDistinctValues() { .count()); } + @Test + void maxCountIsNotHeldByAPrimaryKeyThatReachesOutsideTheSubjectKey() { + final OntologyShapeCheckModel model = customers().primaryKey("customers", "id", "name"); + final TableCheck check = model.check("Customer", model.on("customerEmail").withMaxCount(1)); + final MoreValues probe = probe(MoreValues.class, check); + assertEquals(1, probe.count()); + assertEquals(List.of(List.of("email")), probe.columns()); + assertEquals("customers", check.place().holder().table().getName()); + } + @Test void maxCountZeroIsGeneratedEvenOnASimpleTable() { final OntologyShapeCheckModel model = simpleCustomers(); @@ -283,33 +300,27 @@ void maxCountZeroIsGeneratedEvenOnASimpleTable() { } @Test - void inOnATextColumnThatIsNeverNullOnASimpleTableIsTheSetTest() { - final OntologyShapeCheckModel model = simpleCustomers().notNull("customers", "email"); - final OntologyShapeConstraint constraint = - model.on("customerEmail").withIn(literals("ada@example.org", "it's \"x\"")); - assertEquals( - new Builtin( - "columnValuesToBeInSet", - EMAIL_LINK, - List.of( - parameter("allowedValues", "[\"ada@example.org\",\"it's \\\"x\\\"\"]"), - parameter("matchEnum", "true"))), - model.check("Customer", constraint).test()); - } + void inOnAColumnThatIsNeverNullIsGeneratedWhereTheRowsAreTheRecordsToo() { + final OntologyShapeCheckModel text = simpleCustomers().notNull("customers", "email"); + final TableCheck check = + text.check( + "Customer", text.on("customerEmail").withIn(literals("ada@example.org", "it's \"x\""))); + final OutsideList listed = probe(OutsideList.class, check); + assertEquals(List.of("email"), listed.column()); + assertEquals(List.of("ada@example.org", "it's \"x\""), sources(listed.allowed())); + assertEquals(List.of("customers"), tables(check.read())); - @Test - void inOnAWholeNumberKeyColumnOfASimpleTableListsNumbers() { - final OntologyShapeCheckModel model = + final OntologyShapeCheckModel key = customersWith( identity("Customer", "customers", List.of("id"), null, bound("customerName", "id"))) .primaryKey("customers", "id") .notNull("customers", "id"); - assertEquals( - new Builtin( - "columnValuesToBeInSet", - "<#E::table::warehouse.sales.shop.customers::columns::id>", - List.of(parameter("allowedValues", "[1,2]"), parameter("matchEnum", "true"))), - model.check("Customer", model.on("customerName").withIn(literals("1", "2"))).test()); + final OutsideList numbers = + probe( + OutsideList.class, + key.check("Customer", key.on("customerName").withIn(literals("1", "2")))); + assertEquals(List.of("id"), numbers.column()); + assertEquals(List.of("1", "2"), sources(numbers.allowed())); } @Test @@ -320,7 +331,7 @@ void inOnAColumnThatMayHoldNullIsGenerated() { OutsideList.class, model.check("Customer", model.on("customerEmail").withIn(literals("a", "b")))); assertEquals(List.of("email"), probe.column()); - assertEquals(List.of("a", "b"), probe.allowed().stream().map(value -> value.source()).toList()); + assertEquals(List.of("a", "b"), sources(probe.allowed())); } @Test @@ -350,41 +361,31 @@ void inOnADecimalColumnIsGeneratedEvenOnASimpleTable() { probe( OutsideList.class, model.check("Order", model.on("orderTotal").withIn(literals("9.99", "20")))); - assertEquals( - List.of("9.99", "20"), probe.allowed().stream().map(value -> value.source()).toList()); + assertEquals(List.of("9.99", "20"), sources(probe.allowed())); } @Test - void rangeOnANumericColumnOfASimpleTableIsTheBetweenTest() { + void rangeOnANumericColumnIsGeneratedWhereTheRowsAreTheRecordsToo() { final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); - final String link = "<#E::table::warehouse.sales.shop.orders::columns::total>"; - assertEquals( - new Builtin( - "columnValuesToBeBetween", - link, - List.of(parameter("minValue", "0"), parameter("maxValue", "1000.5"))), - model - .check( + final OutsideRange both = + probe( + OutsideRange.class, + model.check( "Order", model .on("orderTotal") .withMinInclusive(limit("0")) - .withMaxInclusive(limit("1000.5"))) - .test()); - assertEquals( - new Builtin("columnValuesToBeBetween", link, List.of(parameter("maxValue", "250"))), - model.check("Order", model.on("orderTotal").withMaxInclusive(limit("250"))).test()); - } + .withMaxInclusive(limit("1000.5")))); + assertEquals(List.of("total"), both.column()); + assertEquals("0", both.min().orElseThrow().source()); + assertEquals("1000.5", both.max().orElseThrow().source()); - @Test - void rangeWithABoundThatNoDoubleHoldsIsGenerated() { - final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); - final OutsideRange probe = + final OutsideRange upper = probe( OutsideRange.class, - model.check("Order", model.on("orderTotal").withMaxInclusive(limit("0.1")))); - assertEquals(Optional.empty(), probe.min()); - assertEquals("0.1", probe.max().orElseThrow().source()); + model.check("Order", model.on("orderTotal").withMaxInclusive(limit("250")))); + assertEquals(Optional.empty(), upper.min()); + assertEquals("250", upper.max().orElseThrow().source()); } @Test @@ -410,36 +411,92 @@ void rangeOnATextColumnIsNotEnforceable() { } @Test - void patternOnATextColumnOfASimpleTableIsTheRegexTest() { - final OntologyShapeCheckModel model = simpleCustomers(); + void patternOnATextColumnCountsRecordsWithAValueThatDoesNotMatch() { + final OntologyShapeCheckModel model = customers(); final String pattern = "^[a-z]+\\@example\\.org$"; - assertEquals( - new Builtin("columnValuesToMatchRegex", EMAIL_LINK, List.of(parameter("regex", pattern))), - model.check("Customer", model.on("customerEmail").withPattern(pattern)).test()); + final TableCheck check = + model.check("Customer", model.on("customerEmail").withPattern(pattern)); + final Unmatched probe = probe(Unmatched.class, check); + assertEquals(SqlEngineFamily.POSTGRES, probe.reach().family()); + assertEquals(List.of("email"), probe.column()); + assertEquals(pattern, probe.pattern().source()); + assertNull(probe.reach().holder()); + assertEquals("customers", check.place().holder().table().getName()); + assertEquals(List.of(List.of("email")), check.columns()); + assertEquals(List.of("customers"), tables(check.read())); } @Test - void patternOffASimpleTableIsNotEnforceable() { - final OntologyShapeCheckModel undeclared = customers(); - assertEquals( - refused(OntologyShapeCheckReason.TABLE_NOT_SIMPLE), - undeclared.answer("Customer", undeclared.on("customerEmail").withPattern("^a$"))); - final OntologyShapeCheckModel contributing = shape(COMPOSITE_KEY); - assertEquals( - refused(OntologyShapeCheckReason.TABLE_NOT_SIMPLE), - contributing.answer("Account", contributing.on("accountTier").withPattern("^a$"))); + void patternOnAContributingTableJoinsItToTheRecords() { + final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); + final TableCheck check = model.check("Account", model.on("accountTier").withPattern("^a$")); + final Unmatched probe = probe(Unmatched.class, check); + assertEquals(List.of("tier"), probe.column()); + assertEquals("crm_customer_profile", probe.reach().holder().table().table().getName()); + assertEquals(List.of("crm_customers", "crm_customer_profile"), tables(check.read())); + } + + @Test + void patternWritesItsWildcardAsEveryCharacterButALineBreak() { + final OntologyShapeCheckModel model = customers(); + final Unmatched probe = + probe( + Unmatched.class, + model.check("Customer", model.on("customerEmail").withPattern("^1.2\\.3$"))); + assertEquals("^1[^\\n\\r]2\\.3$", probe.pattern().source()); } @ParameterizedTest - @CsvSource({"Mssql", "Oracle"}) - void patternOnAnEngineWithNoCommonRegexIsNotEnforceable(final String serviceType) { + @EnumSource(value = SqlEngineFamily.class, names = "POSTGRES", mode = EnumSource.Mode.EXCLUDE) + void patternOnAnyOtherEngineFamilyIsNotEnforceable(final SqlEngineFamily family) { final OntologyShapeCheckModel model = - new OntologyShapeCheckModel(UNFILTERED_IDENTITY, serviceType).primaryKey("customers", "id"); + customersOn(OntologyStatementGoldens.SERVICE_TYPES.get(family)); assertEquals( refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), model.answer("Customer", model.on("customerEmail").withPattern("^a$"))); } + @ParameterizedTest + @ValueSource( + strings = { + "Timescale", + "Presto", + "Athena", + "MariaDB", + "SingleStore", + "Doris", + "StarRocks", + "UnityCatalog", + "Hive", + "Impala", + "Iomete", + "AzureSQL", + "Synapse", + "MicrosoftFabric", + "Oracle" + }) + void patternOnAnyOtherServiceTypeIsNotEnforceable(final String serviceType) { + final OntologyShapeCheckModel model = customersOn(serviceType).primaryKey("customers", "id"); + assertEquals( + refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + model.answer("Customer", model.on("customerEmail").withPattern("^a$"))); + } + + @Test + void patternOnMysqlIsNotEnforceableWhateverThePatternAndTheColumn() { + final OntologyShapeCheckModel model = customersOn("Mysql").primaryKey("customers", "id"); + final NotEnforceable unsupported = refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + assertEquals( + unsupported, model.answer("Customer", model.on("customerEmail").withPattern("^[0-9]+$"))); + assertEquals( + unsupported, model.answer("Customer", model.on("customerEmail").withPattern("^1.2$"))); + assertEquals( + unsupported, model.answer("Customer", model.on("customerEmail").withPattern("\\d+"))); + column(model, "customers", "email").withDataType(ColumnDataType.INT); + assertEquals( + unsupported, model.answer("Customer", model.on("customerEmail").withPattern("^[0-9]+$"))); + } + @Test void patternOutsideTheCommonCoreIsNotEnforceable() { final OntologyShapeCheckModel model = simpleCustomers(); @@ -449,16 +506,21 @@ void patternOutsideTheCommonCoreIsNotEnforceable() { } @Test - void patternWithALetterIsNotPortableToTheMysqlFamily() { - final OntologyShapeCheckModel model = - new OntologyShapeCheckModel(UNFILTERED_IDENTITY, "Mysql").primaryKey("customers", "id"); + void patternThatIsTooLongOnceWrittenIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); assertEquals( - refused(OntologyShapeCheckReason.PATTERN_NOT_PORTABLE), - model.answer("Customer", model.on("customerEmail").withPattern("^[a-z]+$"))); + 702, + probe( + Unmatched.class, + model.check( + "Customer", model.on("customerEmail").withPattern("^" + ".".repeat(100) + "$"))) + .pattern() + .source() + .length()); assertEquals( - new Builtin( - "columnValuesToMatchRegex", EMAIL_LINK, List.of(parameter("regex", "^[0-9]{3}$"))), - model.check("Customer", model.on("customerEmail").withPattern("^[0-9]{3}$")).test()); + refused(OntologyShapeCheckReason.PATTERN_NOT_PORTABLE), + model.answer( + "Customer", model.on("customerEmail").withPattern("^" + ".".repeat(147) + "$"))); } @Test @@ -469,6 +531,29 @@ void patternOnAColumnThatIsNotTextIsNotEnforceable() { model.answer("Order", model.on("orderTotal").withPattern("^[0-9]+$"))); } + @Test + void patternOnAColumnThatPadsItsValuesIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + column(model, "customers", "email").withDataType(ColumnDataType.CHAR); + assertEquals( + refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED), + model.answer("Customer", model.on("customerEmail").withPattern("^[a-z]+$"))); + } + + @ParameterizedTest + @CsvSource({"VARCHAR", "TEXT", "STRING", "MEDIUMTEXT", "ENUM"}) + void patternIsMatchedOnEveryOtherTextType(final ColumnDataType type) { + final OntologyShapeCheckModel model = customers(); + column(model, "customers", "email").withDataType(type); + assertEquals( + "^[a-z]+$", + probe( + Unmatched.class, + model.check("Customer", model.on("customerEmail").withPattern("^[a-z]+$"))) + .pattern() + .source()); + } + @Test void classCountsValuesThatAreNoRecordOfTheNamedClass() { final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); @@ -609,25 +694,48 @@ void valuePartsOnARelationAreNotEnforceable() { @ParameterizedTest @CsvSource({ - "VARCHAR,,string", - "ENUM,,string", - "BOOLEAN,,boolean", - "INT,,integer", - "BIGINT,,decimal", - "DECIMAL,0,integer", - "NUMERIC,2,decimal", - "NUMBER,,decimal", - "DOUBLE,,double", - "FLOAT,,double", - "FLOAT,,float", - "DATE,,date", - "TIME,,time", - "TIMESTAMP,,dateTime", - "DATETIME,,dateTime" + "Postgres,BOOLEAN,,boolean", + "Redshift,BOOLEAN,,boolean", + "Trino,BOOLEAN,,boolean", + "Clickhouse,BOOLEAN,,boolean", + "BigQuery,BOOLEAN,,boolean", + "Snowflake,BOOLEAN,,boolean", + "Databricks,BOOLEAN,,boolean", + "Postgres,TINYINT,,integer", + "Postgres,SMALLINT,,integer", + "Postgres,INT,,integer", + "Mysql,INT,,integer", + "Mssql,BIGINT,,integer", + "Databricks,BIGINT,,integer", + "Snowflake,BYTEINT,,integer", + "StarRocks,LARGEINT,,integer", + "Mysql,DECIMAL,0,integer", + "Snowflake,NUMERIC,0,integer", + "Databricks,DECIMAL,0,integer", + "Postgres,BIGINT,,decimal", + "Databricks,INT,,decimal", + "Mysql,DECIMAL,2,decimal", + "Mssql,NUMERIC,,decimal", + "BigQuery,NUMERIC,2,decimal", + "Postgres,FLOAT,,double", + "Mysql,FLOAT,,double", + "Mssql,FLOAT,,double", + "Databricks,FLOAT,,double", + "BigQuery,DATE,,date", + "Mssql,DATE,,date", + "BigQuery,TIME,,time", + "Mssql,TIME,,time", + "BigQuery,TIMESTAMP,,dateTime", + "BigQuery,DATETIME,,dateTime", + "Mssql,DATETIME,,dateTime", + "Synapse,DATETIME,,dateTime" }) - void datatypeIsHeldWhenEveryValueOfTheColumnTypeIsOfTheDatatype( - final ColumnDataType type, final Integer scale, final String datatype) { - final OntologyShapeCheckModel model = customers(); + void datatypeIsHeldWhereTheEngineStoresNothingElseInTheColumnType( + final String serviceType, + final ColumnDataType type, + final Integer scale, + final String datatype) { + final OntologyShapeCheckModel model = customersOn(serviceType); column(model, "customers", "email").withDataType(type).withScale(scale); assertEquals( new HeldByMapping(), @@ -635,19 +743,171 @@ void datatypeIsHeldWhenEveryValueOfTheColumnTypeIsOfTheDatatype( "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype)))); } + /** A 64-bit column is named FLOAT on some engines, so no column holds only 32-bit numbers. */ + @ParameterizedTest + @CsvSource({"Postgres,FLOAT", "Mysql,FLOAT", "Mssql,FLOAT", "Snowflake,FLOAT", "Postgres,DOUBLE"}) + void floatIsHeldOnNoColumn(final String serviceType, final ColumnDataType type) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, "float")); + } + + /** DOUBLE also names a decimal floating-point type. */ + @ParameterizedTest + @ValueSource(strings = {"Postgres", "Mysql", "Snowflake", "BigQuery", "Mssql"}) + void doubleIsNotHeldOnADoubleColumn(final String serviceType) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + datatype(serviceType, ColumnDataType.DOUBLE, "double")); + } + + /** The MySQL family stores a time of 25:00:00 and a negative one. */ + @ParameterizedTest + @ValueSource(strings = {"Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"}) + void timeIsNotHeldOnTheMysqlFamily(final String serviceType) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + datatype(serviceType, ColumnDataType.TIME, "time")); + } + + /** Postgres stores NaN in a fixed-point column. */ @ParameterizedTest @CsvSource({ - "VARCHAR,,integer", - "INT,,string", - "DECIMAL,2,integer", - "DECIMAL,,integer", - "DOUBLE,,float", - "BIT,,boolean", - "TIMESTAMP,,date" + "Postgres,DECIMAL,2,decimal", + "Postgres,NUMERIC,2,decimal", + "Postgres,NUMERIC,,decimal", + "Postgres,DECIMAL,0,integer", + "Postgres,NUMERIC,0,integer", + "Timescale,NUMERIC,0,integer", + "Timescale,DECIMAL,2,decimal" + }) + void fixedPointIsNotHeldOnThePostgresFamily( + final String serviceType, + final ColumnDataType type, + final Integer scale, + final String datatype) { + final OntologyShapeCheckModel model = customersOn(serviceType); + column(model, "customers", "email").withDataType(type).withScale(scale); + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype)))); + } + + /** Postgres stores infinity in a date and a timestamp, and its time can carry an offset. */ + @ParameterizedTest + @CsvSource({ + "Postgres,DATE,date", + "Postgres,TIMESTAMP,dateTime", + "Postgres,TIMESTAMPZ,dateTime", + "Postgres,DATETIME,dateTime", + "Postgres,TIME,time", + "Timescale,DATE,date", + "Timescale,TIMESTAMP,dateTime" + }) + void datesAndTimesAreNotHeldOnThePostgresFamily( + final String serviceType, final ColumnDataType type, final String datatype) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, datatype)); + } + + /** The MySQL family stores the zero date. */ + @ParameterizedTest + @CsvSource({ + "Mysql,DATE,date", + "Mysql,DATETIME,dateTime", + "Mysql,TIMESTAMP,dateTime", + "MariaDB,DATE,date", + "MariaDB,DATETIME,dateTime", + "MariaDB,TIMESTAMP,dateTime" + }) + void datesAreNotHeldOnTheMysqlFamily( + final String serviceType, final ColumnDataType type, final String datatype) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, datatype)); + } + + /** A boolean of the MySQL family is a number from -128 to 127, and T-SQL has no boolean. */ + @ParameterizedTest + @ValueSource(strings = {"Mysql", "MariaDB", "SingleStore", "Mssql", "AzureSQL"}) + void booleanIsNotHeldWhereTheEngineHasNoBooleanType(final String serviceType) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + datatype(serviceType, ColumnDataType.BOOLEAN, "boolean")); + } + + /** Every text type stores control characters, which are no characters of xsd:string. */ + @ParameterizedTest + @CsvSource({ + "Postgres,VARCHAR", + "Postgres,CHAR", + "Postgres,TEXT", + "Postgres,ENUM", + "Mysql,MEDIUMTEXT", + "Snowflake,STRING", + "Mssql,VARCHAR" + }) + void stringIsHeldOnNoColumn(final String serviceType, final ColumnDataType type) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, "string")); + } + + /** + * The lines the table leaves out for a reason of their own: a decimal that the catalog names + * INT, a row version that it names TIMESTAMP or NUMBER, and the engines whose dates and times + * were not read. + */ + @ParameterizedTest + @CsvSource({ + "Databricks,INT,integer", + "Hive,INT,integer", + "Mssql,TIMESTAMP,dateTime", + "Mssql,NUMBER,decimal", + "Postgres,NUMBER,decimal", + "Snowflake,NUMBER,integer", + "Snowflake,DATE,date", + "Trino,TIMESTAMP,dateTime", + "Databricks,DATE,date", + "Redshift,TIME,time", + "Clickhouse,DATETIME,dateTime", + "Mssql,TIMESTAMPZ,dateTime" + }) + void datatypeIsNotHeldWhereTheCatalogTypeNamesSomethingElseOrWasNotRead( + final String serviceType, final ColumnDataType type, final String datatype) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, datatype)); + } + + @ParameterizedTest + @CsvSource({ + "Oracle,INT,integer", + "Oracle,DATE,date", + "Db2,DOUBLE,double", + "Db2,BOOLEAN,boolean", + "Teradata,FLOAT,double" + }) + void datatypeIsHeldOnNoServiceTypeWithoutAnEngineFamily( + final String serviceType, final ColumnDataType type, final String datatype) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, datatype)); + } + + @ParameterizedTest + @CsvSource({ + "Postgres,VARCHAR,,integer", + "Postgres,INT,,boolean", + "Mysql,DECIMAL,2,integer", + "Mysql,DECIMAL,,integer", + "Postgres,BIT,,boolean", + "BigQuery,TIMESTAMP,,date", + "BigQuery,DATE,,dateTime", + "Mssql,FLOAT,,decimal" }) void datatypeThatTheColumnTypeCanBreakIsNotEnforceable( - final ColumnDataType type, final Integer scale, final String datatype) { - final OntologyShapeCheckModel model = customers(); + final String serviceType, + final ColumnDataType type, + final Integer scale, + final String datatype) { + final OntologyShapeCheckModel model = customersOn(serviceType); column(model, "customers", "email").withDataType(type).withScale(scale); assertEquals( refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), @@ -655,6 +915,15 @@ void datatypeThatTheColumnTypeCanBreakIsNotEnforceable( "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype)))); } + /** The answer for a datatype on a column of the type, with no scale, on a service type. */ + private static OntologyPartOutcome datatype( + final String serviceType, final ColumnDataType type, final String datatype) { + final OntologyShapeCheckModel model = customersOn(serviceType); + column(model, "customers", "email").withDataType(type); + return model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype))); + } + @Test void datatypeOutsideTheSupportedOnesIsNotEnforceable() { final OntologyShapeCheckModel model = customers(); @@ -691,7 +960,8 @@ void countsOverSeveralTablesAreNotEnforceable() { @Test void tablesThatDoNotAgreeGetOneAnswerEach() { - final OntologyShapeCheckModel model = nameInTwoTables().primaryKey("customers", "id"); + final OntologyShapeCheckModel model = nameInTwoTables(); + column(model, "customer_addresses", "city").withDataType(ColumnDataType.CHAR); final List answers = model.answers("Customer", model.on("customerName").withPattern("^[0-9]+$")); assertEquals(2, answers.size()); @@ -699,7 +969,7 @@ void tablesThatDoNotAgreeGetOneAnswerEach() { assertEquals( List.of("customers"), check.checks().stream().map(one -> one.place().holder().table().getName()).toList()); - assertEquals(refused(OntologyShapeCheckReason.TABLE_NOT_SIMPLE), answers.getLast()); + assertEquals(refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED), answers.getLast()); } @Test @@ -789,17 +1059,24 @@ void tableInAnotherDatabaseIsNotEnforceable() { } @Test - void generatedCheckNeedsAnEngineThatStatementsAreWrittenForAndAColumnTestDoesNot() { - final OntologyShapeCheckModel undeclared = - new OntologyShapeCheckModel(UNFILTERED_IDENTITY, "Oracle"); + void everyCheckNeedsAnEngineThatStatementsAreWrittenFor() { + final NotEnforceable unsupported = refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + final OntologyShapeCheckModel undeclared = customersOn("Oracle"); assertEquals( - refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), - undeclared.answer("Customer", undeclared.on("customerEmail").withMinCount(1))); + unsupported, undeclared.answer("Customer", undeclared.on("customerEmail").withMinCount(1))); final OntologyShapeCheckModel simple = - new OntologyShapeCheckModel(UNFILTERED_IDENTITY, "Oracle").primaryKey("customers", "id"); + customersOn("Oracle").primaryKey("customers", "id").notNull("customers", "email"); + assertEquals( + List.of(unsupported, unsupported, unsupported), + simple.answers( + "Customer", + simple.on("customerEmail").withMinCount(1).withIn(literals("a")).withPattern("^a$"))); + final OntologyShapeCheckModel orders = + new OntologyShapeCheckModel(COLUMN_RELATION, "Oracle").primaryKey("orders", "id"); + assertEquals( + unsupported, orders.answer("Order", orders.on("orderTotal").withMaxInclusive(limit("5")))); assertEquals( - new Builtin("columnValuesToBeNotNull", EMAIL_LINK, List.of()), - simple.check("Customer", simple.on("customerEmail").withMinCount(1)).test()); + new HeldByMapping(), simple.answer("Customer", simple.on("customerEmail").withMaxCount(1))); } @Test @@ -811,18 +1088,10 @@ void clickHouseGetsNoStatementThatKeepsUnmatchedRows() { contributing.answers("Account", contributing.on("accountTier").withMinCount(1))); assertInstanceOf( MoreValues.class, - ((Generated) - contributing - .check("Account", contributing.on("accountTier").withMaxCount(1)) - .test()) - .probe()); + contributing.check("Account", contributing.on("accountTier").withMaxCount(1)).probe()); assertInstanceOf( FewerValues.class, - ((Generated) - contributing - .check("Account", contributing.on("accountName").withMinCount(1)) - .test()) - .probe()); + contributing.check("Account", contributing.on("accountName").withMinCount(1)).probe()); final OntologyShapeCheckModel related = new OntologyShapeCheckModel(COLUMN_RELATION, "Clickhouse"); assertEquals( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java index c90fe107223b..362ed6204642 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java @@ -21,7 +21,9 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -29,15 +31,16 @@ import org.openmetadata.schema.api.data.OntologyShapeCheckReason; import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; import org.openmetadata.service.ontology.OntologyShapeCheckGoldens.Golden; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; /** * Holds every generated shape check to the SQL text that a person read and committed: nine engine - * families, the six mapping shapes and each part that compiles to a query. The test reads the - * files and never writes one. + * families, the six mapping shapes and each part that compiles to a query. A pattern compiles to + * one for Postgres alone. The test reads the files and never writes one. */ class OntologyShapeCheckGoldenTest { private static final int FAMILIES = 9; - private static final int PARTS_OF_THE_SHAPES = 21; + private static final int PARTS_OF_THE_SHAPES = 25; private static final List NOT_WRITTEN_FOR_CLICKHOUSE = List.of( "columnRelation-placedBy-class", @@ -45,6 +48,12 @@ class OntologyShapeCheckGoldenTest { "linkTable-contains-class", "linkTable-contains-minCount", "repeatedContribution-addressCity-minCount"); + private static final List PATTERNS = + List.of( + "compositeKey-accountTier-pattern", + "filteredIdentity-personName-pattern", + "repeatedContribution-addressCity-pattern", + "unfilteredIdentity-customerEmail-pattern"); static List goldens() { return OntologyShapeCheckGoldens.all(); @@ -88,17 +97,26 @@ void everyGoldenFileBelongsToACheck() throws IOException, URISyntaxException { .toList()); } assertEquals( - FAMILIES * PARTS_OF_THE_SHAPES - NOT_WRITTEN_FOR_CLICKHOUSE.size(), goldens().size()); + FAMILIES * PARTS_OF_THE_SHAPES + - NOT_WRITTEN_FOR_CLICKHOUSE.size() + - (FAMILIES - 1) * PATTERNS.size(), + goldens().size()); } @Test - void aPartWithNoQueryIsOneThatKeepsUnmatchedRowsOnClickHouse() { + void aPartWithNoQueryIsAPatternOffPostgresOrOneThatKeepsUnmatchedRowsOnClickHouse() { final List refused = OntologyShapeCheckGoldens.asked().stream().filter(golden -> !golden.isGenerated()).toList(); + final List expected = new ArrayList<>(); + NOT_WRITTEN_FOR_CLICKHOUSE.forEach(name -> expected.add(resource("clickhouse", name))); + for (final SqlEngineFamily family : SqlEngineFamily.values()) { + if (family != SqlEngineFamily.POSTGRES) { + final String directory = family.name().toLowerCase(Locale.ROOT); + PATTERNS.forEach(name -> expected.add(resource(directory, name))); + } + } assertEquals( - NOT_WRITTEN_FOR_CLICKHOUSE.stream() - .map(name -> OntologyShapeCheckGoldens.DIRECTORY + "/clickhouse/" + name + ".sql") - .toList(), + expected.stream().sorted().toList(), refused.stream().map(Golden::resource).sorted().toList()); refused.forEach( golden -> @@ -107,4 +125,8 @@ void aPartWithNoQueryIsOneThatKeepsUnmatchedRowsOnClickHouse() { golden.answer(), golden.resource())); } + + private static String resource(final String family, final String name) { + return OntologyShapeCheckGoldens.DIRECTORY + "/" + family + "/" + name + ".sql"; + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java index 7cfe8a10733f..8e5327837e39 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java @@ -27,7 +27,6 @@ import java.util.function.UnaryOperator; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test.Generated; import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; import org.openmetadata.service.ontology.sql.SqlEngineFamily; @@ -39,6 +38,9 @@ final class OntologyShapeCheckGoldens { static final String DIRECTORY = "ontology/shape-checks"; + /** A wildcard, an escaped dot that is no wildcard, and a colon and a quote that a string escapes. */ + private static final String PATTERN = "^[A-Z][a-z0-9]+.(\\:|\\.|\\')*[^ ]{2,}$"; + private OntologyShapeCheckGoldens() {} /** @@ -89,8 +91,7 @@ String keys() { private Statements statements() { final OntologyPartOutcome.Check check = (OntologyPartOutcome.Check) answer(); - final Generated generated = (Generated) check.checks().getFirst().test(); - return OntologyShapeCheckSql.write(generated.probe()); + return OntologyShapeCheckSql.write(check.checks().getFirst().probe()); } @Override @@ -147,14 +148,18 @@ static List parts() { return List.copyOf(parts); } - /** The counts and the list of a text property. */ + /** + * The counts, the list and the pattern of a text property. The pattern holds each construct + * that is written in another way than it is given: a wildcard, and a backslash before a colon, + * a percent sign and a quote. + */ private static List valueParts( final Shape shape, final String type, final String property, final int count) { return List.of( new Asked(shape, type, property, "minCount", constraint -> constraint.withMinCount(count)), new Asked(shape, type, property, "maxCount", constraint -> constraint.withMaxCount(count)), - new Asked( - shape, type, property, "in", constraint -> constraint.withIn(literals("a", "b")))); + new Asked(shape, type, property, "in", constraint -> constraint.withIn(literals("a", "b"))), + new Asked(shape, type, property, "pattern", constraint -> constraint.withPattern(PATTERN))); } /** The counts of a relation of the order class, and the class its values must be records of. */ diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java index f2840f129d49..b9a9344d0b1d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java @@ -14,6 +14,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; @@ -38,14 +39,13 @@ import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; -import org.openmetadata.service.ontology.OntologyPartOutcome.Test.Generated; import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; import org.openmetadata.service.ontology.sql.SqlEngineFamily; /** * The text of the generated shape checks that the golden files of the six mapping shapes do not - * hold: a join of several columns, a filtered table on the far side of a join, a bound on one side - * and a list with no member. + * hold: a join of several columns, a filtered table on the far side of a join, a bound on one side, + * a list with no member and a pattern with a backslash. */ class OntologyShapeCheckSqlTest { private static final String POSTGRES = "Postgres"; @@ -83,8 +83,7 @@ private static String keys( private static Statements statements( final OntologyShapeCheckModel model, final String type, final OntologyShapeConstraint part) { - final Generated generated = (Generated) model.check(type, part).test(); - return OntologyShapeCheckSql.write(generated.probe()); + return OntologyShapeCheckSql.write(model.check(type, part).probe()); } private static OntologyShapeCheckModel shape(final Shape shape) { @@ -235,6 +234,45 @@ AND t1.city NOT IN ('London')""", keys(model, "Customer", model.on("addressCity").withIn(literals("London")))); } + @Test + void patternIsMatchedAgainstTheValueAsTextUnderTheCodePointCollation() { + final OntologyShapeCheckModel model = shape(UNFILTERED_IDENTITY); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ '^[a-z]+$')""", + keys(model, "Customer", model.on("customerEmail").withPattern("^[a-z]+$"))); + } + + @Test + void patternWithABackslashIsWrittenAsAStringThatReadsItsEscapes() { + final OntologyShapeCheckModel model = shape(UNFILTERED_IDENTITY); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+[^\\\\n\\\\r]\\\\@example\\\\.org$')""", + keys( + model, "Customer", model.on("customerEmail").withPattern("^[a-z]+.\\@example\\.org$"))); + } + + @Test + void patternOnATableThatAddsToTheRecordsJoinsItByTheKey() { + final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); + assertEquals( + """ + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND NOT (CAST(t1.tier AS text) COLLATE "C" ~ '^(gold|silver)$')""", + keys(model, "Account", model.on("accountTier").withPattern("^(gold|silver)$"))); + } + @Test void countQueryHoldsTheKeyListAndNothingThatOrdersOrLimitsIt() { final OntologyShapeCheckModel model = new OntologyShapeCheckModel(COLUMN_RELATION, "Mssql"); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java index 59a36565d795..a90ce1bd4158 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java @@ -44,7 +44,7 @@ void statementTextTakesNoCharacterThatOpensAStringANameAParameterOrAComment( assertThrows(IllegalArgumentException.class, () -> sql.sql("SELECT 1 " + character)); assertEquals( - "Statement text takes letters, digits, spaces, line breaks and _ , . ( ) * = < >." + "Statement text takes letters, digits, spaces, line breaks and _ , . ( ) * = < > ~." + " Pass a name to name() and a value to value()", refusal.getMessage()); } @@ -52,7 +52,7 @@ void statementTextTakesNoCharacterThatOpensAStringANameAParameterOrAComment( @Test void statementTextTakesKeywordsOperatorsAliasesAndNumbersAsTheyAreWritten() { final String text = - "SELECT TOP 50 t0.*, COUNT(*)\nFROM x t0 WHERE a <= 1 AND b <> 2 AND c >= 3 AND d_1 = 4"; + "SELECT TOP 50 t0.*, COUNT(*)\nFROM x t0 WHERE a <= 1 AND b <> 2 AND c >= 3 AND d_1 = 4 AND e ~ f"; assertEquals(text, SqlEngineFamily.TRINO.inline(TypedStatement.builder().sql(text).build())); assertEquals( diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql new file mode 100644 index 000000000000..7d055d45a6bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND NOT (CAST(t1.tier AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](\\:|\\.|\\'')*[^ ]{2,}$') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql new file mode 100644 index 000000000000..f106a5c82417 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND NOT (CAST(t0.name AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](\\:|\\.|\\'')*[^ ]{2,}$') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql new file mode 100644 index 000000000000..b2c3a03cdef2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND NOT (CAST(t1.city AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](\\:|\\.|\\'')*[^ ]{2,}$') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql new file mode 100644 index 000000000000..0c773b575be4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](\\:|\\.|\\'')*[^ ]{2,}$') +) c diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json index cb51d1208a9a..7b71568ec90f 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json @@ -13,13 +13,13 @@ "enum": ["minCount", "maxCount", "class", "datatype", "range", "in", "pattern"] }, "outcome": { - "description": "How a part is checked. `check` carries the tests that check it. `heldByMapping` needs no test, because the table bindings already hold the part for every record. `notMapped` means the class binds the property in no column, or the version read has no such property. `notEnforceable` means no test finds exactly the records that break the part, and `reason` says why. `hidden` means the caller may not view a table the answer rests on.", + "description": "How a part is checked. `check` carries the tests that check it. `heldByMapping` needs no test, because the table bindings already hold the part for every record. `notMapped` means the class binds the property in no column, or the version read has no such property. `notEnforceable` means no test finds exactly the records that break the part, and `reason` says why. `hidden` means the caller may not view a table the answer rests on, or the property the constraint is about.", "type": "string", "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckOutcome", "enum": ["check", "heldByMapping", "notMapped", "notEnforceable", "hidden"] }, "reason": { - "description": "Why a part has no exact test. `noIdentityTable`: the class binds the property and has no identity table, so it has no records. `severalTables`: the class binds the property in several columns, and a count over all of them has no test. `boundOnInverse`: the class does not bind the relation and another class binds its inverse. `noJoin` and `joinNotConfirmed`: the relation has no join, or one that is only inferred. `notARelation` and `notADataProperty`: the part asks for the other kind of property. `targetClassNotOnJoin`: the class the part names has no identity table where the join arrives. `subclassOnJoinTable`: a subclass of that class has its identity table there too, and the filter of the class would leave its records out. `valuesAreRecords`: the list names records by IRI. `valueDoesNotFitColumn`: a value does not parse as the data type of the column. `tooManyValues`: the list has more than 1,000 values. `columnTypeNotSupported`: the data type of the column takes no such comparison. `datatypeNotSupported`: the datatype is not one this answer reads. `datatypeMismatch`: the column can hold a value that is not of the datatype. `patternNotPortable`: engines read the pattern in different ways. `tableNotSimple`: the test reads rows, and the rows of the table are not its records one for one. `columnMissing`: a column of the binding left the table. `otherDatabase`: a table sits in another database than the identity table. `engineNotSupported`: no statement is written for the service type.", + "description": "Why a part has no exact test. `noIdentityTable`: the class binds the property and has no identity table, so it has no records. `severalTables`: the class binds the property in several columns, and a count over all of them has no test. `boundOnInverse`: the class does not bind the relation and another class binds its inverse. `noJoin` and `joinNotConfirmed`: the relation has no join, or one that is only inferred. `notARelation` and `notADataProperty`: the part asks for the other kind of property. `targetClassNotOnJoin`: the class the part names has no identity table where the join arrives. `subclassOnJoinTable`: a subclass of that class has its identity table there too, and the filter of the class would leave its records out. `valuesAreRecords`: the list names records by IRI. `valueDoesNotFitColumn`: a value does not parse as the data type of the column. `tooManyValues`: the list has more than 1,000 values. `columnTypeNotSupported`: the data type of the column takes no such comparison. `datatypeNotSupported`: the datatype is not one this answer reads. `datatypeMismatch`: nothing shows that every value the column can store is of the datatype, because its data type stores other values on this engine or was not read for it. `patternNotPortable`: the pattern leaves the constructs that are known to be read as SHACL reads them, or is too long for a statement. `columnMissing`: a column of the binding left the table. `otherDatabase`: a table sits in another database than the identity table. `engineNotSupported`: no statement is written for the service type, or none that asks this part. A pattern is matched on Postgres only.", "type": "string", "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckReason", "enum": [ @@ -39,7 +39,6 @@ "datatypeNotSupported", "datatypeMismatch", "patternNotPortable", - "tableNotSimple", "columnMissing", "otherDatabase", "engineNotSupported" @@ -69,7 +68,7 @@ "additionalProperties": false }, "check": { - "description": "One data quality test on one table. `testDefinition`, `entityLink` and `parameterValues` are what a request to create a test case takes. The result of the test is 0 violations exactly when every record of the class satisfies the part.", + "description": "One data quality test on one table: the test `tableCustomSQLQuery` with a statement written for the part. `testDefinition`, `entityLink` and `parameterValues` are what a request to create a test case takes. The result of the test is 0 violations exactly when every record of the class satisfies the part.", "type": "object", "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheck", "properties": { @@ -89,21 +88,21 @@ "default": [] }, "testDefinition": { - "description": "Fully qualified name of the test definition.", + "description": "Fully qualified name of the test definition, which is `tableCustomSQLQuery` for every check.", "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" }, "entityLink": { - "description": "The table, or the column of it, that the test is created on.", + "description": "The table that the test is created on.", "$ref": "../../type/basic.json#/definitions/entityLink" }, "parameterValues": { - "description": "The parameters of the test. A generated test carries its statement in `sqlExpression`, with every colon written as a backslash and a colon, and `strategy` `COUNT`, `operator` `<=` and `threshold` `0`. The statement returns one number, the records in violation.", + "description": "The parameters of the test: the statement in `sqlExpression`, with every colon written as a backslash and a colon, then `strategy` `COUNT`, `operator` `<=` and `threshold` `0`. The statement returns one number, the records in violation.", "type": "array", "items": { "$ref": "../../tests/testCase.json#/definitions/testCaseParameterValue" }, "default": [] }, "inspectionQuery": { - "description": "For a generated test, the statement that lists the keys of the records in violation, for a person to read. Absent on a test that needs no statement.", + "description": "The statement that lists the keys of the records in violation, for a person to read.", "$ref": "../../type/basic.json#/definitions/sqlQuery" }, "readBindings": { @@ -120,6 +119,7 @@ "testDefinition", "entityLink", "parameterValues", + "inspectionQuery", "readBindings" ], "additionalProperties": false @@ -155,7 +155,7 @@ "type": "string" }, "path": { - "description": "IRI of the property the constraint is about.", + "description": "IRI of the property the constraint is about. Absent when the caller may not view that property.", "$ref": "../../type/ontologyIri.json" }, "parts": { @@ -165,7 +165,7 @@ "default": [] } }, - "required": ["id", "path", "parts"], + "required": ["id", "parts"], "additionalProperties": false }, "checkedShape": { @@ -207,7 +207,7 @@ "$ref": "ontologyStatementPlan.json#/definitions/versionRead" }, "shapes": { - "description": "The shapes of that version that target the class, in name order. A shape that targets a parent of the class is not listed.", + "description": "The shapes of that version that target the class and that the caller may view, in name order. A shape that targets a parent of the class is not listed.", "type": "array", "items": { "$ref": "#/definitions/checkedShape" }, "default": [] From ec2e484f9f0fd0b5d053d8891c0c4b5d32083d0d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 12:54:33 -0800 Subject: [PATCH 083/203] Run the generated checks and a pattern on a database The answer tests expect the generated query where they expected a column test. A new test runs the pattern check on Postgres rows that hold a line break, a letter of the other case and characters outside ASCII, and on a column whose collation folds case. On MySQL it asserts that a pattern has no check. --- .../it/tests/OntologyShapeCheckAnswerIT.java | 171 ++++++++------ .../it/tests/OntologyShapeCheckPatternIT.java | 211 ++++++++++++++++++ 2 files changed, 315 insertions(+), 67 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java index a8b0fccf6e71..52d9042661e4 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java @@ -39,7 +39,6 @@ import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; -import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.parameter; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.part; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.read; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.reference; @@ -84,7 +83,6 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; import org.openmetadata.schema.entity.data.OntologyShape; -import org.openmetadata.schema.tests.TestCaseParameterValue; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.type.OntologyExpression; import org.openmetadata.schema.type.OntologyExpressionKind; @@ -97,15 +95,15 @@ import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; /** - * What {@code GET /v1/ontologyConcepts/{id}/shapeChecks} answers for each outcome: a column test of - * the catalog, a generated test, a part that the mapping holds, a property with no binding, a part - * with no exact test, and the version that a request names. + * What {@code GET /v1/ontologyConcepts/{id}/shapeChecks} answers for each outcome: a test with its + * statement, a part that the mapping holds, a property with no binding, a part with no exact test, + * and the version that a request names. */ @ExtendWith(TestNamespaceExtension.class) class OntologyShapeCheckAnswerIT extends BaseOntologyApprovalIT { private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; private static final String TABLE_LINK = "<#E::table::%s>"; - private static final String COLUMN_LINK = "<#E::table::%s::columns::%s>"; + private static final String POSTGRES = "postgres"; /** One table whose declared key is its subject key, so each row is one record. */ private static final Shape ACCOUNTS = @@ -141,31 +139,50 @@ private OntologyShapeCheckBinding binding() { return read(fixture, "Account", "accounts", 1L); } - private OntologyShapeCheck test(final String column) { + /** A test of the table, with the list of keys that its statement counts. */ + OntologyShapeCheck test(final String column, final String count) { return new OntologyShapeCheck() .withTable(reference(fixture, "accounts")) .withColumns(List.of(List.of(column))) - .withReadBindings(List.of(binding())); - } - - /** A test that the catalog defines for one column. */ - OntologyShapeCheck columnTest( - final String definition, final String column, final TestCaseParameterValue... parameters) { - return test(column) - .withTestDefinition(definition) - .withEntityLink(COLUMN_LINK.formatted(tableName(), column)) - .withParameterValues(List.of(parameters)); - } - - /** A generated test of the table, with the list of keys that its statement counts. */ - OntologyShapeCheck generated(final String column, final String count) { - return test(column) + .withReadBindings(List.of(binding())) .withTestDefinition(CUSTOM_SQL) .withEntityLink(TABLE_LINK.formatted(tableName())) .withParameterValues(countParameters(count)) .withInspectionQuery(keyList(count)); } + /** The statement that counts the accounts whose value in a column breaks {@code test}. */ + String countWhere(final String column, final String test) { + final String id = fixture.name("id"); + return String.join( + "\n", + "SELECT COUNT(*) AS violations", + "FROM (", + " SELECT DISTINCT t0." + id + " AS k0", + " FROM " + fixture.from("accounts") + " t0", + " WHERE t0." + id + " IS NOT NULL", + " AND " + test.replace("{}", "t0." + fixture.name(column)), + ") c"); + } + + /** The statement that counts the accounts with no value in a column. */ + String countWithout(final String column) { + final String id = fixture.name("id"); + return String.join( + "\n", + "SELECT COUNT(*) AS violations", + "FROM (", + " SELECT k.k0", + " FROM (", + " SELECT DISTINCT t0." + id + " AS k0, t0." + fixture.name(column) + " AS v0", + " FROM " + fixture.from("accounts") + " t0", + " WHERE t0." + id + " IS NOT NULL", + " ) k", + " GROUP BY k.k0", + " HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1", + ") c"); + } + /** A part that one test checks, which takes its name from what it checks. */ OntologyCheckedPart checked( final String constraint, final OntologyShapePart part, final OntologyShapeCheck test) { @@ -200,13 +217,14 @@ private static OntologyShapeCheckReason reason( } @Test - void aTableWhoseRowsAreItsRecordsGetsTheColumnTestsOfTheCatalog(final TestNamespace ns) { + void aTableWhoseRowsAreItsRecordsGetsAStatementForEveryCheckToo(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "accounts"); try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { fixture.bindAll(); fixture.property("accountNote"); declareKey(fixture, "accounts", List.of("id"), "email"); + final boolean postgres = POSTGRES.equals(fixture.family()); final OntologyConcept account = fixture.type("Account"); final Accounts accounts = new Accounts( @@ -229,56 +247,46 @@ void aTableWhoseRowsAreItsRecordsGetsTheColumnTestsOfTheCatalog(final TestNamesp .withDatatypeIri(URI.create(XSD + "date")), on(fixture, "note-required", "accountNote").withMinCount(1), on(fixture, "nick-class", "accountNick").withClassIri(account.getIri()))); - final String id = fixture.name("id"); - final String countOfNick = - String.join( - "\n", - "SELECT COUNT(*) AS violations", - "FROM (", - " SELECT DISTINCT t0." + id + " AS k0", - " FROM " + fixture.from("accounts") + " t0", - " WHERE t0." + id + " IS NOT NULL", - " AND t0." + fixture.name("nick") + " NOT IN ('x')", - ") c"); - final OntologyCheckedPart notNull = + final OntologyCheckedPart requiredPart = accounts.checked( - "email-count", MIN_COUNT, accounts.columnTest("columnValuesToBeNotNull", "email")); - final OntologyCheckedPart inSet = + "email-count", MIN_COUNT, accounts.test("email", accounts.countWithout("email"))); + final OntologyCheckedPart emailListedPart = accounts.checked( "email-listed", IN, - accounts.columnTest( - "columnValuesToBeInSet", - "email", - parameter("allowedValues", "[\"a\",\"b\"]"), - parameter("matchEnum", "true"))); - final OntologyCheckedPart listed = - accounts.checked("nick-listed", IN, accounts.generated("nick", countOfNick)); - final OntologyCheckedPart regex = + accounts.test("email", accounts.countWhere("email", "{} NOT IN ('a', 'b')"))); + final OntologyCheckedPart nickListedPart = accounts.checked( - "nick-pattern", - PATTERN, - accounts.columnTest( - "columnValuesToMatchRegex", "nick", parameter("regex", "^[0-9]{3}$"))); - final OntologyCheckedPart between = + "nick-listed", + IN, + accounts.test("nick", accounts.countWhere("nick", "{} NOT IN ('x')"))); + // A pattern is matched on Postgres only, and no other engine gets a statement for one. + final OntologyCheckedPart matched = + postgres + ? accounts.checked( + "nick-pattern", + PATTERN, + accounts.test( + "nick", + accounts.countWhere( + "nick", "NOT (CAST({} AS text) COLLATE \"C\" ~ '^[0-9]{3}$')"))) + : entry(PATTERN, NOT_ENFORCEABLE) + .withReason(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + final OntologyCheckedPart rangedPart = accounts.checked( "age-range", RANGE, - accounts.columnTest( - "columnValuesToBeBetween", - "age", - parameter("minValue", "0"), - parameter("maxValue", "120"))); + accounts.test("age", accounts.countWhere("age", "({} < 0 OR {} > 120)"))); final List constraints = List.of( accounts.constraint("no-required", "accountNo", entry(MIN_COUNT, HELD_BY_MAPPING)), accounts.constraint( - "email-count", "accountEmail", notNull, entry(MAX_COUNT, HELD_BY_MAPPING)), - accounts.constraint("email-listed", "accountEmail", inSet), - accounts.constraint("nick-listed", "accountNick", listed), - accounts.constraint("nick-pattern", "accountNick", regex), + "email-count", "accountEmail", requiredPart, entry(MAX_COUNT, HELD_BY_MAPPING)), + accounts.constraint("email-listed", "accountEmail", emailListedPart), + accounts.constraint("nick-listed", "accountNick", nickListedPart), + accounts.constraint("nick-pattern", "accountNick", matched), accounts.constraint( - "age-range", "accountAge", entry(DATATYPE, HELD_BY_MAPPING), between), + "age-range", "accountAge", entry(DATATYPE, HELD_BY_MAPPING), rangedPart), accounts.constraint( "email-type", "accountEmail", @@ -311,13 +319,42 @@ void aTableWhoseRowsAreItsRecordsGetsTheColumnTestsOfTheCatalog(final TestNamesp JsonUtils.readTree(JsonUtils.pojoToJson(expected)), JsonUtils.readTree(answer(admin(), account, DRAFT))); - // The nick column may hold a null, so its list is a generated test, and a null passes it. - final OntologyShapeCheck nick = check(checks(admin(), account, DRAFT), "nick-listed", IN); - assertCounts("0", List.of(), nick); - addRows(fixture, "accounts", row(1, "a", "x", 10), row(2, "b", null, 20)); - assertCounts("0", List.of(), nick); - addRows(fixture, "accounts", row(3, "a", "y", 30)); - assertCounts("1", List.of(List.of("3")), nick); + // The table has no row yet, and a statement counts nothing on an empty table. + final OntologyShapeChecks checks = checks(admin(), account, DRAFT); + final OntologyShapeCheck required = check(checks, "email-count", MIN_COUNT); + final OntologyShapeCheck emailListed = check(checks, "email-listed", IN); + final OntologyShapeCheck nickListed = check(checks, "nick-listed", IN); + final OntologyShapeCheck ranged = check(checks, "age-range", RANGE); + final List run = List.of(required, emailListed, nickListed, ranged); + run.forEach(check -> assertCounts("0", List.of(), check)); + + // Account 2 has no nick, and a null breaks no list. + addRows(fixture, "accounts", row(1, "a", "x", 10), row(2, "b", null, 120)); + run.forEach(check -> assertCounts("0", List.of(), check)); + + // One account breaks each part. The catalog says that email holds no null and that id is + // the key, and the table holds a null email and a row with no id all the same. + addRows( + fixture, + "accounts", + row(3, null, "x", 30), + row(4, "c", "x", 40), + row(5, "a", "y", 50), + row(6, "a", "x", 121), + row(null, "c", "y", 500)); + assertCounts("1", List.of(List.of("3")), required); + assertCounts("1", List.of(List.of("4")), emailListed); + assertCounts("1", List.of(List.of("5")), nickListed); + assertCounts("1", List.of(List.of("6")), ranged); + if (postgres) { + // Account 2 has no nick and account 8 has one of three digits. + addRows(fixture, "accounts", row(7, "a", "12x", 1), row(8, "a", "123", 1)); + assertCounts( + "6", + List.of( + List.of("1"), List.of("3"), List.of("4"), List.of("5"), List.of("6"), List.of("7")), + check(checks, "nick-pattern", PATTERN)); + } } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java new file mode 100644 index 000000000000..effe781e687b --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java @@ -0,0 +1,211 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.CUSTOM_SQL; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.addRows; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.assertCounts; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.check; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.part; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.row; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyShapePart.PATTERN; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Runs the pattern test of {@code GET /v1/ontologyConcepts/{id}/shapeChecks} on Postgres, on the + * values that show whether an engine reads a pattern as SHACL does: a line break inside a value + * and at its end, a letter of the other case, and a letter and a digit outside ASCII. On any + * other database the part has no test, and that is asserted there. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckPatternIT extends BaseOntologyApprovalIT { + private static final List> NO_KEYS = List.of(); + private static final String POSTGRES = "postgres"; + private static final List CONSTRAINTS = List.of("pair", "digits", "word", "mail"); + + /** One table with a text column for each pattern, and two rows that match every one. */ + private static final Shape CODES = + mapping( + "codes", + List.of( + table( + "codes", + List.of(integer("id"), text("pair"), text("digits"), text("word"), text("mail")), + row(1, "1x2", "123", "abc", "ada@example.org"), + row(2, "1 2", "7", "z", "grace@example.org"))), + List.of("Code"), + List.of( + data("codePair", "Code"), + data("codeDigits", "Code"), + data("codeWord", "Code"), + data("codeMail", "Code")), + identityTable( + "Code", + "codes", + List.of("id"), + null, + bound("codePair", "pair"), + bound("codeDigits", "digits"), + bound("codeWord", "word"), + bound("codeMail", "mail"))); + + /** Declares one pattern for each text column of the codes table and asks how they are checked. */ + private static OntologyShapeChecks patterns( + final Ontology ontology, final OntologyShapeFixture fixture) { + fixture.bindAll(); + declare( + ontology, + fixture, + "CodeShape", + "Code", + on(fixture, "pair", "codePair").withPattern("^1.2$"), + on(fixture, "digits", "codeDigits").withPattern("^[0-9]+$"), + on(fixture, "word", "codeWord").withPattern("^[a-z]+$"), + on(fixture, "mail", "codeMail").withPattern("^[a-z]+\\@[a-z]+\\.org$")); + return checks(admin(), fixture.type("Code"), DRAFT); + } + + private static void assertNoTestOffPostgres(final OntologyShapeChecks checks) { + for (final String constraint : CONSTRAINTS) { + final OntologyCheckedPart pattern = part(checks, constraint, PATTERN); + assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, pattern.getOutcome(), constraint); + assertEquals(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED, pattern.getReason(), constraint); + assertNull(pattern.getChecks(), constraint); + } + } + + private static void execute(final String statement) { + TestSuiteBootstrap.getJdbi().useHandle(handle -> handle.execute(statement)); + } + + @Test + void aPatternCountsTheRecordsWithAValueThatItDoesNotMatch(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "codes"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, CODES).withRows()) { + final OntologyShapeChecks checks = patterns(ontology, fixture); + if (!POSTGRES.equals(fixture.family())) { + assertNoTestOffPostgres(checks); + return; + } + final OntologyShapeCheck pair = check(checks, "pair", PATTERN); + final OntologyShapeCheck digits = check(checks, "digits", PATTERN); + final OntologyShapeCheck word = check(checks, "word", PATTERN); + final OntologyShapeCheck mail = check(checks, "mail", PATTERN); + + assertEquals(CUSTOM_SQL, pair.getTestDefinition()); + assertEquals( + String.join( + "\n", + "SELECT DISTINCT t0.id AS k0", + "FROM " + fixture.from("codes") + " t0", + "WHERE t0.id IS NOT NULL", + " AND NOT (CAST(t0.pair AS text) COLLATE \"C\" ~ E'^1[^\\\\n\\\\r]2$')"), + pair.getInspectionQuery()); + for (final OntologyShapeCheck check : List.of(pair, digits, word, mail)) { + assertCounts("0", NO_KEYS, check); + } + + // Codes 3 and 4 hold a line feed or a carriage return, inside a value, after it and before + // it. Code 5 holds a letter and digits outside ASCII, and a capital. Code 6 holds no value, + // code 7 holds values that are too short or empty, and the row with no id is no code. + addRows( + fixture, + "codes", + row(3, "1\n2", "123\n", "aBc", "ada@exampleXorg"), + row(4, "1\r2", "\n123", "B", "ada@example.org\n"), + row(5, "1é2", "١٢٣", "é", "ADA@example.org"), + row(6, null, null, null, null), + row(7, "12", "", "", "a@b.org"), + row(null, "bad", "bad", "BAD", "bad")); + + assertCounts("3", List.of(List.of("3"), List.of("4"), List.of("7")), pair); + assertCounts("4", List.of(List.of("3"), List.of("4"), List.of("5"), List.of("7")), digits); + assertCounts("4", List.of(List.of("3"), List.of("4"), List.of("5"), List.of("7")), word); + assertCounts("3", List.of(List.of("3"), List.of("4"), List.of("5")), mail); + } + } + + @Test + void aPatternReadsARangeByCodePointWhateverTheCollationOfItsColumn(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "collated"); + final String folding = "fold_" + UUID.randomUUID().toString().substring(0, 8); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, CODES).withRows()) { + final OntologyShapeChecks checks = patterns(ontology, fixture); + if (!POSTGRES.equals(fixture.family())) { + assertNoTestOffPostgres(checks); + return; + } + final String codes = fixture.from("codes"); + final OntologyShapeCheck word = check(checks, "word", PATTERN); + final OntologyShapeCheck mail = check(checks, "mail", PATTERN); + // The word column sorts B between a and z. The mail column calls ADA and ada equal, and + // Postgres refuses to match a regular expression under such a collation. + execute( + "CREATE COLLATION " + + folding + + " (provider = icu, locale = 'und-u-ks-level2', deterministic = false)"); + try { + execute( + "ALTER TABLE " + codes + " ALTER COLUMN word TYPE VARCHAR(64) COLLATE \"en-x-icu\""); + execute("ALTER TABLE " + codes + " ALTER COLUMN mail TYPE VARCHAR(64) COLLATE " + folding); + addRows( + fixture, + "codes", + row(3, "1x2", "1", "B", "ADA@example.org"), + row(4, "1x2", "1", "b", "ada@example.org")); + + assertEquals( + List.of(List.of("3", "inside", "same")), + OntologyShapeFixture.run( + "SELECT id, CASE WHEN word BETWEEN 'a' AND 'z' THEN 'inside' ELSE 'outside' END," + + " CASE WHEN mail = 'ada@example.org' THEN 'same' ELSE 'other' END FROM " + + codes + + " WHERE id = 3")); + assertCounts("1", List.of(List.of("3")), word); + assertCounts("1", List.of(List.of("3")), mail); + } finally { + execute("ALTER TABLE " + codes + " ALTER COLUMN mail TYPE VARCHAR(64) COLLATE \"C\""); + execute("DROP COLLATION " + folding); + } + } + } +} From edb55fd9da97452cfc3aa755d4df9259acfa1c14 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 12:54:44 -0800 Subject: [PATCH 084/203] Hide the shapes and the properties a caller may not view The answer left out no shape and named every property, whoever asked. One batch now drops each shape that the caller may not view, before anything is read for it. A second batch finds the properties of the constraints that the caller may not view. A constraint about one keeps its id, loses its path and answers hidden for each part it states. A draft asks about the live rows by id. A release asks about the definitions as it holds them, so a released shape still answers after its working row is deleted. A request now runs 46 statements for a draft and 52 for a release, for any number of tables and constraints. Also test that a binding write of a class that a part names makes the reader read the rows again, and that the shapes of a release are read from every page of its members. --- .../OntologyShapeCheckDefinitionRightsIT.java | 343 ++++++++++++++++++ .../it/tests/OntologyShapeCheckReadsIT.java | 280 +++++++++----- .../ontology/OntologyShapeCheckAnswer.java | 35 +- .../ontology/OntologyShapeCheckReader.java | 38 +- .../service/ontology/OntologyVersion.java | 33 ++ .../OntologyShapeCheckAnswerTest.java | 46 +++ .../OntologyShapeCheckReaderTest.java | 204 ++++++++++- .../OntologyShapeCheckValueCasesTest.java | 3 +- 8 files changed, 872 insertions(+), 110 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java new file mode 100644 index 000000000000..4cf3db7b2e3d --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java @@ -0,0 +1,343 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.answer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.HIDDEN; +import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; +import static org.openmetadata.schema.api.data.OntologyShapePart.IN; +import static org.openmetadata.schema.api.data.OntologyShapePart.MAX_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.MIN_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; + +/** + * What a reader who may not view a shape, or the property a constraint is about, reads from {@code + * GET /v1/ontologyConcepts/{id}/shapeChecks}. A shape the reader may not view is left out. A + * constraint about a property the reader may not view says only {@code hidden} for each part it + * states, and does not name the property. Every reader here holds every other right, so each + * reads the working draft too. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckDefinitionRightsIT extends BaseOntologyApprovalIT { + private static final String ORDER_SHAPE = "OrderShape"; + private static final String LINE_SHAPE = "LineShape"; + private static final String EVERY_RESOURCE = "All"; + private static final String NOT_THE_OWNER = "!isOwner()"; + private static final List VERSIONS = List.of(RELEASE, DRAFT); + private static final List PROPERTIES = + List.of("orderChannel", "contains", "itemQuantity"); + + /** The parts that each constraint of the two shapes states, by the id of the constraint. */ + private static final Map> STATED = + Map.of( + "onChannel", List.of(IN), + "onProducts", List.of(MIN_COUNT, MAX_COUNT, CLASS), + "channelRequired", List.of(MIN_COUNT), + "onQuantity", List.of(RANGE)); + + /** + * Two shapes of the order class of the link table mapping, with an active release. Between them + * they state a part about each of its three properties, and they differ in name and severity. + */ + private record Scene(OntologyShapeFixture fixture, OntologyShape orders, OntologyShape lines) { + static Scene released( + final TestNamespace ns, final Ontology ontology, final OntologyShapeFixture fixture) { + fixture.bindAll(); + final OntologyShape orders = + declare( + ontology, + fixture, + ORDER_SHAPE, + "Order", + on(fixture, "onChannel", "orderChannel").withIn(literals("web", "store")), + on(fixture, "onProducts", "contains") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(fixture.type("Product").getIri())); + final OntologyShape lines = + admin() + .ontologyShapes() + .create( + new CreateOntologyShape() + .withName(LINE_SHAPE) + .withDisplayName(LINE_SHAPE) + .withDescription("What the lines of an order must satisfy") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(fixture.type("Order").getIri()) + .withSeverity(OntologyShapeSeverity.WARNING) + .withConstraints( + List.of( + on(fixture, "channelRequired", "orderChannel").withMinCount(1), + on(fixture, "onQuantity", "itemQuantity") + .withMinInclusive(limit("1"))))); + activate(ns, ontology); + return new Scene(fixture, orders, lines); + } + + OntologyConcept order() { + return fixture.type("Order"); + } + + /** The answer as an administrator reads it now, which masks and leaves out nothing. */ + OntologyShapeChecks whole(final OntologyStatementVersion version) { + final OntologyShapeChecks whole = checks(admin(), order(), version); + assertEquals( + List.of(LINE_SHAPE, ORDER_SHAPE), + whole.getShapes().stream().map(OntologyCheckedShape::getName).toList()); + return whole; + } + + /** The whole answer with only the shape of this name. */ + OntologyShapeChecks only(final OntologyStatementVersion version, final String shape) { + final OntologyShapeChecks whole = whole(version); + return whole.withShapes( + whole.getShapes().stream().filter(found -> found.getName().equals(shape)).toList()); + } + + /** + * The whole answer with each of these constraints as a reader who may not view its property + * reads it: its id, and {@code hidden} for each part it states. + */ + OntologyShapeChecks masking(final OntologyStatementVersion version, final String... ids) { + final OntologyShapeChecks whole = whole(version); + for (final OntologyCheckedShape shape : whole.getShapes()) { + shape.setConstraints( + shape.getConstraints().stream() + .map(found -> Arrays.asList(ids).contains(found.getId()) ? hidden(found) : found) + .toList()); + } + return whole; + } + + private static OntologyCheckedConstraint hidden(final OntologyCheckedConstraint found) { + return new OntologyCheckedConstraint() + .withId(found.getId()) + .withParts( + STATED.get(found.getId()).stream() + .map(part -> new OntologyCheckedPart().withPart(part).withOutcome(HIDDEN)) + .toList()); + } + + void assertNamesNothingOf(final String body, final OntologyShape denied) { + assertFalse(body.contains(denied.getId().toString()), body); + assertFalse(body.contains(denied.getName()), body); + assertFalse(body.contains(denied.getSeverity().value()), body); + } + + void assertNamesNothingOf(final String body, final String property) { + final OntologyProperty denied = fixture.property(property); + assertFalse(body.contains(denied.getId().toString()), body); + assertFalse(body.contains(denied.getName()), body); + assertFalse(body.contains(denied.getIri().toString()), body); + } + } + + private static void assertAnswer(final OntologyShapeChecks expected, final String body) { + assertEquals(JsonUtils.readTree(JsonUtils.pojoToJson(expected)), JsonUtils.readTree(body)); + } + + private static void owns(final OpenMetadataClient reader, final OntologyShape shape) { + final String id = shape.getId().toString(); + admin() + .ontologyShapes() + .update( + id, + admin() + .ontologyShapes() + .get(id, "owners") + .withOwners(List.of(readerReference(reader)))); + } + + private static void owns(final OpenMetadataClient reader, final OntologyProperty property) { + final String id = property.getId().toString(); + admin() + .ontologyProperties() + .update( + id, + admin() + .ontologyProperties() + .get(id, "owners") + .withOwners(List.of(readerReference(reader)))); + } + + @Test + void aReaderWhoMayViewNoShapeReadsAnAnswerWithNoShape(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deniedShapes"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var basic = new RdfAccessFixtures("chkShB" + ns.shortPrefix()); + var all = new RdfAccessFixtures("chkShA" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final List readers = + List.of( + callerWithout(basic, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_SHAPE, null), + callerWithout(all, MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_SHAPE, null)); + + for (final OntologyStatementVersion version : VERSIONS) { + for (final OpenMetadataClient reader : readers) { + final String body = answer(reader, scene.order(), version); + + assertAnswer(scene.whole(version).withShapes(List.of()), body); + scene.assertNamesNothingOf(body, scene.orders()); + scene.assertNamesNothingOf(body, scene.lines()); + } + } + } + } + + @Test + void aReaderWhoMayViewNoPropertyReadsHiddenForEveryConstraintAndNoPath(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deniedProperties"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var basic = new RdfAccessFixtures("chkPrB" + ns.shortPrefix()); + var all = new RdfAccessFixtures("chkPrA" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final List readers = + List.of( + callerWithout(basic, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_PROPERTY, null), + callerWithout(all, MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_PROPERTY, null)); + + for (final OntologyStatementVersion version : VERSIONS) { + for (final OpenMetadataClient reader : readers) { + final String body = answer(reader, scene.order(), version); + + assertAnswer( + scene.masking(version, "onChannel", "onProducts", "channelRequired", "onQuantity"), + body); + assertFalse(body.contains("\"path\""), body); + PROPERTIES.forEach(property -> scene.assertNamesNothingOf(body, property)); + } + } + } + } + + @Test + void aReaderReadsTheShapesAndThePropertiesTheyMayViewAsAnyoneReadsThem(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "ownedDefinitions"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var shapes = new RdfAccessFixtures("chkShO" + ns.shortPrefix()); + var properties = new RdfAccessFixtures("chkPrO" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final OpenMetadataClient ofOneShape = + callerWithout(shapes, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_SHAPE, NOT_THE_OWNER); + final OpenMetadataClient ofTwoProperties = + callerWithout( + properties, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_PROPERTY, NOT_THE_OWNER); + owns(ofOneShape, scene.orders()); + owns(ofTwoProperties, fixture.property("orderChannel")); + owns(ofTwoProperties, fixture.property("itemQuantity")); + + for (final OntologyStatementVersion version : VERSIONS) { + final String oneShape = answer(ofOneShape, scene.order(), version); + final String twoProperties = answer(ofTwoProperties, scene.order(), version); + + assertAnswer(scene.only(version, ORDER_SHAPE), oneShape); + scene.assertNamesNothingOf(oneShape, scene.lines()); + assertAnswer(scene.masking(version, "onProducts"), twoProperties); + scene.assertNamesNothingOf(twoProperties, "contains"); + } + } + } + + @Test + void aReaderWhoMayViewEverythingReadsTheBytesAnAdministratorReads(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "allowedReader"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("chkAll" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final var everything = access.allowRole(MetadataOperation.ALL, EVERY_RESOURCE); + final OpenMetadataClient reader = + client(access.userToken("reader", List.of(everything.getId()))); + + for (final OntologyStatementVersion version : VERSIONS) { + final String body = answer(reader, scene.order(), version); + + assertEquals(answer(admin(), scene.order(), version), body); + assertTrue(body.contains(scene.orders().getId().toString()), body); + assertTrue(body.contains(scene.lines().getId().toString()), body); + PROPERTIES.forEach( + property -> + assertTrue(body.contains(fixture.property(property).getIri().toString()), body)); + } + } + } + + @Test + void aReleasedShapeIsReadAsReleasedAfterItsWorkingRowIsDeleted(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedShape"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var owned = new RdfAccessFixtures("chkShD" + ns.shortPrefix()); + var denied = new RdfAccessFixtures("chkShN" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final OpenMetadataClient owner = + callerWithout(owned, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_SHAPE, NOT_THE_OWNER); + final OpenMetadataClient ofNoShape = + callerWithout(denied, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_SHAPE, null); + owns(owner, scene.lines()); + final String ownerRead = answer(owner, scene.order(), RELEASE); + final String everyoneRead = answer(admin(), scene.order(), RELEASE); + assertAnswer(scene.only(RELEASE, LINE_SHAPE), ownerRead); + + admin().ontologyShapes().delete(scene.lines().getId().toString()); + + assertEquals(ownerRead, answer(owner, scene.order(), RELEASE)); + assertEquals(everyoneRead, answer(admin(), scene.order(), RELEASE)); + scene.assertNamesNothingOf(answer(ofNoShape, scene.order(), RELEASE), scene.lines()); + assertEquals( + List.of(ORDER_SHAPE), + checks(admin(), scene.order(), DRAFT).getShapes().stream() + .map(OntologyCheckedShape::getName) + .toList()); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index 489e68af7510..99e7f74bd372 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -41,6 +41,7 @@ import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Isolated; @@ -54,12 +55,16 @@ import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.Entity; import org.openmetadata.service.monitoring.RequestLatencyContext; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; /** * How many statements {@code GET /v1/ontologyConcepts/{id}/shapeChecks} runs. Each kind of input is - * read once for the answer, so a class with five shapes and forty constraints is read in the - * statements of a class with one shape and one constraint. + * read once for the answer, and the caller's right to view is checked once for the shapes, once + * for the properties and once for the tables. So a class with eighty constraints is read in the + * statements of a class with one, and a class of twelve tables in the statements of one of three. */ @Isolated("Counts the SQL statements that serve one request") @ExtendWith(TestNamespaceExtension.class) @@ -72,44 +77,63 @@ class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { private static final String SETTINGS = "from openmetadata_settings"; /** Every statement of one read of the draft, as an administrator, and of the active release. */ - private static final int DRAFT_STATEMENTS = 36; - - private static final int RELEASE_STATEMENTS = 44; - - /** An order class that binds five tables, and a relation that arrives at a sixth. */ - private static final Shape SIX_TABLES = - mapping( - "sixTables", - List.of( - table("orders", List.of(integer("id"), text("channel"))), - table("order_notes", List.of(integer("order_id"), text("note"))), - table("order_flags", List.of(integer("order_id"), text("flag"))), - table("order_tags", List.of(integer("order_id"), text("tag"))), - table( - "order_items", - List.of(integer("order_id"), text("product_sku"), integer("quantity"))), - table("products", List.of(text("sku"), text("title")))), - List.of("Order", "Product"), - List.of( - data("orderChannel", "Order"), - data("orderNote", "Order"), - data("orderFlag", "Order"), - data("orderTag", "Order"), - data("itemQuantity", "Order"), - data("productTitle", "Product"), - relation("contains", "Order", "Product")), - identityTable("Order", "orders", List.of("id"), null, bound("orderChannel", "channel")), - identityTable( - "Product", "products", List.of("sku"), null, bound("productTitle", "title")), - contributing("Order", "order_notes", List.of("order_id"), bound("orderNote", "note")), - contributing("Order", "order_flags", List.of("order_id"), bound("orderFlag", "flag")), - contributing("Order", "order_tags", List.of("order_id"), bound("orderTag", "tag")), + private static final int DRAFT_STATEMENTS = 46; + + private static final int RELEASE_STATEMENTS = 52; + + /** A shape holds at most this many of the constraints that a test declares. */ + private static final int CONSTRAINTS_OF_A_SHAPE = 5; + + /** + * An order class that binds its identity table, a link table, and one more table for each note + * property. Its relation arrives at one more table, so the mapping has {@code notes + 3} tables. + */ + private static Shape orders(final String name, final int notes) { + final List tables = + new ArrayList<>( + List.of( + table("orders", List.of(integer("id"), text("channel"))), + table( + "order_items", + List.of(integer("order_id"), text("product_sku"), integer("quantity"))), + table("products", List.of(text("sku"), text("title"))))); + final List properties = + new ArrayList<>( + List.of( + data("orderChannel", "Order"), + data("itemQuantity", "Order"), + data("productTitle", "Product"), + relation("contains", "Order", "Product"))); + final List bindings = + new ArrayList<>( + List.of( + identityTable( + "Order", "orders", List.of("id"), null, bound("orderChannel", "channel")), + identityTable( + "Product", "products", List.of("sku"), null, bound("productTitle", "title")), + contributing( + "Order", + "order_items", + List.of("order_id"), + bound("itemQuantity", "quantity"), + joined("contains", "product_sku", "products", "sku")))); + for (int note = 0; note < notes; note++) { + tables.add(table("order_notes" + note, List.of(integer("order_id"), text("note")))); + properties.add(data("orderNote" + note, "Order")); + bindings.add( contributing( "Order", - "order_items", + "order_notes" + note, List.of("order_id"), - bound("itemQuantity", "quantity"), - joined("contains", "product_sku", "products", "sku"))); + bound("orderNote" + note, "note"))); + } + return mapping( + name, + tables, + List.of("Order", "Product"), + properties, + bindings.toArray(BindingSpec[]::new)); + } /** The statements of one request, as the server rendered them. */ private record Reads(OntologyShapeChecks answer, List statements) { @@ -189,22 +213,49 @@ private static String plain(final String rendered) { .toLowerCase(Locale.ROOT); } - /** The first {@code count} of ten constraints that between them rest on all six tables. */ - private static OntologyShapeConstraint[] constraints( - final OntologyShapeFixture fixture, final int count) { - return List.of( - on(fixture, "product", "contains").withClassIri(fixture.type("Product").getIri()), - on(fixture, "channel", "orderChannel").withIn(literals("web", "store")), - on(fixture, "note", "orderNote").withMinCount(1), - on(fixture, "flag", "orderFlag").withMaxCount(1), - on(fixture, "tag", "orderTag").withIn(literals("new", "gift")), - on(fixture, "quantity", "itemQuantity").withMinInclusive(limit("1")), - on(fixture, "some", "contains").withMinCount(1), - on(fixture, "one", "contains").withMaxCount(1), - on(fixture, "noteOnce", "orderNote").withMaxCount(1), - on(fixture, "tagRequired", "orderTag").withMinCount(1)) - .subList(0, count) - .toArray(OntologyShapeConstraint[]::new); + /** + * Every constraint that a shape of a test can hold: seven on the three tables that every mapping + * has, and two on each note table. Between them they rest on every table of the mapping. + */ + private static List stated( + final OntologyShapeFixture fixture, final int notes) { + final List stated = + new ArrayList<>( + List.of( + on(fixture, "product", "contains").withClassIri(fixture.type("Product").getIri()), + on(fixture, "channel", "orderChannel").withIn(literals("web", "store")), + on(fixture, "quantity", "itemQuantity").withMinInclusive(limit("1")), + on(fixture, "some", "contains").withMinCount(1), + on(fixture, "one", "contains").withMaxCount(1), + on(fixture, "channelOnce", "orderChannel").withMaxCount(1), + on(fixture, "quantityRequired", "itemQuantity").withMinCount(1))); + for (int note = 0; note < notes; note++) { + stated.add(on(fixture, "note" + note, "orderNote" + note).withMinCount(1)); + stated.add( + on(fixture, "noteListed" + note, "orderNote" + note).withIn(literals("new", "gift"))); + } + return stated; + } + + /** + * Declares shapes of the order class until it has {@code upTo} constraints, given that it has + * {@code already}. Constraint {@code n} of the class is constraint {@code n} of {@link #stated}, + * which starts again when it runs out. + */ + private static void declareUpTo( + final Ontology ontology, + final OntologyShapeFixture fixture, + final int notes, + final int already, + final int upTo) { + final List stated = stated(fixture, notes); + for (int first = already; first < upTo; first += CONSTRAINTS_OF_A_SHAPE) { + final OntologyShapeConstraint[] held = + IntStream.range(first, Math.min(first + CONSTRAINTS_OF_A_SHAPE, upTo)) + .mapToObj(constraint -> stated.get(constraint % stated.size())) + .toArray(OntologyShapeConstraint[]::new); + declare(ontology, fixture, "Shape" + first, "Order", held); + } } private static List sizes(final Reads reads) { @@ -212,62 +263,129 @@ private static List sizes(final Reads reads) { } @Test - void fortyConstraintsInFiveShapesAreReadInTheStatementsOfOneConstraint(final TestNamespace ns) { + void aDraftOfSixTablesIsReadInTheSameStatementsForOneFortyAndEightyConstraints( + final TestNamespace ns) { final Ontology ontology = createOntology(ns, "shapeReads"); - try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, SIX_TABLES)) { + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, orders("sixTables", 3))) { fixture.bindAll(); - declare(ontology, fixture, "Shape0", "Order", constraints(fixture, 1)); + declareUpTo(ontology, fixture, 3, 0, 1); final Reads one = reads(fixture, DRAFT); - for (int shape = 1; shape < 4; shape++) { - declare(ontology, fixture, "Shape" + shape, "Order", constraints(fixture, 10)); - } - declare(ontology, fixture, "Shape4", "Order", constraints(fixture, 9)); - + declareUpTo(ontology, fixture, 3, 1, 40); final Reads forty = reads(fixture, DRAFT); + declareUpTo(ontology, fixture, 3, 40, 80); + final Reads eighty = reads(fixture, DRAFT); assertEquals(List.of(1, 1, 3), sizes(one)); - assertEquals(List.of(5, 40, 6), sizes(forty)); + assertEquals(List.of(9, 40, 6), sizes(forty)); + assertEquals(List.of(17, 80, 6), sizes(eighty)); assertEquals( - List.of(DRAFT_STATEMENTS, DRAFT_STATEMENTS), - List.of(one.statements().size(), forty.statements().size()), - forty::listed); - assertEquals(1, forty.of(SHAPES), forty::listed); - assertEquals(1, forty.of(PROPERTIES), forty::listed); - assertEquals(2, forty.of(BINDING_ROWS), forty::listed); - assertEquals(0, forty.of(RELEASE_MEMBERS), forty::listed); + List.of(DRAFT_STATEMENTS, DRAFT_STATEMENTS, DRAFT_STATEMENTS), + List.of(one.statements().size(), forty.statements().size(), eighty.statements().size()), + eighty::listed); + assertDraftReads(one); + assertDraftReads(eighty); } } @Test - void aReleaseWithFortyConstraintsIsReadInTheStatementsOfAnyRelease(final TestNamespace ns) { - final Reads forty = released(ns, "fortyReleased", 5, 8); + void aDraftOfThreeTablesWithFortyConstraintsIsReadInTheStatementsOfAnyDraft( + final TestNamespace ns) { + final Reads three = drafted(ns, "threeTables", 0, 40); - assertEquals(List.of(5, 40, 6), sizes(forty)); - assertReleaseReads(forty); + assertEquals(List.of(8, 40, 3), sizes(three)); + assertEquals(DRAFT_STATEMENTS, three.statements().size(), three::listed); + assertDraftReads(three); } @Test - void aReleaseWithOneConstraintIsReadInTheStatementsOfAnyRelease(final TestNamespace ns) { - final Reads one = released(ns, "oneReleased", 1, 1); + void aDraftOfTwelveTablesWithFortyConstraintsIsReadInTheStatementsOfAnyDraft( + final TestNamespace ns) { + final Reads twelve = drafted(ns, "twelveTables", 9, 40); + + assertEquals(List.of(8, 40, 12), sizes(twelve)); + assertEquals(DRAFT_STATEMENTS, twelve.statements().size(), twelve::listed); + assertDraftReads(twelve); + } + + @Test + void aReleaseOfSixTablesWithOneConstraintIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads one = released(ns, "sixTables", 3, 1); assertEquals(List.of(1, 1, 3), sizes(one)); assertReleaseReads(one); } - /** The statements of a read of the active release of a class with this many shapes. */ + @Test + void aReleaseOfSixTablesWithFortyConstraintsIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads forty = released(ns, "sixTables", 3, 40); + + assertEquals(List.of(8, 40, 6), sizes(forty)); + assertReleaseReads(forty); + } + + @Test + void aReleaseOfSixTablesWithEightyConstraintsIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads eighty = released(ns, "sixTables", 3, 80); + + assertEquals(List.of(16, 80, 6), sizes(eighty)); + assertReleaseReads(eighty); + } + + @Test + void aReleaseOfThreeTablesWithFortyConstraintsIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads three = released(ns, "threeTables", 0, 40); + + assertEquals(List.of(8, 40, 3), sizes(three)); + assertReleaseReads(three); + } + + @Test + void aReleaseOfTwelveTablesWithFortyConstraintsIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads twelve = released(ns, "twelveTables", 9, 40); + + assertEquals(List.of(8, 40, 12), sizes(twelve)); + assertReleaseReads(twelve); + } + + /** The statements of a read of the draft of an order class with this many constraints. */ + private static Reads drafted( + final TestNamespace ns, final String name, final int notes, final int constraints) { + final Ontology ontology = createOntology(ns, name); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, orders(name, notes))) { + fixture.bindAll(); + declareUpTo(ontology, fixture, notes, 0, constraints); + return reads(fixture, DRAFT); + } + } + + /** The statements of a read of the active release of an order class with this many constraints. */ private static Reads released( - final TestNamespace ns, final String name, final int shapes, final int constraints) { + final TestNamespace ns, final String name, final int notes, final int constraints) { final Ontology ontology = createOntology(ns, name); - try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, SIX_TABLES)) { + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, orders(name, notes))) { fixture.bindAll(); - for (int shape = 0; shape < shapes; shape++) { - declare(ontology, fixture, "Shape" + shape, "Order", constraints(fixture, constraints)); - } + declareUpTo(ontology, fixture, notes, 0, constraints); activate(ns, ontology); return reads(fixture, RELEASE); } } + /** A draft reads the shapes and the properties twice: as rows, then for the right to view. */ + private static void assertDraftReads(final Reads reads) { + assertEquals(2, reads.of(SHAPES), reads::listed); + assertEquals(2, reads.of(PROPERTIES), reads::listed); + assertEquals(2, reads.of(BINDING_ROWS), reads::listed); + assertEquals(0, reads.of(RELEASE_MEMBERS), reads::listed); + } + private static void assertReleaseReads(final Reads reads) { assertEquals(RELEASE_STATEMENTS, reads.statements().size(), reads::listed); assertEquals(0, reads.of(SHAPES), reads::listed); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java index fa9e51824300..2d2a32756016 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java @@ -13,6 +13,7 @@ package org.openmetadata.service.ontology; +import java.net.URI; import java.util.List; import java.util.Set; import java.util.UUID; @@ -44,9 +45,10 @@ /** * Writes the answer a caller gets from what the shape check compile settled * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). The compile is the same for every - * caller. What a caller may not view is masked here, in one step after it: a constraint that rests + * caller. What a caller may not view is masked here, in one step after it. A constraint that rests * on a table the caller may not view answers {@code hidden} for each part it states, and says - * nothing else about it. + * nothing else about it. A constraint about a property the caller may not view answers the same, + * and does not name the property either. */ final class OntologyShapeCheckAnswer { /** The table test that runs a statement written for the check. */ @@ -69,25 +71,27 @@ final class OntologyShapeCheckAnswer { private static final String PATH_SEPARATOR = "\u001e"; private final OntologyShapeCheckFacts facts; - private final Set hidden; + private final Hidden hidden; - private OntologyShapeCheckAnswer(final OntologyShapeCheckFacts facts, final Set hidden) { + private OntologyShapeCheckAnswer(final OntologyShapeCheckFacts facts, final Hidden hidden) { this.facts = facts; this.hidden = hidden; } - /** The part of one constraint of one shape that a test checks. */ - private record Named(UUID shapeId, String constraintId, OntologyShapePart part) {} - /** - * The answer for each shape. + * What the caller may not view of what an answer rests on. * - * @param hidden the ids of the tables the caller may not view + * @param tables the ids of the tables that exist and that the caller may not view + * @param paths the IRIs of the properties of the constraints that the caller may not view */ + record Hidden(Set tables, Set paths) {} + + /** The part of one constraint of one shape that a test checks. */ + private record Named(UUID shapeId, String constraintId, OntologyShapePart part) {} + + /** The answer for each shape, with what the caller may not view masked. */ static List shapes( - final OntologyShapeCheckFacts facts, - final List shapes, - final Set hidden) { + final OntologyShapeCheckFacts facts, final List shapes, final Hidden hidden) { final OntologyShapeCheckAnswer answer = new OntologyShapeCheckAnswer(facts, hidden); return OntologyShapeCheckCompiler.compile(facts, shapes).stream().map(answer::shape).toList(); } @@ -106,10 +110,13 @@ private OntologyCheckedShape shape(final CompiledShape compiled) { private OntologyCheckedConstraint constraint(final UUID shapeId, final CompiledConstraint found) { final String id = found.constraint().getId(); - final boolean masked = found.rests().stream().anyMatch(hidden::contains); + final URI path = found.constraint().getPath(); + final boolean aboutHiddenProperty = hidden.paths().contains(path); + final boolean masked = + aboutHiddenProperty || found.rests().stream().anyMatch(hidden.tables()::contains); return new OntologyCheckedConstraint() .withId(id) - .withPath(found.constraint().getPath()) + .withPath(aboutHiddenProperty ? null : path) .withParts( masked ? masked(found.parts()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java index f98801b510ad..fc9d3d85a3e1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java @@ -39,11 +39,13 @@ import org.openmetadata.schema.type.OntologyColumnBinding; import org.openmetadata.schema.type.OntologyPropertyKind; import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; import org.openmetadata.service.ontology.OntologyBindingAccess.TableViews; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Target; @@ -55,6 +57,11 @@ * parts name, the binding rows between two reads of the binding revisions, and the tables those * rows name. * + *

      The caller's right to view is checked once for the shapes, once for the properties and once + * for the tables. A shape that the caller may not view is left out before anything is read for + * it. A property and a table are read whoever asks, because the compile is the same for every + * caller, and what the caller may not view of them is masked afterwards. + * *

      Two questions cost further reads, and only when a constraint asks them. A relation that the * class binds nowhere is looked for on its declared inverse. A class that a {@code class} part * names, and whose identity binding has a row filter, is checked for a subclass with an identity @@ -87,10 +94,9 @@ record Asked(UUID id, URI iri, UUID ontologyId, OntologyVersion version) {} /** * Everything one answer reads. * - * @param shapes the shapes that target the class, in name order - * @param hidden the ids of the tables that exist and that the caller may not view + * @param shapes the shapes that target the class and that the caller may view, in name order */ - record Read(List shapes, OntologyShapeCheckFacts facts, Set hidden) {} + record Read(List shapes, OntologyShapeCheckFacts facts, Hidden hidden) {} /** * The binding rows of one answer. @@ -112,7 +118,7 @@ private record Rows( private record Others(Map> inverseHolders, Set sharing) {} Read read(final Access access, final Asked asked) { - final List shapes = shapes(asked); + final List shapes = shapes(access, asked); final Map properties = byIri( asked @@ -141,15 +147,33 @@ Read read(final Access access, final Asked asked) { targets(classes, rows, others, tables), boundOnInverse(others, tables), rows.revisions()), - hidden(tables)); + new Hidden(hidden(tables), hiddenPaths(access, asked, properties))); } - private List shapes(final Asked asked) { - return asked.version().shapesTargeting(store, asked.ontologyId(), asked.iri()).stream() + private List shapes(final Access access, final Asked asked) { + final List targeting = + asked.version().shapesTargeting(store, asked.ontologyId(), asked.iri()); + final Set viewable = + asked.version().viewable(catalog, access, Entity.ONTOLOGY_SHAPE, targeting); + return targeting.stream() + .filter(shape -> viewable.contains(shape.getId())) .sorted(Comparator.comparing(OntologyShape::getName).thenComparing(OntologyShape::getId)) .toList(); } + /** The IRIs of the properties of the constraints that the caller may not view. */ + private Set hiddenPaths( + final Access access, final Asked asked, final Map properties) { + final Set viewable = + asked + .version() + .viewable(catalog, access, Entity.ONTOLOGY_PROPERTY, List.copyOf(properties.values())); + return properties.entrySet().stream() + .filter(property -> !viewable.contains(property.getValue().getId())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + } + /** The IRIs that the constraints of the shapes name in one of their fields. */ private static Set named( final List shapes, final Function field) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java index 826f52db5b5e..666934164dc0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -88,6 +88,18 @@ record Wanted( Map viewableProperties( OntologyBindingAccess catalog, Access access, Collection ids); + /** + * The ids of the definitions among {@code read} that the caller may view. They are definitions + * of one type, read from this version whoever asks. The working draft checks the live working + * rows. A release checks the definitions as released, so one whose working row is deleted + * since is still found. + */ + Set viewable( + OntologyBindingAccess catalog, + Access access, + String entityType, + List read); + /** * The id of the one class this version declares with one of {@code iris}, empty when it has * none. @@ -163,6 +175,16 @@ public Map viewableProperties( .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); } + @Override + public Set viewable( + final OntologyBindingAccess catalog, + final Access access, + final String entityType, + final List read) { + final List ids = read.stream().map(OntologyDefinition::getId).toList(); + return Set.copyOf(catalog.viewable(access, entityType, ids).keySet()); + } + @Override public Optional classNamed( final OntologyConceptBindingStore store, final UUID ontologyId, final List iris) { @@ -226,6 +248,17 @@ public OntologyStatementVersionRead read() { .withSemanticVersion(release.getSemanticVersion()); } + @Override + public Set viewable( + final OntologyBindingAccess catalog, + final Access access, + final String entityType, + final List read) { + return read.isEmpty() + ? Set.of() + : Set.copyOf(catalog.viewable(access, entityType, read).keySet()); + } + /** * A class is found by IRI through the working rows, deleted ones too, and kept only when the * release holds a member with that id and that IRI. A class deleted for good and made again diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java index 6337dc85fa8d..8b6ccc96a4f7 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java @@ -33,6 +33,7 @@ import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; /** * The answer as a caller reads it: one kind of entry for each outcome, every test as a request to @@ -77,11 +78,20 @@ private static List parts( .getParts(); } + /** The answer for a caller who may not view the tables {@code hidden} and may view the rest. */ private static List shapes( final OntologyShapeCheckModel model, final String type, final Set hidden, final OntologyShapeConstraint... constraints) { + return shapes(model, type, new Hidden(hidden, Set.of()), constraints); + } + + private static List shapes( + final OntologyShapeCheckModel model, + final String type, + final Hidden hidden, + final OntologyShapeConstraint... constraints) { return OntologyShapeCheckAnswer.shapes( model.facts(type), List.of(model.targeting(type, constraints)), hidden); } @@ -323,6 +333,42 @@ void aConstraintOnAHiddenIdentityTableSaysOnlyHiddenForEachPart() { .withMaxCount(1)))); } + @Test + void aConstraintAboutAHiddenPropertySaysOnlyHiddenForEachPartAndDoesNotNameTheProperty() { + final OntologyShapeCheckModel model = customers(); + final Hidden hidden = new Hidden(Set.of(), Set.of(UNFILTERED_IDENTITY.iri("customerEmail"))); + assertEquals( + "[{\"id\":\"c740db69-5948-3a3f-8958-af47e77417cb\",\"name\":\"shape\"," + + "\"severity\":\"Violation\",\"constraints\":[" + + "{\"id\":\"c1\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"in\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/unfilteredIdentity#customerName\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}]}]}]", + JsonUtils.pojoToJson( + shapes( + model, + "Customer", + hidden, + model.on("customerEmail").withMinCount(1).withIn(literals("a")), + model.on("customerName").withId("c2").withMinCount(0)))); + } + + @Test + void aHiddenPropertyOnAHiddenTableIsNotNamedEither() { + final OntologyShapeCheckModel model = customers(); + final Hidden hidden = + new Hidden( + Set.of(model.mapping().id("customers")), + Set.of(UNFILTERED_IDENTITY.iri("customerEmail"))); + assertEquals( + "[{\"id\":\"c1\",\"parts\":[{\"part\":\"maxCount\",\"outcome\":\"hidden\"}]}]", + JsonUtils.pojoToJson( + shapes(model, "Customer", hidden, model.on("customerEmail").withMaxCount(1)) + .getFirst() + .getConstraints())); + } + @Test void aHiddenTableThatHoldsOnePropertyHidesOnlyTheConstraintsOnThatProperty() { final OntologyShapeCheckModel model = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java index 32828c5e3394..8e71dc886039 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java @@ -15,9 +15,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import jakarta.ws.rs.ClientErrorException; @@ -32,26 +38,47 @@ import java.util.stream.IntStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyBindingAssetType; import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.jdbi3.OntologyReleaseDAO; import org.openmetadata.service.ontology.OntologyBindingAccess.TableViews; import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; import org.openmetadata.service.ontology.OntologyShapeCheckReader.Asked; import org.openmetadata.service.ontology.OntologyShapeCheckReader.Read; /** * What an answer is read from: the binding revision its rows were read under, the shapes that - * target the class, and the classes that get no answer because one read cannot hold all of theirs. + * target the class and that the caller may view, the properties the caller may not view, and the + * classes that get no answer because one read cannot hold all of theirs. */ class OntologyShapeCheckReaderTest { private static final UUID ORDER = UUID.fromString("00000000-0000-0000-0000-00000000000a"); + private static final UUID PERSON = UUID.fromString("00000000-0000-0000-0000-00000000000b"); private static final UUID ONTOLOGY = UUID.fromString("00000000-0000-0000-0000-0000000000f0"); + private static final UUID RELEASE = UUID.fromString("00000000-0000-0000-0000-0000000000e0"); private static final URI ORDER_IRI = URI.create("https://example.org/shop#Order"); + private static final URI PERSON_IRI = URI.create("https://example.org/shop#Person"); private static final URI PRODUCT_IRI = URI.create("https://example.org/shop#Product"); + private static final URI CHANNEL_IRI = URI.create("https://example.org/shop#orderChannel"); + private static final URI PLACED_BY_IRI = URI.create("https://example.org/shop#placedBy"); + private static final int MOST_SHAPES_OF_A_DRAFT = 1001; private static final Asked DRAFT_ORDER = new Asked(ORDER, ORDER_IRI, ONTOLOGY, new OntologyVersion.Draft(7L)); @@ -59,9 +86,9 @@ class OntologyShapeCheckReaderTest { private final OntologyBindingAccess catalog = mock(OntologyBindingAccess.class); private final OntologyShapeCheckReader reader = new OntologyShapeCheckReader(store, catalog); - /** Every table that is asked for exists, and the caller may view it. */ + /** Every table that is asked for exists, and the caller may view it and every definition. */ @BeforeEach - void everyTableExists() { + void everythingExistsAndIsViewable() { when(catalog.tableViews(any(), anyCollection())) .thenAnswer( call -> { @@ -71,6 +98,14 @@ void everyTableExists() { .collect(Collectors.toMap(id -> id, id -> new Table().withId(id))); return new TableViews(live, live.keySet()); }); + when(catalog.viewable(any(), anyString(), anyCollection())) + .thenAnswer( + call -> + call.>getArgument(2).stream() + .distinct() + .collect( + Collectors.>toMap( + id -> id, id -> new OntologyShape().withId(id)))); } @Test @@ -84,7 +119,7 @@ void anAnswerNamesTheRevisionItsRowsWereReadUnder() { assertEquals(Map.of(ORDER, 4L), read.facts().revisions()); assertEquals(List.of(orders, items), rows(read)); - assertEquals(Set.of(), read.hidden()); + assertEquals(new Hidden(Set.of(), Set.of()), read.hidden()); } @Test @@ -102,6 +137,31 @@ void aBindingWriteThatLandsWhileTheRowsAreReadMakesTheReaderReadThemAgain() { assertEquals(List.of(after), rows(read)); } + @Test + void aBindingWriteOfAClassThatAPartNamesMakesTheReaderReadTheRowsAgain() { + final BindingRow orders = row(1, OntologyBindingRole.IDENTITY); + final BindingRow before = row(PERSON, 2, OntologyBindingRole.IDENTITY); + final BindingRow after = row(PERSON, 3, OntologyBindingRole.IDENTITY); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn(List.of(shape(1, "a", ORDER_IRI, on(PLACED_BY_IRI).withClassIri(PERSON_IRI)))); + when(store.liveConcepts(ONTOLOGY, Set.of(PERSON_IRI))) + .thenReturn(List.of(new OntologyConcept().withId(PERSON).withIri(PERSON_IRI))); + when(store.revisions(anyCollection())) + .thenReturn( + Map.of(ORDER, 4L, PERSON, 7L), + Map.of(ORDER, 4L, PERSON, 8L), + Map.of(ORDER, 4L, PERSON, 8L)); + when(store.identityFirstTables(List.of(ORDER), 101)).thenReturn(List.of(orders)); + when(store.identityRows(List.of(PERSON))).thenReturn(List.of(before), List.of(after)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(Map.of(ORDER, 4L, PERSON, 8L), read.facts().revisions()); + assertEquals(after, read.facts().targets().get(PERSON_IRI).identity().row()); + verify(store, times(2)).identityFirstTables(List.of(ORDER), 101); + verify(store, times(2)).identityRows(List.of(PERSON)); + } + @Test void bindingsThatChangeOnEveryReadGiveNoAnswer() { when(store.revisions(anyCollection())) @@ -158,6 +218,113 @@ void theShapesOfAnAnswerAreTheOnesThatTargetTheClassInNameOrder() { assertEquals(List.of(first, second), reader.read(null, DRAFT_ORDER).shapes()); } + @Test + void aShapeTheCallerMayNotViewIsLeftOutAndNothingIsReadForIt() { + final OntologyShape viewable = shape(1, "b", ORDER_IRI, on(CHANNEL_IRI).withMinCount(1)); + final OntologyShape denied = + shape(2, "a", ORDER_IRI, on(PLACED_BY_IRI).withClassIri(PERSON_IRI)); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn(List.of(denied, viewable)); + when(catalog.viewable(null, Entity.ONTOLOGY_SHAPE, List.of(denied.getId(), viewable.getId()))) + .thenReturn(Map.of(viewable.getId(), viewable)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(List.of(viewable), read.shapes()); + verify(store).liveProperties(ONTOLOGY, Set.of(CHANNEL_IRI)); + verify(store).liveConcepts(ONTOLOGY, Set.of()); + } + + @Test + void aPropertyTheCallerMayNotViewIsReadForTheCompileAndNamedAsHidden() { + final OntologyProperty channel = property(1, CHANNEL_IRI); + final OntologyProperty placedBy = property(2, PLACED_BY_IRI); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn( + List.of( + shape( + 1, + "a", + ORDER_IRI, + on(CHANNEL_IRI).withMinCount(1), + on(PLACED_BY_IRI).withMinCount(1)))); + when(store.liveProperties(ONTOLOGY, Set.of(CHANNEL_IRI, PLACED_BY_IRI))) + .thenReturn(List.of(channel, placedBy)); + when(catalog.viewable( + null, Entity.ONTOLOGY_PROPERTY, List.of(channel.getId(), placedBy.getId()))) + .thenReturn(Map.of(channel.getId(), channel)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(new Hidden(Set.of(), Set.of(PLACED_BY_IRI)), read.hidden()); + assertEquals(Map.of(CHANNEL_IRI, channel, PLACED_BY_IRI, placedBy), read.facts().properties()); + } + + @Test + void theShapesOfAReleaseAreReadFromEveryPageOfItsMembers() { + final List members = new ArrayList<>(); + IntStream.rangeClosed(1, OntologyVersion.SHAPE_MEMBERS_READ) + .forEach(shape -> members.add(released(shape, PRODUCT_IRI))); + final OntologyShape onTheFirstPage = released(7, ORDER_IRI); + members.set(6, onTheFirstPage); + final OntologyShape onTheSecondPage = + released(OntologyVersion.SHAPE_MEMBERS_READ + 2, ORDER_IRI); + members.add(released(OntologyVersion.SHAPE_MEMBERS_READ + 1, PRODUCT_IRI)); + members.add(onTheSecondPage); + final OntologyVersion release = release(members); + + assertEquals( + List.of(onTheFirstPage.getId(), onTheSecondPage.getId()), + release.shapesTargeting(store, ONTOLOGY, ORDER_IRI).stream() + .map(OntologyShape::getId) + .toList()); + } + + /** A sealed release whose shape members are {@code shapes}, listed a page at a time by id. */ + private static OntologyVersion release(final List shapes) { + final OntologyReleaseDAO releases = mock(OntologyReleaseDAO.class); + final CollectionDAO dao = mock(CollectionDAO.class); + when(dao.ontologyReleaseDAO()).thenReturn(releases); + final List members = + shapes.stream() + .map( + shape -> + new OntologyReleaseMember() + .withReleaseId(RELEASE) + .withMemberKind(MemberKind.SHAPE) + .withMemberId(shape.getId()) + .withPayload(JsonUtils.valueToTree(shape))) + .toList(); + final int[] listed = {0}; + when(releases.listMembers(eq(RELEASE), eq(MemberKind.SHAPE.value()), anyString(), anyInt())) + .thenAnswer( + call -> { + // A cursor that never moves would list the first page for ever. + assertTrue(++listed[0] <= members.size(), "the cursor does not move"); + final String after = call.getArgument(2); + return members.stream() + .filter(member -> member.getMemberId().toString().compareTo(after) > 0) + .limit(call.getArgument(3)) + .toList(); + }); + return new OntologyVersion.Release( + dao, + new OntologyRelease() + .withId(RELEASE) + .withEncodingVersion(OntologyRelease.EncodingVersion.ONTOLOGY_RELEASE_V_1) + .withOntology(new EntityReference().withId(ONTOLOGY)), + "shop"); + } + + /** A shape as a release holds it, with an id that sorts in the order of {@code number}. */ + private static OntologyShape released(final int number, final URI target) { + return new OntologyShape() + .withId(new UUID(2, number)) + .withName("s" + number) + .withTargetConcept(target) + .withOntology(new EntityReference().withId(ONTOLOGY)); + } + private static void assertRefused(final String message, final Runnable read) { final ClientErrorException refused = assertThrows(ClientErrorException.class, read::run); @@ -171,8 +338,12 @@ private static List rows(final Read read) { } private static BindingRow row(final int table, final OntologyBindingRole role) { + return row(ORDER, table, role); + } + + private static BindingRow row(final UUID type, final int table, final OntologyBindingRole role) { return new BindingRow( - ORDER, + type, new UUID(0, table), OntologyBindingAssetType.TABLE, "hash" + table, @@ -182,7 +353,26 @@ private static BindingRow row(final int table, final OntologyBindingRole role) { null); } - private static OntologyShape shape(final int id, final String name, final URI target) { - return new OntologyShape().withId(new UUID(1, id)).withName(name).withTargetConcept(target); + private static OntologyShape shape( + final int id, + final String name, + final URI target, + final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(new UUID(1, id)) + .withName(name) + .withTargetConcept(target) + .withConstraints(List.of(constraints)); + } + + private static OntologyShapeConstraint on(final URI path) { + return new OntologyShapeConstraint().withId(path.getFragment()).withPath(path); + } + + private static OntologyProperty property(final int id, final URI iri) { + return new OntologyProperty() + .withId(new UUID(3, id)) + .withIri(iri) + .withKind(OntologyPropertyKind.DATA); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java index 84ee604fb982..3e8c96986d9f 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java @@ -36,6 +36,7 @@ import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; import org.openmetadata.schema.api.data.OntologyShapeCheckReason; import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; /** * Sends each key value case of {@code ontology/sql-value-cases.json} that is for one text column @@ -91,7 +92,7 @@ private static OntologyCheckedPart listed(final Run run) { List.of( model.targeting( "Customer", model.on("customerEmail").withIn(literals(run.input())))), - Set.of()) + new Hidden(Set.of(), Set.of())) .getFirst() .getConstraints() .getFirst() From 5e17d5d72ef526ee284edd97891c9c8223806103 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 13:02:27 -0800 Subject: [PATCH 085/203] Refuse a range in a pattern that ends outside ASCII MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A range such as [a-é] passed, because only its first character was checked. The engine run that showed how Postgres reads a range covered ASCII ranges only, so the pattern grammar now takes no other. --- .../service/ontology/OntologyPortablePattern.java | 5 ++++- .../service/ontology/OntologyPortablePatternTest.java | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java index 75db3efa8a62..499b08c3c154 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java @@ -150,7 +150,10 @@ private boolean member() { } final char high = at + 1 < body.length() ? body.charAt(at + 1) : ' '; at += 2; - return low <= high && Character.getType(low) == Character.getType(high) && low != ' '; + return isPlain(high) + && low <= high + && Character.getType(low) == Character.getType(high) + && low != ' '; } private boolean group() { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java index 5bceedb14360..fab7ab7863a0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java @@ -98,6 +98,8 @@ void writesAWildcardAsEveryCharacterButALineBreak(final String pattern, final St "^[z-a]$", "^[a-Z]$", "^[a-]$", + "^[a-é]$", + "^[0-٣]$", "^[\\d]$", "^[a\\-z]$", "^[.]$", From edd8f084bf13a13af74abfe3579cca4038b10712 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 13:02:30 -0800 Subject: [PATCH 086/203] Record that every shape check is a generated query Rewrite the rule table and its reasons: why no column test is offered, that a declared key is trusted and what that costs, where a pattern is checked and how it is written for Postgres, and which column types hold a datatype on which engine family, each with the reason no stored value breaks it. Say how a shape or a property that the caller may not view is left out or hidden, and give the new statement counts. Amend the record on typed values: statement text takes the tilde. --- ...-keeps-typed-values-apart-from-its-text.md | 8 +- ...ape-check-is-exact-or-it-is-not-offered.md | 325 ++++++++++++------ 2 files changed, 226 insertions(+), 107 deletions(-) diff --git a/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md b/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md index 889101c118c7..b4cd4b21e0cc 100644 --- a/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md +++ b/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md @@ -1,7 +1,7 @@ # Generated SQL keeps typed values apart from its text - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (finished text comes in a form to read and a form to run) +- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (finished text comes in a form to read and a form to run) · v3 2026-11-24 (statement text takes the tilde) - **Deciders:** Ontology Studio maintainers - **Guard:** `OntologySqlValueCasesTest`, `SqlEngineFamilyTest`, `TypedValuesTest`, `TypedStatementTest`, `OntologyConceptSqlGeneratorTest`, `OntologySqlLiteralIT`, `OntologyRowFilterValueIT`, `OntologyConceptQueryIT` - **Related:** ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension (two of its rules @@ -150,3 +150,9 @@ that passed `sql` to a reader of `:name` parameters must pass `escapedSql` inste sends a statement straight to a driver sends `sql`, which answers the last consequence above. The statements that return both forms are in ADR:2026-11-22-record-statements-start-from-the-identity-table. + +v3 (2026-11-24): statement text also takes `~`, the operator that matches a regular expression. +Where this record lists the characters of statement text, add `~`. A tilde opens no string, quoted +name, parameter, or comment, so the rule that text can put no value into a statement still holds. +The pattern that the operator matches is a typed value like any other. The one statement that uses +the operator is in ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered. diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index d08bfae64be5..6ac536a091f6 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -1,9 +1,9 @@ # A shape check is exact or it is not offered - **Status:** Accepted -- **Revisions:** v1 2026-11-23 (initial) +- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckReadsIT` (the reads) +- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads) - **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) ## Context @@ -17,6 +17,10 @@ key, a key column can hold a null, and a value can sit in a second table. A test then reports a violation that no record has, or misses one that a record has. A person who reads the result cannot tell which of the two happened, so a test of that kind is worse than no test. +A built-in column test does not read the whole table either. The test runner builds the data of +such a test from the profile sample of the table, and the server that offers the test does not +read how that sample is set. + ## Decision **The server says how each constraint of a class's shapes is checked, and creates nothing.** @@ -27,14 +31,15 @@ one of five outcomes. | Outcome | Meaning | |---|---| -| `check` | A test finds a violation exactly when a record breaks the part. One check for each table. | +| `check` | A test counts the records that break the part. One check for each table that holds the property. | | `heldByMapping` | No record can break the part, because of how the class is mapped. | | `notMapped` | The class binds the property in no column, or the version has no such property. | | `notEnforceable` | No exact test exists. A `reason` from a closed list says why. | -| `hidden` | The caller may not view a table that the answer rests on. | +| `hidden` | The caller may not view a table that the answer rests on, or the property the constraint is about. | -**A check is exact.** Its number is 0 exactly when every record satisfies the part. Where no such -test exists the part is `notEnforceable`. The server never offers a test that is close. +**A check is exact.** Its number is the number of records that break the part, so it is 0 exactly +when every record satisfies the part. Where no such test exists the part is `notEnforceable`. The +server never offers a test that is close. **What is checked.** @@ -52,79 +57,154 @@ test exists the part is `notEnforceable`. The server never offers a test that is text without regard to case counts `a` and `A` as one value, and finds `A` in a list that holds `a`. The check and the source agree, which is what a person who reads the table expects. +**Every check is a generated query.** A check is a `tableCustomSQLQuery` test whose statement the +server writes. The built-in column tests `columnValuesToBeNotNull`, `columnValuesToBeInSet`, +`columnValuesToBeBetween` and `columnValuesToMatchRegex` are not offered, for two reasons. + +- A column test counts rows. A row that the filter drops is no record, and a column test still + reads it. Two rows with one key are one record: when one row holds a null and the other a value, + the record has a value and a test for nulls fails. A value in a contributing table belongs to a + record only when its key matches one, and a column test cannot ask. +- A column test reads a sample. The test runner builds the data of a built-in test from the profile + sample of the table (`create_data_quality_interface` in + `ingestion/src/metadata/data_quality/runner/base_test_suite_source.py`). A sample that is set on + the table, its schema or its database comes before the sample of the pipeline, and the partition + and the sample query of the table apply too. The compile does not read those settings, and no + binding revision moves when one of them changes. A column test that is exact today can therefore + stop being exact while the shape and the mapping stay as they are. + +A `tableCustomSQLQuery` test runs its statement on the session as it is written and never reads the +sample. The statement starts from the records, so it is exact on every table of the class, and it +returns 0 for an empty table. + **A table is simple for the class** when it is the identity table of the class, the binding has no row filter, and the columns of its declared primary key are exactly the subject key. On a simple -table each row is one record and each record is one row. A primary key is declared by a -`PRIMARY_KEY` table constraint, or by the column constraint `PRIMARY_KEY` when exactly one column -carries it. The declaration in the catalog is taken at its word. - -**The rule.** "Generated" is a `tableCustomSQLQuery` test whose query the server writes. - -| Part | On a simple table | Anywhere else | -|---|---|---| -| `minCount 0` | `heldByMapping` | `heldByMapping` | -| `minCount 1`, a property bound to a subject key column of the identity table | `heldByMapping` | `heldByMapping` | -| `minCount 1`, one column | `columnValuesToBeNotNull` | generated: records with no value | -| `minCount 1`, a relation of several columns | generated | generated | -| `minCount n`, n above 1 | generated | generated: records with fewer than n distinct values | -| `maxCount n`, n at least 1, a value on a simple table, or on a table where a declared primary or unique key lies inside the subject key columns | `heldByMapping` | `heldByMapping` | -| `maxCount n` otherwise, `maxCount 0` included | generated | generated: records with more than n distinct values | -| `in`, literals | `columnValuesToBeInSet` with `matchEnum` `true`, for a text or whole-number column with the column constraint `NOT_NULL` or `PRIMARY_KEY` | generated: values outside the list | -| `range` | `columnValuesToBeBetween`, for a numeric column and bounds that a double holds exactly | generated: values outside the bounds | -| `pattern` | `columnValuesToMatchRegex`, for a portable pattern | `notEnforceable` | -| `class` | generated: values with no record of that class | the same | -| `datatype` | `heldByMapping` when every value of the column's type is a value of the datatype, else `notEnforceable` | the same | - -**A column test needs a simple table, because it counts rows.** A row that the filter drops is no -record, and a column test still reads it. Two rows with one key are one record: when one holds a -null and the other a value, the record has a value and `columnValuesToBeNotNull` fails. A value in -a contributing table belongs to a record only when its key matches one, and a column test cannot -ask. A generated query starts from the records, so it is exact on every table. - -**`columnValuesToBeInSet` runs with `matchEnum`.** Without it the test passes as soon as one listed -value occurs in the column, whatever the other rows hold. With it the test counts the rows whose -value is not listed. It counts a null as not listed, and a null is no value, so the column must be -declared `NOT_NULL` or `PRIMARY_KEY`. The test reads a list of text or of whole numbers, so other -column types get the generated query. - -**`columnValuesToBeBetween` reads its bounds as doubles.** A bound that no double holds exactly -would move, so such a range gets the generated query. So does a range on a date, a time or a -timestamp column. A range on a column whose values have no order the server knows is -`notEnforceable`. - -**A generated test counts in the source.** It runs with the strategy `COUNT`, the operator `<=` and -the threshold `0`, so the query returns one number and the test passes exactly when the number is -0. The strategy `ROWS` would bring one row for each violation to the runner. The count query has no -`ORDER BY` and no row limit. A second query, `inspectionQuery`, lists the keys of the records in -violation for a person to read. It has no order and no row limit either, so a person who runs it on -a large table adds a limit. Every column in both is qualified with its table alias, every table is -in one database, and no label, comment or name of an ontology term reaches the text. A value -reaches the text only as a typed value +table each row is one record and each record is one row. A simple table matters only for +`maxCount`, where it is one of the tables that the next rule covers. + +**A declared key is trusted.** A declared primary or unique key whose columns all lie inside the +subject key columns of a table says that the table holds at most one row for each key. A record +then has at most one value there, so `maxCount n` is `heldByMapping` for n of at least 1. A key +with a column outside the subject key says nothing, because two rows can share the subject key and +differ there. A primary key is declared by a `PRIMARY_KEY` table constraint, or by the column +constraint `PRIMARY_KEY` when exactly one column carries it. A unique key is declared by a `UNIQUE` +table constraint or by the column constraint `UNIQUE`. The declaration in the catalog is taken at +its word on every engine, whether the database or a person declared it, and whether or not the +engine enforces it. + +**The rule.** "Generated" is a check whose statement counts the records that the row names. + +| Part | Answer | +|---|---| +| `minCount 0` | `heldByMapping` | +| `minCount 1`, a property whose value columns are all subject key columns of the identity table | `heldByMapping` | +| `minCount 1`, one column | generated: records with no value | +| `minCount 1`, a relation of several columns | generated: records with no value, where a value has every column of the join non-null | +| `minCount n`, n above 1 | generated: records with fewer than n distinct values | +| `maxCount n`, n at least 1, a value on a simple table, or on any table where a declared primary or unique key lies inside the subject key columns | `heldByMapping` | +| `maxCount n` otherwise, `maxCount 0` included | generated: records with more than n distinct values | +| `in`, literals | generated: records with a value outside the list | +| `range` | generated: records with a value outside the bounds | +| `pattern` | generated on the `Postgres` service type: records with a value that the pattern does not match. `notEnforceable` with `engineNotSupported` on every other service type | +| `class` | generated: records with a value that is no record of that class | +| `datatype` | `heldByMapping` when every value that the engine stores in the column's type is a value of the datatype, else `notEnforceable` with `datatypeMismatch` | + +A null is no value, so it breaks none of `in`, `range`, `pattern` and `datatype`. A generated check +needs a service type that statements are written for, every table of its statement in one database, +and every column that it names still in its table. `minCount` on a contributing table and `class` +keep the records with no matching row. The `CLICKHOUSE` family gets no such statement, because an +unmatched row there holds a default value and no null. + +A literal is parsed by the type of the column it is compared with, and the datatype of the literal +is not read. A range needs a column whose values have an order the server knows: a whole number, a +decimal, a date, a time or a timestamp. A list needs a column type that takes a value. + +**A check counts in the source.** It runs with the strategy `COUNT`, the operator `<=` and the +threshold `0`, so the statement returns one number and the test passes exactly when the number is +0. The strategy `ROWS` would bring one row for each violation to the runner. The count statement +has no `ORDER BY` and no row limit. A second statement, `inspectionQuery`, lists the keys of the +records in violation for a person to read, and every check carries one. It has no order and no row +limit either, so a person who runs it on a large table adds a limit. Every column in both is +qualified with its table alias, every table is in one database, and no label, comment or name of an +ontology term reaches the text. A value reaches the text only as a typed value (ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). -**A pattern is checked only when every engine reads it alike.** The regex test is the only way to -check a pattern, so the column is a text column of a simple table. The pattern starts with `^` and -ends with an unescaped `$`. Between them it holds only letters, digits and spaces, escaped -punctuation, `.`, character classes of plain characters and ranges, negated or not, groups with no -prefix, alternation inside a group, and the quantifiers `?`, `*`, `+`, `{n}`, `{n,}` and `{n,m}`. -An alternation outside a group is refused, because `^a|b$` means something else on an engine that -anchors a pattern by itself. A back reference, a look-around, a lazy or possessive quantifier, a -class such as `\d`, an anchor in the middle and a flag are refused. On the `MYSQL` family a pattern -with a letter is refused too, because a match there ignores case under most collations. The `TSQL` -family has no such operator. A refused pattern is `notEnforceable`. +**A pattern is checked on Postgres, the way XPath reads it.** SHACL reads `pattern` as the +`matches` function of XPath does with no flag. Postgres is the one engine that was run against +every construct a pattern may hold, so a pattern gets a check on the `Postgres` service type only. +Every other service type answers `engineNotSupported`, Timescale included, until an engine run +shows that it reads each construct the same way. + +- The column is a text column of any table of the class. A `CHAR` column is refused, because the + engine pads its values with spaces and nothing says whether the pattern is asked of the padding. +- The pattern starts with `^` and ends with an unescaped `$`. Between them it holds only ASCII + letters, digits and spaces, a backslash before an ASCII punctuation character, `.`, character + classes, groups with no prefix, alternation inside a group, and the quantifiers `?`, `*`, `+`, + `{n}`, `{n,}` and `{n,m}` with counts up to 255. A character class holds ASCII letters, digits, + spaces and ranges of two digits or of two letters of one case, and may be negated. +- An alternation outside a group is refused, because `^a|b$` means something else on an engine that + anchors a pattern by itself. A back reference, a look-around, a lazy or possessive quantifier, a + class such as `\d`, an anchor in the middle and a flag are refused. A refused pattern is + `patternNotPortable`. +- Postgres reads one construct of that core in another way. Its `.` matches a line feed and a + carriage return, and the `.` of XPath matches neither. The statement therefore holds + `[^\n\r]` in place of each `.`. Refusing every pattern with a `.` was the other choice, and it + would leave every pattern that uses a wildcard without a check. +- The statement is `NOT (CAST( AS text) COLLATE "C" ~ )`, with the pattern as a + typed text value. Under the collation `C` a range in a class goes by code point whatever the + collation of the column or of the database, which is how XPath reads a range. The cast makes one + rule for every text type: a `citext` column would fold case, an enumerated type has no match + operator, and a nondeterministic collation refuses a regular expression. +- `$` matches at the very end only, so a value that ends with a line break does not match + `^[0-9]+$`. **`class` reads the confirmed join of a relation.** The class of the constraint must have its -identity table where the join arrives. The query counts the values that match no record of that -class, so it carries the row filter of that binding and its non-null key. When a subclass of that -class has its identity table on the same table and the binding of the class has a row filter, the -filter may leave out records of the subclass, and the part is `notEnforceable`. The subclass steps -are the named ones of the version that is read, so a release answers as it was sealed. - -**`datatype` is settled by the column's type.** It supports `xsd:string`, `xsd:boolean`, -`xsd:integer`, `xsd:decimal`, `xsd:double`, `xsd:float`, `xsd:date`, `xsd:time` and -`xsd:dateTime`. A fixed-point column with a scale of 0 holds integers, and a whole-number column -holds decimals. When every value of the column's type is a value of the datatype the part is -`heldByMapping`. Otherwise no query can tell, and the part is `notEnforceable`. +identity table where the join arrives. The query counts the records with a value that matches no +record of that class, so it carries the row filter of that binding and its non-null key. When a +subclass of that class has its identity table on the same table and the binding of the class has a +row filter, the filter may leave out records of the subclass, and the part is `notEnforceable`. The +subclass steps are the named ones of the version that is read, so a release answers as it was +sealed. + +**`datatype` is settled by the column's type on the engine that stores it.** It reads `xsd:string`, +`xsd:boolean`, `xsd:integer`, `xsd:decimal`, `xsd:double`, `xsd:float`, `xsd:date`, `xsd:time` and +`xsd:dateTime`. A part is `heldByMapping` only where every value that the engine stores in a column +of that type is a value of the datatype. The catalog gives one name to types that differ between +engines, so the table is by engine family +(ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). A column of a service type +with no family is held for nothing. + +| Datatype | Column type | Engine families | Why no stored value breaks it | +|---|---|---|---| +| `xsd:boolean` | `BOOLEAN` | all but `MYSQL` and `TSQL` | The type stores true and false only. | +| `xsd:integer` | `TINYINT`, `BYTEINT`, `SMALLINT`, `BIGINT`, `LARGEINT` | all | Every source type that gets one of these names is a whole-number type. | +| `xsd:integer` | `INT` | all but `SPARK` | The same. | +| `xsd:integer` | `DECIMAL` or `NUMERIC` with a scale of 0 | all but `POSTGRES` | A fixed-point value with no fraction digit is a whole number, and the type stores no `NaN` on these engines. | +| `xsd:decimal` | the six whole-number types | all | A whole number is a decimal. On `SPARK` a column named `INT` can be a `decimal` column, whose values are decimals too. | +| `xsd:decimal` | `DECIMAL`, `NUMERIC` | all but `POSTGRES` | A fixed-point value is a decimal, and the type stores no `NaN` and no infinity on these engines. | +| `xsd:double` | `FLOAT` | all | Every source type that gets the name is a binary floating-point type of 32 or 64 bits. Each of its values is a 64-bit value, and `xsd:double` has `NaN` and both infinities. | +| `xsd:date` | `DATE` | `BIGQUERY`, `TSQL` | The type stores calendar days from year 1 to year 9999 and nothing else. | +| `xsd:time` | `TIME` | `BIGQUERY`, `TSQL` | The type stores a time of day below 24 hours and nothing else. | +| `xsd:dateTime` | `DATETIME` | `BIGQUERY`, `TSQL` | Every source type that gets the name stores a calendar day from year 1 to year 9999 with a time of day. | +| `xsd:dateTime` | `TIMESTAMP` | `BIGQUERY` | The same. | + +Every other pair is `datatypeMismatch`, and each is left out for a value that the type stores. + +- `xsd:float` is held nowhere. A `FLOAT` column has 64 bits on SQL Server and on Snowflake, and a + 64-bit value need not be a 32-bit value. +- `xsd:double` is not held on `DOUBLE`, because a decimal floating-point type gets that name too. +- `xsd:string` is held nowhere. Every text type stores the control characters below U+0020, and an + XML string holds none of them but the tab, the line feed and the carriage return. +- On the `MYSQL` family a `BOOLEAN` column can be a `TINYINT(1)`, which stores -128 to 127. The + date types of that family store the zero date `0000-00-00`, and its `TIME` stores `25:00:00` and + `-01:00:00`. The `TSQL` family has no type that gets the name `BOOLEAN`. +- On the `POSTGRES` family a fixed-point column stores `NaN`, and a date or a timestamp stores + `infinity`. +- On the `SPARK` family the Databricks source reads a `decimal` column as a type that the catalog + names `INT`. +- A `TIMESTAMP` column of the `TSQL` family is a row version. +- The date and time types of the other families are held for nothing until someone reads what + their engines store. **What is not enforceable, and why.** @@ -140,18 +220,15 @@ holds decimals. When every value of the column's type is a value of the datatype | `valuesAreRecords` | An `in` list names a record by IRI. | | `valueDoesNotFitColumn` | A literal does not parse as a value of the column's type, or carries a language tag. A stored row filter that no longer parses gives the same reason. | | `tooManyValues` | An `in` list of more than 1,000 values. | -| `columnTypeNotSupported` | The column's type has no values the part can be compared with. | -| `datatypeNotSupported`, `datatypeMismatch` | The datatype is not one of the nine, or the column's type can hold a value that the datatype does not have. | -| `patternNotPortable`, `tableNotSimple` | The pattern is outside the common core, or its column is not on a simple table. | +| `columnTypeNotSupported` | The column's type has no values the part can be compared with: a range on a type with no order, a list on a type that takes no value, or a pattern on a column that is not text or is `CHAR`. | +| `datatypeNotSupported`, `datatypeMismatch` | The datatype is not one of the nine, or the engine can store a value in the column's type that the datatype does not have. | +| `patternNotPortable` | The pattern is outside the common core, or it is longer than a statement takes once it is written. | | `columnMissing` | A bound column, a key column or a join column left the table. | | `otherDatabase` | A table of the check is in another database than the identity table. | -| `engineNotSupported` | A generated query on a service type that no statement is written for, a pattern on the `TSQL` family, or a query on the `CLICKHOUSE` family that keeps the records with no matching row, because an unmatched row there holds a default value and no null. | +| `engineNotSupported` | A statement on a service type that none is written for, a pattern on any service type but `Postgres`, or a statement on the `CLICKHOUSE` family that keeps the records with no matching row. | -A literal is parsed by the type of the column it is compared with, and the datatype of the literal -is not read. A property bound in several tables is checked once for each table for `in`, `range`, -`class`, `datatype` and `pattern`. When the tables do not agree, each answer is its own part entry. -A column test needs no statement, so it is offered on a service type that no statement is written -for. +A property bound in several tables is checked once for each table for `in`, `range`, `class`, +`datatype` and `pattern`. When the tables do not agree, each answer is its own part entry. **A check has an identity that survives an edit of its bound.** It is the lowercase hex SHA-256 of the shape id, the constraint id, the part, the class id, the table id and the column path, joined @@ -168,38 +245,74 @@ binds the filtered table later changes the answer, and a caller sees it when it **Each kind of input is read once.** After the class and the version, one request reads the shapes that target the class, the properties their constraints name, the classes their `class` parts -name, the binding rows, and the tables those rows name. The number of statements does not grow -with the number of shapes or of constraints. For a class with 5 shapes, 40 constraints and 6 -tables, an administrator's request runs 36 `SELECT` statements from the draft and 44 from a -release, as many as for one shape with one constraint. Of these, 23 read the tables with what the -check of the right to view them needs. A server setting whose cached value has lapsed is read on -top of them. Two questions cost further reads, and only when a constraint asks them: the declared -inverse of a relation that the class binds nowhere, and a subclass on a filtered identity table -that a `class` part arrives at. +name, the binding rows, and the tables those rows name. It checks the caller's right to view once +for the shapes, once for the properties and once for the tables. The number of statements does not +grow with the number of shapes, of constraints or of tables. An administrator's request runs 46 +`SELECT` statements from the draft and 52 from a release. `OntologyShapeCheckReadsIT` counts those +two numbers for 1, 40 and 80 constraints on a class of 6 tables, and for 40 constraints on a class +of 3 tables and of 12. Of these, 23 read the tables with what the check of the right to view them +needs. The two checks of the shapes and the properties take 10 in a draft and 8 in a release. A +server setting whose cached value has lapsed is read on top of them. Two questions cost further +reads, and only when a constraint asks them: the declared inverse of a relation that the class +binds nowhere, and a subclass on a filtered identity table that a `class` part arrives at. **An answer is whole or it is refused.** A class that binds more than 100 tables, and a draft class that more than 1,000 shapes name, get 409. An answer built from a part of them would leave a constraint unchecked or a count short. -**What a caller may not view is masked after the compile.** The compile is the same for every -caller. A constraint whose answer rests on a table the caller may not view, which is the identity -table, a table that binds the property in whatever role, or the table a join arrives at, has every -part `hidden`, with no check, no reason and no column. A hidden constraint has one entry for each -part, so it does not tell how many tables answered. No table name appears anywhere else in the -response. +**What a caller may not view is left out or masked.** A shape that the caller may not view is not +in the answer, and nothing is read for it. The compile of the other shapes is the same for every +caller, and one step after it masks the rest. A constraint about a property the caller may not view +keeps its id, has no `path`, and has every part `hidden`. A constraint whose answer rests on a +table the caller may not view has every part `hidden` too, with no check, no reason and no column. +Such a table is the identity table, a table that binds the property in whatever role, or the table +a join arrives at. A hidden constraint has one entry for each part, so it does not tell how many +tables answered. No name, id or IRI of such a shape, property or table appears anywhere in the +response. A draft asks about the working rows. A release asks about the definitions as it holds +them, so a shape whose working row was deleted after the release still answers. ## Consequences A person is shown a test only when its result means what the shape says. Everything else comes with a reason that names what to change: declare the key, confirm the join, pick an identity table. -A catalog whose declared primary key is wrong gives a column test that is not exact, because the -declaration is taken at its word. A generated query does not depend on it. - -A pattern outside the common core, a pattern on a table that is not simple, and a count over a -property bound in several places have no check. Each needs its own exact form before it can be -offered, and a new record when it gets one. - -The answer is computed for each request from the shapes and the bindings as they are. Nothing is -stored, so a check has no state here. Creating tests from this answer is a separate step that keys -on the identity of a check and compares the binding revisions it read. +Every check is one kind of test, and its result is read one way. Each check costs one statement on +the source for each run. + +A declared key can be wrong where the engine does not enforce it. Several engines accept a primary +key and do not enforce it, BigQuery, Snowflake, Redshift and Databricks among them, and a person +can declare a key in the catalog on any table. Where two rows share such a key, a record can have +two values. The answer for `maxCount` is `heldByMapping` all the same, and no test is written that +would find those rows. That is the cost of taking a declaration at its word. + +A pattern has a check on Postgres only. A pattern on another engine, a pattern outside the common +core, and a count over a property bound in several places have none. Each needs its own exact form +before it can be offered, and a new record when it gets one. A Postgres database whose encoding is +`SQL_ASCII` counts bytes where XPath counts characters, and the server cannot see the encoding of a +database. A pattern check there can differ on a value that holds a character outside ASCII. + +A `datatype` part is `heldByMapping` on fewer columns than a reader may expect: `xsd:string` on +none, and a date on two engine families. The table gains a line when someone reads what an engine +stores in a type. + +The answer is computed for each request from the shapes, the bindings and the catalog as they are. +The type of a column is the name that the last read of its table wrote, so a table that an older +source read keeps the older name until it is read again. Nothing is stored, so a check has no state +here. Creating tests from this answer is a separate step that keys on the identity of a check and +compares the binding revisions it read. + +## Amendment + +v2 (2026-11-24): the text above is the amended rule. Four things changed from the first version. + +- Every check is a generated query. The first version offered the built-in column tests + `columnValuesToBeNotNull`, `columnValuesToBeInSet`, `columnValuesToBeBetween` and + `columnValuesToMatchRegex` on a simple table. The reason `tableNotSimple` left the closed list. +- A pattern is checked on the `Postgres` service type only, with `[^\n\r]` in place of each `.`. + The first version sent a pattern to the regex test of every engine. +- A datatype is held by engine family. The first version held it by the name of the column's type + alone, and so counted `NaN`, `infinity`, the zero date and a time above 24 hours as values of a + datatype. +- A shape that the caller may not view is left out, and a constraint about a property that the + caller may not view is hidden. The first version showed both to every caller who could read the + class. The two checks add 10 statements to a draft and 8 to a release. From e12956c05a2cf203b886efcc59e403af02e6c12d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 16:17:58 -0800 Subject: [PATCH 087/203] Test that no term text reaches a statement and that no read locks A person names and describes a shape, a property, a table and a column. OntologyShapeCheckGoldenTest writes text that ends a string and starts a statement into each of them for every golden case. The count that the test runs must still be the golden file with its colons escaped, and the list of keys must still be the one the count is made from. OntologyShapeCheckReadsIT asserts that no statement of a request locks the rows it reads. OntologyShapeCheckPatternIT reads the text of a pattern statement after the counts, so a statement that Postgres reads in another way fails on the number it counts. --- .../it/tests/OntologyShapeCheckPatternIT.java | 19 ++++--- .../it/tests/OntologyShapeCheckReadsIT.java | 17 ++++++ .../OntologyShapeCheckGoldenTest.java | 48 +++++++++++++++-- .../ontology/OntologyShapeCheckGoldens.java | 53 +++++++++++++++++-- 4 files changed, 121 insertions(+), 16 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java index effe781e687b..a9d1ebc580f1 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java @@ -132,14 +132,6 @@ void aPatternCountsTheRecordsWithAValueThatItDoesNotMatch(final TestNamespace ns final OntologyShapeCheck mail = check(checks, "mail", PATTERN); assertEquals(CUSTOM_SQL, pair.getTestDefinition()); - assertEquals( - String.join( - "\n", - "SELECT DISTINCT t0.id AS k0", - "FROM " + fixture.from("codes") + " t0", - "WHERE t0.id IS NOT NULL", - " AND NOT (CAST(t0.pair AS text) COLLATE \"C\" ~ E'^1[^\\\\n\\\\r]2$')"), - pair.getInspectionQuery()); for (final OntologyShapeCheck check : List.of(pair, digits, word, mail)) { assertCounts("0", NO_KEYS, check); } @@ -161,6 +153,17 @@ void aPatternCountsTheRecordsWithAValueThatItDoesNotMatch(final TestNamespace ns assertCounts("4", List.of(List.of("3"), List.of("4"), List.of("5"), List.of("7")), digits); assertCounts("4", List.of(List.of("3"), List.of("4"), List.of("5"), List.of("7")), word); assertCounts("3", List.of(List.of("3"), List.of("4"), List.of("5")), mail); + + // The text is read after the counts, so a statement that the engine reads in another way + // fails on the number it counts. + assertEquals( + String.join( + "\n", + "SELECT DISTINCT t0.id AS k0", + "FROM " + fixture.from("codes") + " t0", + "WHERE t0.id IS NOT NULL", + " AND NOT (CAST(t0.pair AS text) COLLATE \"C\" ~ E'^1[^\\\\n\\\\r]2$')"), + pair.getInspectionQuery()); } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index 99e7f74bd372..f822d1fe7935 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -65,6 +65,7 @@ * read once for the answer, and the caller's right to view is checked once for the shapes, once * for the properties and once for the tables. So a class with eighty constraints is read in the * statements of a class with one, and a class of twelve tables in the statements of one of three. + * No statement of a request locks the rows it reads. */ @Isolated("Counts the SQL statements that serve one request") @ExtendWith(TestNamespaceExtension.class) @@ -76,6 +77,15 @@ class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { private static final String RELEASE_MEMBERS = "from ontology_release_member"; private static final String SETTINGS = "from openmetadata_settings"; + /** What a read that locks its rows ends with, on MySQL and on Postgres. */ + private static final List LOCKS = + List.of( + " for update", + " for share", + " for no key update", + " for key share", + " lock in share mode"); + /** Every statement of one read of the draft, as an administrator, and of the active release. */ private static final int DRAFT_STATEMENTS = 46; @@ -384,6 +394,7 @@ private static void assertDraftReads(final Reads reads) { assertEquals(2, reads.of(PROPERTIES), reads::listed); assertEquals(2, reads.of(BINDING_ROWS), reads::listed); assertEquals(0, reads.of(RELEASE_MEMBERS), reads::listed); + assertNoLock(reads); } private static void assertReleaseReads(final Reads reads) { @@ -392,5 +403,11 @@ private static void assertReleaseReads(final Reads reads) { assertEquals(1, reads.of(PROPERTIES), reads::listed); assertEquals(2, reads.of(BINDING_ROWS), reads::listed); assertEquals(4, reads.of(RELEASE_MEMBERS), reads::listed); + assertNoLock(reads); + } + + /** A request only reads, so none of its statements may lock the rows it read. */ + private static void assertNoLock(final Reads reads) { + LOCKS.forEach(lock -> assertEquals(0, reads.of(lock), reads::listed)); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java index 362ed6204642..43a38b991795 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java @@ -13,6 +13,7 @@ package org.openmetadata.service.ontology; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; @@ -28,6 +29,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; import org.openmetadata.schema.api.data.OntologyShapeCheckReason; import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; import org.openmetadata.service.ontology.OntologyShapeCheckGoldens.Golden; @@ -55,17 +58,54 @@ class OntologyShapeCheckGoldenTest { "repeatedContribution-addressCity-pattern", "unfilteredIdentity-customerEmail-pattern"); + /** Text that ends a string, starts a statement, opens a comment and names a parameter. */ + private static final String INJECTION = "ZQX'; DROP TABLE t; -- :p \\ %_"; + + private static final String MARKER = "ZQX"; + static List goldens() { return OntologyShapeCheckGoldens.all(); } - @ParameterizedTest - @MethodSource("goldens") - void aCountQueryIsTheTextOfItsGoldenFile(final Golden golden) throws IOException { + private static String file(final Golden golden) throws IOException { try (InputStream file = OntologyShapeCheckGoldenTest.class.getResourceAsStream("/" + golden.resource())) { assertNotNull(file, "No golden file " + golden.resource()); - assertEquals(new String(file.readAllBytes(), StandardCharsets.UTF_8), golden.text()); + return new String(file.readAllBytes(), StandardCharsets.UTF_8); + } + } + + @ParameterizedTest + @MethodSource("goldens") + void aCountQueryIsTheTextOfItsGoldenFile(final Golden golden) throws IOException { + assertEquals(file(golden), golden.text()); + } + + /** + * A person names and describes a shape, a property, a table and a column, and none of that text + * is part of a statement. With an injection as each of them, the answer names the shape with + * the text, the count that a test runs is still the golden file with its colons escaped, the + * list of keys is still the one the count is made from, and no parameter holds the injection. + */ + @ParameterizedTest + @MethodSource("goldens") + void injectionTextInEveryTermReachesNoStatement(final Golden golden) throws IOException { + final OntologyCheckedShape shape = golden.checkedWhereEveryTermHolds(INJECTION); + final List checks = + shape.getConstraints().getFirst().getParts().getFirst().getChecks(); + final OntologyShapeCheck first = checks.getFirst(); + assertEquals(INJECTION, shape.getName()); + assertEquals( + file(golden).stripTrailing().replace(":", "\\:"), + first.getParameterValues().getFirst().getValue()); + assertEquals(golden.keys(), first.getInspectionQuery()); + for (final OntologyShapeCheck check : checks) { + assertFalse(check.getInspectionQuery().contains(MARKER), check.getInspectionQuery()); + check + .getParameterValues() + .forEach( + parameter -> + assertFalse(parameter.getValue().contains(MARKER), parameter.getValue())); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java index 8e5327837e39..bfff1969821e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java @@ -24,9 +24,15 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Set; import java.util.function.UnaryOperator; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; import org.openmetadata.service.ontology.sql.SqlEngineFamily; @@ -68,13 +74,38 @@ String resource() { "%s/%s/%s.sql", DIRECTORY, family.name().toLowerCase(Locale.ROOT), asked.name()); } + private OntologyShapeCheckModel model() { + return new OntologyShapeCheckModel( + asked.shape(), OntologyStatementGoldens.SERVICE_TYPES.get(family)); + } + OntologyPartOutcome answer() { - final OntologyShapeCheckModel model = - new OntologyShapeCheckModel( - asked.shape(), OntologyStatementGoldens.SERVICE_TYPES.get(family)); + final OntologyShapeCheckModel model = model(); return model.answer(asked.type(), asked.states().apply(model.on(asked.property()))); } + /** + * The answer for the shape of this part, when {@code text} is every name and description that + * a person gives the shape and each property, and the display name and the description of each + * table and column. The names of a table and of a column stay, because a statement is written + * with them. + */ + OntologyCheckedShape checkedWhereEveryTermHolds(final String text) { + final OntologyShapeCheckModel model = model(); + asked.shape().tables().forEach(spec -> describe(model.mapping().table(spec.name()), text)); + final OntologyShapeCheckFacts facts = model.facts(asked.type()); + facts.properties().values().forEach(property -> describe(property, text)); + final OntologyShape shape = + model + .targeting(asked.type(), asked.states().apply(model.on(asked.property()))) + .withName(text) + .withDisplayName(text) + .withDescription(text) + .withFullyQualifiedName(text); + return OntologyShapeCheckAnswer.shapes(facts, List.of(shape), new Hidden(Set.of(), Set.of())) + .getFirst(); + } + boolean isGenerated() { return answer() instanceof OntologyPartOutcome.Check; } @@ -148,10 +179,24 @@ static List parts() { return List.copyOf(parts); } + private static void describe(final Table table, final String text) { + table.withDisplayName(text).withDescription(text); + table.getColumns().forEach(column -> column.withDisplayName(text).withDescription(text)); + } + + private static void describe(final OntologyProperty property, final String text) { + property + .withName(text) + .withDisplayName(text) + .withDescription(text) + .withFullyQualifiedName(text) + .withUnit(text); + } + /** * The counts, the list and the pattern of a text property. The pattern holds each construct * that is written in another way than it is given: a wildcard, and a backslash before a colon, - * a percent sign and a quote. + * a dot and a quote. */ private static List valueParts( final Shape shape, final String type, final String property, final int count) { From 8327114538158587e4e92ec9799937334248a22d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 16:18:10 -0800 Subject: [PATCH 088/203] Say what a part is answered before the rule is read The rule table is read for a property that an identity table or a contributing table of the class binds, on a class whose records can be read. The record now names the answers that come before it, and says that no statement of a request locks the rows it reads. --- ...ape-check-is-exact-or-it-is-not-offered.md | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index 6ac536a091f6..b0d3c85c5a4b 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -33,7 +33,7 @@ one of five outcomes. |---|---| | `check` | A test counts the records that break the part. One check for each table that holds the property. | | `heldByMapping` | No record can break the part, because of how the class is mapped. | -| `notMapped` | The class binds the property in no column, or the version has no such property. | +| `notMapped` | No identity table and no contributing table of the class binds the property, or the version has no such property. | | `notEnforceable` | No exact test exists. A `reason` from a closed list says why. | | `hidden` | The caller may not view a table that the answer rests on, or the property the constraint is about. | @@ -92,7 +92,19 @@ table constraint or by the column constraint `UNIQUE`. The declaration in the ca its word on every engine, whether the database or a person declared it, and whether or not the engine enforces it. -**The rule.** "Generated" is a check whose statement counts the records that the row names. +**The rule.** "Generated" is a check whose statement counts the records that the row names. The +table is read for a property that an identity table or a contributing table of the class binds. Two +answers come before it. + +- A property that the version does not have is `notMapped`. A property that no identity table and + no contributing table of the class binds is `notMapped` too, with two exceptions that the table + of reasons names: `noIdentityTable` when the class binds it in a table with no role and has no + identity table, and `boundOnInverse` when the class binds a relation in no table and another + class binds the inverse. +- For every part but `minCount 0`, a class whose records cannot be read is `notEnforceable`: + `noIdentityTable` when it has no identity table, `columnMissing` when the subject key is empty or + when one of its columns or the column of the row filter is not in the identity table, and + `valueDoesNotFitColumn` when the stored row filter no longer parses. | Part | Answer | |---|---| @@ -248,9 +260,10 @@ that target the class, the properties their constraints name, the classes their name, the binding rows, and the tables those rows name. It checks the caller's right to view once for the shapes, once for the properties and once for the tables. The number of statements does not grow with the number of shapes, of constraints or of tables. An administrator's request runs 46 -`SELECT` statements from the draft and 52 from a release. `OntologyShapeCheckReadsIT` counts those -two numbers for 1, 40 and 80 constraints on a class of 6 tables, and for 40 constraints on a class -of 3 tables and of 12. Of these, 23 read the tables with what the check of the right to view them +`SELECT` statements from the draft and 52 from a release, and no statement locks the rows it reads. +`OntologyShapeCheckReadsIT` counts those two numbers for 1, 40 and 80 constraints on a class of 6 +tables, and for 40 constraints on a class of 3 tables and of 12, and it finds no locking read in +any request. Of the statements, 23 read the tables with what the check of the right to view them needs. The two checks of the shapes and the properties take 10 in a draft and 8 in a release. A server setting whose cached value has lapsed is read on top of them. Two questions cost further reads, and only when a constraint asks them: the declared inverse of a relation that the class From 4e905a515b8bc5b174acfc9936492e15ceb5d294 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 16:55:52 -0800 Subject: [PATCH 089/203] Compare a check's table without its entity type in the answer test The type of an entity reference comes from the registry of entity types. OntologyShapeCheckAnswerTest does not load the registry, and the answer it expected held a table reference with no type. Another test of the same run can load the registry first. The answer then names the type, and the test failed that way in one full unit run. The test now leaves the type out of the answer it compares. The entity link of the check still names the table type. --- .../OntologyShapeCheckAnswerTest.java | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java index 8b6ccc96a4f7..423af15bdcbd 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java @@ -51,7 +51,11 @@ class OntologyShapeCheckAnswerTest { + "{\"name\":\"operator\",\"value\":\"<=\"}," + "{\"name\":\"threshold\",\"value\":\"0\"}]"; - /** The reference of a table that no catalog holds, so it names no entity type. */ + /** + * The reference of the customers table without its entity type. The type of a reference comes + * from the registry of entity types. This test does not load the registry and another test of + * the same run may, so {@link #withoutEntityType} takes the type out of what is compared. + */ private static final String CUSTOMERS_TABLE = "{\"id\":\"7cc39a8b-6fb0-313c-b68f-2dc9b46b50d5\",\"name\":\"customers\"," + "\"fullyQualifiedName\":\"warehouse.sales.shop.customers\"," @@ -78,6 +82,16 @@ private static List parts( .getParts(); } + /** The parts with no entity type on the table reference of a check. */ + private static List withoutEntityType( + final List parts) { + parts.stream() + .filter(part -> part.getChecks() != null) + .flatMap(part -> part.getChecks().stream()) + .forEach(check -> check.getTable().setType(null)); + return parts; + } + /** The answer for a caller who may not view the tables {@code hidden} and may view the rest. */ private static List shapes( final OntologyShapeCheckModel model, @@ -241,11 +255,12 @@ void aTestRunsItsCountWithColonsEscapedAndListsItsKeysAsAPersonReadsThem() { + CUSTOMER_BINDING + "]}]}]", JsonUtils.pojoToJson( - parts( - model, - "Customer", - model.on("customerEmail").withIn(literals("mailto:a", "b")), - Set.of()))); + withoutEntityType( + parts( + model, + "Customer", + model.on("customerEmail").withIn(literals("mailto:a", "b")), + Set.of())))); } @Test From 1baab29f539a8a649880fdb889d5d44933608144 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 22:36:45 -0800 Subject: [PATCH 090/203] Read the escapes and punctuation of XPath, and hide a class part's class from a caller who may not view it A pattern takes any ASCII punctuation character that is no metacharacter as itself, and a backslash only before a character of the XPath single-character escape set, with \n, \r and \t read as a line feed, a carriage return and a tab. The answer masks a constraint whose class part names a class the caller may not view, and a draft authorizes the shape, property and class rows it already read. A contributing column named like an identity key column is tested as not held. --- .../ontology/OntologyPortablePattern.java | 68 ++++++++---- .../ontology/OntologyShapeCheckAnswer.java | 16 ++- .../ontology/OntologyShapeCheckReader.java | 30 +++-- .../service/ontology/OntologyVersion.java | 44 +++----- .../ontology/OntologyPortablePatternTest.java | 104 +++++++++++++++++- .../OntologyShapeCheckAnswerTest.java | 37 ++++++- .../OntologyShapeCheckCompilerTest.java | 38 ++++++- .../ontology/OntologyShapeCheckGoldens.java | 7 +- .../OntologyShapeCheckReaderTest.java | 60 ++++++++-- .../ontology/OntologyShapeCheckSqlTest.java | 5 +- .../OntologyShapeCheckValueCasesTest.java | 2 +- .../compositeKey-accountTier-pattern.sql | 2 +- .../filteredIdentity-personName-pattern.sql | 2 +- ...peatedContribution-addressCity-pattern.sql | 2 +- ...filteredIdentity-customerEmail-pattern.sql | 2 +- 15 files changed, 323 insertions(+), 96 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java index 499b08c3c154..f4b657d9c955 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java @@ -25,15 +25,24 @@ * *

        *
      • it starts with {@code ^} and ends with {@code $}, and holds no other anchor; - *
      • a character is an ASCII letter, a digit, a space, {@code .}, or a backslash before an - * ASCII punctuation character; - *
      • a character class holds letters, digits, spaces and ranges of them, and may be negated; + *
      • a character is an ASCII letter, a digit, a space, an ASCII punctuation character that is + * no metacharacter, {@code .}, or a backslash before a character of the single-character + * escape set of XPath; + *
      • a character class holds the same literal characters, escapes, and ranges of two digits or + * of two letters of one case, and may be negated; *
      • a group has no prefix such as {@code (?:}, and holds every alternation; *
      • a quantifier is {@code ?}, {@code *}, {@code +}, {@code {n}}, {@code {n,}} or {@code * {n,m}}, and nothing follows it that would make it lazy or possessive. *
      * - * An alternation outside a group is refused because {@code ^a|b$} anchors one branch each on an + * The metacharacters are {@code . \ ? * + { } ( ) [ ] | ^ $}, and {@code -} inside a class. The + * escape set is the one of XPath and XQuery Functions and Operators 3.1, section 5.6.1: {@code n}, + * {@code r}, {@code t}, and a backslash before {@code \ | . ? * + ( ) { } - [ ] ^ $}. Any other + * escape is an error in XPath, so a pattern that holds one is refused and not read as the escaped + * character. {@code \n}, {@code \r} and {@code \t} are a line feed, a carriage return and a tab + * on Postgres too, in a class and outside one. + * + *

      An alternation outside a group is refused because {@code ^a|b$} anchors one branch each on an * engine that searches and both on an engine that matches the whole value. * *

      Postgres is the one engine that was run against every construct of the core. It reads one of @@ -41,12 +50,19 @@ * XPath matches neither. So a pattern is written for Postgres with the class of every character * but those two in place of each {@code .}. The rest it reads as XPath does. {@code $} matches at * the very end only, a range in a class goes by code point whatever the collation, a negated - * class matches a line break, and a backslash before a punctuation character is that character. + * class matches a line break, and each escape of the set above is the character it names. */ final class OntologyPortablePattern { private static final Pattern COUNT = Pattern.compile("0|[1-9][0-9]{0,2}"); private static final String ANY_BUT_A_LINE_BREAK = "[^\\n\\r]"; private static final String QUANTIFIERS = "?*+{"; + + /** Every character that XPath reads as syntax outside a class. {@code -} joins them inside one. */ + private static final String METACHARACTERS = ".\\?*+{}()[]|^$"; + + /** The characters after a backslash that XPath reads: the escape set of its single characters. */ + private static final String ESCAPABLE = "nrt\\|.?*+(){}-[]^$"; + private static final int MOST_REPEATS = 255; private static final char LAST_ASCII = '~'; private final String body; @@ -99,7 +115,7 @@ private boolean sequence() { private boolean atom() { final char next = body.charAt(at); - if (isPlain(next) || next == '.') { + if (isLiteral(next) || next == '.') { wildcards.set(at, next == '.'); at++; return true; @@ -112,19 +128,25 @@ private boolean atom() { }; } - private static boolean isPlain(final char character) { - return character == ' ' || character <= LAST_ASCII && Character.isLetterOrDigit(character); + private static boolean isAlphanumeric(final char character) { + return character <= LAST_ASCII && Character.isLetterOrDigit(character); + } + + /** A character that stands for itself outside a class. */ + private static boolean isLiteral(final char character) { + return character >= ' ' && character <= LAST_ASCII && METACHARACTERS.indexOf(character) < 0; } - /** A backslash before a punctuation character, which is read as that character. */ + /** A character that stands for itself inside a class, where {@code -} is syntax too. */ + private static boolean isClassLiteral(final char character) { + return isLiteral(character) && character != '-'; + } + + /** A backslash before a character of the escape set, which XPath reads and Postgres agrees on. */ private boolean escaped() { - final boolean punctuation = - at + 1 < body.length() - && body.charAt(at + 1) > ' ' - && body.charAt(at + 1) <= LAST_ASCII - && !Character.isLetterOrDigit(body.charAt(at + 1)); + final boolean known = at + 1 < body.length() && ESCAPABLE.indexOf(body.charAt(at + 1)) >= 0; at += 2; - return punctuation; + return known; } private boolean characterClass() { @@ -139,10 +161,16 @@ private boolean characterClass() { return at > first && more() && body.charAt(at++) == ']'; } - /** One plain character of a class, or a range of two digits or of two letters of one case. */ + /** + * One literal character or escape of a class, or a range of two digits or of two letters of one + * case. + */ private boolean member() { + if (body.charAt(at) == '\\') { + return escaped(); + } final char low = body.charAt(at++); - if (!isPlain(low)) { + if (!isClassLiteral(low)) { return false; } if (!more() || body.charAt(at) != '-') { @@ -150,10 +178,10 @@ private boolean member() { } final char high = at + 1 < body.length() ? body.charAt(at + 1) : ' '; at += 2; - return isPlain(high) + return isAlphanumeric(low) + && isAlphanumeric(high) && low <= high - && Character.getType(low) == Character.getType(high) - && low != ' '; + && Character.getType(low) == Character.getType(high); } private boolean group() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java index 2d2a32756016..bca08f070599 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java @@ -28,6 +28,7 @@ import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.ontology.OntologyPartOutcome.Check; @@ -48,7 +49,8 @@ * caller. What a caller may not view is masked here, in one step after it. A constraint that rests * on a table the caller may not view answers {@code hidden} for each part it states, and says * nothing else about it. A constraint about a property the caller may not view answers the same, - * and does not name the property either. + * and does not name the property either. So does a constraint whose {@code class} part names a + * class the caller may not view, which keeps its path because the caller may view the property. */ final class OntologyShapeCheckAnswer { /** The table test that runs a statement written for the check. */ @@ -83,8 +85,10 @@ private OntologyShapeCheckAnswer(final OntologyShapeCheckFacts facts, final Hidd * * @param tables the ids of the tables that exist and that the caller may not view * @param paths the IRIs of the properties of the constraints that the caller may not view + * @param classes the IRIs of the classes that the {@code class} parts name and that the caller may + * not view */ - record Hidden(Set tables, Set paths) {} + record Hidden(Set tables, Set paths, Set classes) {} /** The part of one constraint of one shape that a test checks. */ private record Named(UUID shapeId, String constraintId, OntologyShapePart part) {} @@ -113,7 +117,9 @@ private OntologyCheckedConstraint constraint(final UUID shapeId, final CompiledC final URI path = found.constraint().getPath(); final boolean aboutHiddenProperty = hidden.paths().contains(path); final boolean masked = - aboutHiddenProperty || found.rests().stream().anyMatch(hidden.tables()::contains); + aboutHiddenProperty + || namesHiddenClass(found.constraint()) + || found.rests().stream().anyMatch(hidden.tables()::contains); return new OntologyCheckedConstraint() .withId(id) .withPath(aboutHiddenProperty ? null : path) @@ -125,6 +131,10 @@ private OntologyCheckedConstraint constraint(final UUID shapeId, final CompiledC .toList()); } + private boolean namesHiddenClass(final OntologyShapeConstraint constraint) { + return constraint.getClassIri() != null && hidden.classes().contains(constraint.getClassIri()); + } + /** One entry for each part, so the number of answers the tables gave is not told either. */ private static List masked(final List parts) { return parts.stream() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java index fc9d3d85a3e1..4ddc5749a519 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java @@ -32,6 +32,7 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyShape; @@ -57,8 +58,8 @@ * parts name, the binding rows between two reads of the binding revisions, and the tables those * rows name. * - *

      The caller's right to view is checked once for the shapes, once for the properties and once - * for the tables. A shape that the caller may not view is left out before anything is read for + *

      The caller's right to view is checked once for the shapes, once for the properties, once for + * the classes that {@code class} parts name and once for the tables. A shape that the caller may not view is left out before anything is read for * it. A property and a table are read whoever asks, because the compile is the same for every * caller, and what the caller may not view of them is masked afterwards. * @@ -147,7 +148,10 @@ Read read(final Access access, final Asked asked) { targets(classes, rows, others, tables), boundOnInverse(others, tables), rows.revisions()), - new Hidden(hidden(tables), hiddenPaths(access, asked, properties))); + new Hidden( + hidden(tables), + hiddenIris(access, asked, Entity.ONTOLOGY_PROPERTY, properties), + hiddenIris(access, asked, Entity.ONTOLOGY_CONCEPT, classes))); } private List shapes(final Access access, final Asked asked) { @@ -161,15 +165,19 @@ private List shapes(final Access access, final Asked asked) { .toList(); } - /** The IRIs of the properties of the constraints that the caller may not view. */ - private Set hiddenPaths( - final Access access, final Asked asked, final Map properties) { + /** + * The IRIs among {@code definitions} that the caller may not view, judged on the definitions as + * this version holds them. One batch answers for all of one type. + */ + private Set hiddenIris( + final Access access, + final Asked asked, + final String entityType, + final Map definitions) { final Set viewable = - asked - .version() - .viewable(catalog, access, Entity.ONTOLOGY_PROPERTY, List.copyOf(properties.values())); - return properties.entrySet().stream() - .filter(property -> !viewable.contains(property.getValue().getId())) + asked.version().viewable(catalog, access, entityType, List.copyOf(definitions.values())); + return definitions.entrySet().stream() + .filter(definition -> !viewable.contains(definition.getValue().getId())) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java index 666934164dc0..9550b3dbe001 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -90,15 +90,22 @@ Map viewableProperties( /** * The ids of the definitions among {@code read} that the caller may view. They are definitions - * of one type, read from this version whoever asks. The working draft checks the live working - * rows. A release checks the definitions as released, so one whose working row is deleted - * since is still found. + * of one type, read from this version whoever asks, and they are authorized as they were read, + * with no second read. A row that changed between a second read and the first would be compiled + * from one and authorized from the other. The rows of a release are the definitions as released, + * so one whose working row is deleted since is still found. The rows of the working draft are + * the live working rows. The caller's right is the policy input that the catalog holds now for + * the id: owners, domains and reviewers, loaded onto the rows. */ - Set viewable( - OntologyBindingAccess catalog, - Access access, - String entityType, - List read); + default Set viewable( + final OntologyBindingAccess catalog, + final Access access, + final String entityType, + final List read) { + return read.isEmpty() + ? Set.of() + : Set.copyOf(catalog.viewable(access, entityType, read).keySet()); + } /** * The id of the one class this version declares with one of {@code iris}, empty when it has @@ -175,16 +182,6 @@ public Map viewableProperties( .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); } - @Override - public Set viewable( - final OntologyBindingAccess catalog, - final Access access, - final String entityType, - final List read) { - final List ids = read.stream().map(OntologyDefinition::getId).toList(); - return Set.copyOf(catalog.viewable(access, entityType, ids).keySet()); - } - @Override public Optional classNamed( final OntologyConceptBindingStore store, final UUID ontologyId, final List iris) { @@ -248,17 +245,6 @@ public OntologyStatementVersionRead read() { .withSemanticVersion(release.getSemanticVersion()); } - @Override - public Set viewable( - final OntologyBindingAccess catalog, - final Access access, - final String entityType, - final List read) { - return read.isEmpty() - ? Set.of() - : Set.copyOf(catalog.viewable(access, entityType, read).keySet()); - } - /** * A class is found by IRI through the working rows, deleted ones too, and kept only when the * release holds a member with that id and that IRI. A class deleted for good and made again diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java index fab7ab7863a0..8e998e3b5736 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java @@ -16,8 +16,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Optional; +import java.util.stream.IntStream; +import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; /** @@ -40,7 +43,23 @@ class OntologyPortablePatternTest { "^(ab|cd)$", "^(a(b|c))+d$", "^(a|b)(c|d)$", - "^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}$" + "^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}$", + "^O'Brien$", + "^a:b$", + "^:name$", + "^[^@ ]+@[^@ ]+$", + "^[A-Z]{2}-[0-9]{4}$", + "^a_b$", + "^a\\tb$", + "^a\\nb\\rc$", + "^[^\\n\\r]*$", + "^[\\t ]+$", + "^[a\\-z]+$", + "^x'\\); DROP TABLE t; --$", + "^x'\\) OR 1=1 --$", + "^a\\\\b$", + "^\\$1$", + "^[!\"#%&',/:;<=>@_`~]+$" }) void writesAPatternInsideTheCommonCoreAsItIsGiven(final String pattern) { assertEquals(Optional.of(pattern), OntologyPortablePattern.forPostgres(pattern)); @@ -55,7 +74,9 @@ void writesAPatternInsideTheCommonCoreAsItIsGiven(final String pattern) { "^.*$ => ^[^\\n\\r]*$", "^a\\.b.$ => ^a\\.b[^\\n\\r]$", "^(a|.)+.{2,3}$ => ^(a|[^\\n\\r])+[^\\n\\r]{2,3}$", - "^[a-z]+.[0-9]$ => ^[a-z]+[^\\n\\r][0-9]$" + "^[a-z]+.[0-9]$ => ^[a-z]+[^\\n\\r][0-9]$", + "^O'Brien.$ => ^O'Brien[^\\n\\r]$", + "^a.\\tb$ => ^a[^\\n\\r]\\tb$" }) void writesAWildcardAsEveryCharacterButALineBreak(final String pattern, final String written) { assertEquals(Optional.of(written), OntologyPortablePattern.forPostgres(pattern)); @@ -101,14 +122,87 @@ void writesAWildcardAsEveryCharacterButALineBreak(final String pattern, final St "^[a-é]$", "^[0-٣]$", "^[\\d]$", - "^[a\\-z]$", "^[.]$", "^[[:alpha:]]$", - "^a_b$", "^café$", - "^a\tb$" + "^a\tb$", + "^a}$", + "^a]$", + "^{2}$", + "^a{$", + "^[a-]$", + "^[-a]$", + "^[a^]$", + "^[a$]$", + "^[a|b]$", + "^[(]$", + "^[?]$", + "^[a{]$", + "^[\\d]$", + "^\\D$", + "^\\s$", + "^\\S$", + "^\\W$", + "^\\i$", + "^\\I$", + "^\\c$", + "^\\C$", + "^\\p{L}$", + "^\\P{L}$", + "^O\\'Brien$", + "^a\\:b$", + "^\\@$", + "^\\;$", + "^\\=$", + "^\\_$", + "^\\ $", + "^\\é$", + "^a\\é$", + "^[\\@]$", + "^x\\'\\)\\; DROP TABLE t\\; \\-\\-$" }) void refusesAPatternOutsideTheCommonCore(final String pattern) { assertEquals(Optional.empty(), OntologyPortablePattern.forPostgres(pattern), pattern); } + + /** The escapes of XPath's single characters: XPath and XQuery Functions and Operators 3.1, 5.6.1. */ + private static final String XPATH_ESCAPES = "nrt\\|.?*+(){}-[]^$"; + + private static final String METACHARACTERS = ".\\?*+{}()[]|^$"; + + @ParameterizedTest + @MethodSource("asciiAfterABackslash") + void takesABackslashBeforeACharacterOfTheXPathEscapeSetOnly(final char escaped) { + final boolean read = XPATH_ESCAPES.indexOf(escaped) >= 0; + assertEquals( + read, + OntologyPortablePattern.forPostgres("^\\" + escaped + "$").isPresent(), + "outside a class, backslash then " + escaped); + assertEquals( + read, + OntologyPortablePattern.forPostgres("^[a\\" + escaped + "]$").isPresent(), + "inside a class, backslash then " + escaped); + } + + @ParameterizedTest + @MethodSource("asciiPunctuationWithoutMetacharacters") + void takesAnAsciiPunctuationCharacterThatIsNoMetacharacterAsItself(final char punctuation) { + final String outside = "^a" + punctuation + "b$"; + assertEquals(Optional.of(outside), OntologyPortablePattern.forPostgres(outside)); + final String inside = "^[a" + punctuation + "b]$"; + if (punctuation != '-') { + assertEquals(Optional.of(inside), OntologyPortablePattern.forPostgres(inside)); + } + } + + static Stream asciiAfterABackslash() { + return IntStream.rangeClosed(' ', '~').mapToObj(code -> (char) code); + } + + static Stream asciiPunctuationWithoutMetacharacters() { + return IntStream.rangeClosed('!', '~') + .mapToObj(code -> (char) code) + .filter(character -> !Character.isLetterOrDigit(character)) + .filter(character -> METACHARACTERS.indexOf(character) < 0); + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java index 423af15bdcbd..e06010c6ea4c 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java @@ -26,6 +26,7 @@ import java.util.Set; import java.util.UUID; import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; import org.openmetadata.schema.api.data.OntologyCheckedPart; import org.openmetadata.schema.api.data.OntologyCheckedShape; import org.openmetadata.schema.api.data.OntologyShapeCheck; @@ -98,7 +99,7 @@ private static List shapes( final String type, final Set hidden, final OntologyShapeConstraint... constraints) { - return shapes(model, type, new Hidden(hidden, Set.of()), constraints); + return shapes(model, type, new Hidden(hidden, Set.of(), Set.of()), constraints); } private static List shapes( @@ -206,7 +207,7 @@ SELECT COUNT(*) AS violations void patternIsTheCustomQueryTestWithItsColonsEscapedInTheCountOnly() { final OntologyShapeCheckModel model = customers(); final OntologyShapeCheck check = - check(model, "Customer", model.on("customerEmail").withPattern("^[a-z]+\\:.$")); + check(model, "Customer", model.on("customerEmail").withPattern("^[a-z]+:.$")); assertEquals(CUSTOM_SQL, check.getTestDefinition()); assertEquals(CUSTOMERS_LINK, check.getEntityLink()); assertEquals(List.of(List.of("email")), check.getColumns()); @@ -217,7 +218,7 @@ SELECT COUNT(*) AS violations SELECT DISTINCT t0.id AS k0 FROM shop.customers t0 WHERE t0.id IS NOT NULL - AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+\\\\\\:[^\\\\n\\\\r]$') + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+\\:[^\\\\n\\\\r]$') ) c""", parameter(check, "sqlExpression")); assertEquals( @@ -225,7 +226,7 @@ AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+\\\\\\:[^\\\\n\\\\r]$') SELECT DISTINCT t0.id AS k0 FROM shop.customers t0 WHERE t0.id IS NOT NULL - AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+\\\\:[^\\\\n\\\\r]$')""", + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+:[^\\\\n\\\\r]$')""", check.getInspectionQuery()); assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); assertEquals("[" + CUSTOMER_BINDING + "]", JsonUtils.pojoToJson(check.getReadBindings())); @@ -351,7 +352,8 @@ void aConstraintOnAHiddenIdentityTableSaysOnlyHiddenForEachPart() { @Test void aConstraintAboutAHiddenPropertySaysOnlyHiddenForEachPartAndDoesNotNameTheProperty() { final OntologyShapeCheckModel model = customers(); - final Hidden hidden = new Hidden(Set.of(), Set.of(UNFILTERED_IDENTITY.iri("customerEmail"))); + final Hidden hidden = + new Hidden(Set.of(), Set.of(UNFILTERED_IDENTITY.iri("customerEmail")), Set.of()); assertEquals( "[{\"id\":\"c740db69-5948-3a3f-8958-af47e77417cb\",\"name\":\"shape\"," + "\"severity\":\"Violation\",\"constraints\":[" @@ -375,7 +377,8 @@ void aHiddenPropertyOnAHiddenTableIsNotNamedEither() { final Hidden hidden = new Hidden( Set.of(model.mapping().id("customers")), - Set.of(UNFILTERED_IDENTITY.iri("customerEmail"))); + Set.of(UNFILTERED_IDENTITY.iri("customerEmail")), + Set.of()); assertEquals( "[{\"id\":\"c1\",\"parts\":[{\"part\":\"maxCount\",\"outcome\":\"hidden\"}]}]", JsonUtils.pojoToJson( @@ -423,6 +426,28 @@ void aHiddenTableThatAJoinReachesHidesEveryPartOfTheRelation() { JsonUtils.pojoToJson(shapes.getFirst().getConstraints())); } + @Test + void aClassPartThatNamesAHiddenClassHidesEveryPartOfItsConstraintAndKeepsThePath() { + final OntologyShapeCheckModel model = new OntologyShapeCheckModel(LINK_TABLE, POSTGRES); + final Hidden hidden = new Hidden(Set.of(), Set.of(), Set.of(LINK_TABLE.iri("Product"))); + final List constraints = + shapes( + model, + "Order", + hidden, + model.on("contains").withMinCount(1).withClassIri(LINK_TABLE.iri("Product")), + model.on("orderChannel").withId("c2").withMinCount(0)) + .getFirst() + .getConstraints(); + assertEquals( + "[{\"id\":\"c1\",\"path\":\"https://example.org/linkTable#contains\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"class\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/linkTable#orderChannel\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}]}]", + JsonUtils.pojoToJson(constraints)); + } + @Test void aHiddenAnswerDoesNotTellHowManyAnswersTheTablesGave() { final OntologyShapeCheckModel model = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java index 835fb3aa061e..8bc2fb84813e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java @@ -24,8 +24,11 @@ import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; import static org.openmetadata.service.ontology.OntologyMappingShapes.contributing; +import static org.openmetadata.service.ontology.OntologyMappingShapes.data; import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; import static org.openmetadata.service.ontology.OntologyShapeCheckModel.FILTERED_TARGET; import static org.openmetadata.service.ontology.OntologyShapeCheckModel.TWO_COLUMN_RELATION; import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; @@ -197,6 +200,39 @@ void minCountOneOffASimpleTableCountsRecordsWithNoValue() { assertEquals(OntologyRowFilterOperator.EQUALS, people.reach().identity().filter().operator()); } + @Test + void minCountOneOnAContributingColumnNamedLikeAKeyColumnOfTheIdentityTableIsNotHeld() { + final Shape keyNamedTwice = + new Shape( + "keyNamedTwice", + List.of( + table("customers", List.of(integer("customer_id"), text("name"))), + table("addresses", List.of(integer("customer_id"), text("city")))), + List.of("Customer"), + List.of( + data("customerName", true, "Customer"), data("addressOwner", false, "Customer")), + List.of( + identity( + "Customer", + "customers", + List.of("customer_id"), + null, + bound("customerName", "name")), + contributing( + "Customer", + "addresses", + List.of("customer_id"), + bound("addressOwner", "customer_id"))), + List.of()); + final OntologyShapeCheckModel model = shape(keyNamedTwice); + final TableCheck check = model.check("Customer", model.on("addressOwner").withMinCount(1)); + final FewerValues probe = probe(FewerValues.class, check); + assertEquals("addresses", check.place().holder().table().getName()); + assertEquals(List.of(List.of("customer_id")), probe.columns()); + assertEquals("addresses", probe.reach().holder().table().table().getName()); + assertEquals(1, probe.count()); + } + @Test void minCountOneOnAContributingTableJoinsItToTheRecords() { final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); @@ -413,7 +449,7 @@ void rangeOnATextColumnIsNotEnforceable() { @Test void patternOnATextColumnCountsRecordsWithAValueThatDoesNotMatch() { final OntologyShapeCheckModel model = customers(); - final String pattern = "^[a-z]+\\@example\\.org$"; + final String pattern = "^[a-z]+@example\\.org$"; final TableCheck check = model.check("Customer", model.on("customerEmail").withPattern(pattern)); final Unmatched probe = probe(Unmatched.class, check); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java index bfff1969821e..38a32940e92e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java @@ -44,8 +44,8 @@ final class OntologyShapeCheckGoldens { static final String DIRECTORY = "ontology/shape-checks"; - /** A wildcard, an escaped dot that is no wildcard, and a colon and a quote that a string escapes. */ - private static final String PATTERN = "^[A-Z][a-z0-9]+.(\\:|\\.|\\')*[^ ]{2,}$"; + /** A wildcard, an escaped dot that is no wildcard, an escaped backslash, and a colon and a quote that a string writes. */ + private static final String PATTERN = "^[A-Z][a-z0-9]+.(:|\\.|'|\\\\)*[^ ]{2,}$"; private OntologyShapeCheckGoldens() {} @@ -102,7 +102,8 @@ OntologyCheckedShape checkedWhereEveryTermHolds(final String text) { .withDisplayName(text) .withDescription(text) .withFullyQualifiedName(text); - return OntologyShapeCheckAnswer.shapes(facts, List.of(shape), new Hidden(Set.of(), Set.of())) + return OntologyShapeCheckAnswer.shapes( + facts, List.of(shape), new Hidden(Set.of(), Set.of(), Set.of())) .getFirst(); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java index 8e71dc886039..199045acc28f 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java @@ -22,6 +22,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -38,7 +39,9 @@ import java.util.stream.IntStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; @@ -98,14 +101,13 @@ void everythingExistsAndIsViewable() { .collect(Collectors.toMap(id -> id, id -> new Table().withId(id))); return new TableViews(live, live.keySet()); }); - when(catalog.viewable(any(), anyString(), anyCollection())) + when(catalog.viewable(any(), anyString(), ArgumentMatchers.anyList())) .thenAnswer( call -> - call.>getArgument(2).stream() - .distinct() + call.>getArgument(2).stream() .collect( - Collectors.>toMap( - id -> id, id -> new OntologyShape().withId(id)))); + Collectors.>toMap( + OntologyDefinition::getId, definition -> new OntologyShape()))); } @Test @@ -119,7 +121,7 @@ void anAnswerNamesTheRevisionItsRowsWereReadUnder() { assertEquals(Map.of(ORDER, 4L), read.facts().revisions()); assertEquals(List.of(orders, items), rows(read)); - assertEquals(new Hidden(Set.of(), Set.of()), read.hidden()); + assertEquals(new Hidden(Set.of(), Set.of(), Set.of()), read.hidden()); } @Test @@ -225,7 +227,7 @@ void aShapeTheCallerMayNotViewIsLeftOutAndNothingIsReadForIt() { shape(2, "a", ORDER_IRI, on(PLACED_BY_IRI).withClassIri(PERSON_IRI)); when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) .thenReturn(List.of(denied, viewable)); - when(catalog.viewable(null, Entity.ONTOLOGY_SHAPE, List.of(denied.getId(), viewable.getId()))) + when(catalog.viewable(null, Entity.ONTOLOGY_SHAPE, List.of(denied, viewable))) .thenReturn(Map.of(viewable.getId(), viewable)); final Read read = reader.read(null, DRAFT_ORDER); @@ -250,16 +252,54 @@ void aPropertyTheCallerMayNotViewIsReadForTheCompileAndNamedAsHidden() { on(PLACED_BY_IRI).withMinCount(1)))); when(store.liveProperties(ONTOLOGY, Set.of(CHANNEL_IRI, PLACED_BY_IRI))) .thenReturn(List.of(channel, placedBy)); - when(catalog.viewable( - null, Entity.ONTOLOGY_PROPERTY, List.of(channel.getId(), placedBy.getId()))) + when(catalog.viewable(null, Entity.ONTOLOGY_PROPERTY, List.of(channel, placedBy))) .thenReturn(Map.of(channel.getId(), channel)); final Read read = reader.read(null, DRAFT_ORDER); - assertEquals(new Hidden(Set.of(), Set.of(PLACED_BY_IRI)), read.hidden()); + assertEquals(new Hidden(Set.of(), Set.of(PLACED_BY_IRI), Set.of()), read.hidden()); assertEquals(Map.of(CHANNEL_IRI, channel, PLACED_BY_IRI, placedBy), read.facts().properties()); } + @Test + void aClassThatAPartNamesAndTheCallerMayNotViewIsNamedAsHidden() { + final OntologyConcept product = + new OntologyConcept().withId(new UUID(4, 1)).withIri(PRODUCT_IRI); + final OntologyConcept person = new OntologyConcept().withId(new UUID(4, 2)).withIri(PERSON_IRI); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn( + List.of( + shape( + 1, + "a", + ORDER_IRI, + on(PLACED_BY_IRI).withClassIri(PERSON_IRI), + on(CHANNEL_IRI).withId("c2").withClassIri(PRODUCT_IRI)))); + when(store.liveConcepts(ONTOLOGY, Set.of(PERSON_IRI, PRODUCT_IRI))) + .thenReturn(List.of(person, product)); + when(catalog.viewable(null, Entity.ONTOLOGY_CONCEPT, List.of(person, product))) + .thenReturn(Map.of(person.getId(), person)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(new Hidden(Set.of(), Set.of(), Set.of(PRODUCT_IRI)), read.hidden()); + } + + @Test + void theDraftAuthorizesTheRowsItReadAndReadsNoneAgain() { + final OntologyShape order = shape(1, "a", ORDER_IRI, on(CHANNEL_IRI).withMinCount(1)); + final OntologyProperty channel = property(1, CHANNEL_IRI); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn(List.of(order)); + when(store.liveProperties(ONTOLOGY, Set.of(CHANNEL_IRI))).thenReturn(List.of(channel)); + + reader.read(null, DRAFT_ORDER); + + verify(catalog).viewable(null, Entity.ONTOLOGY_SHAPE, List.of(order)); + verify(catalog).viewable(null, Entity.ONTOLOGY_PROPERTY, List.of(channel)); + verify(catalog, never()).viewable(any(), anyString(), anyCollection()); + } + @Test void theShapesOfAReleaseAreReadFromEveryPageOfItsMembers() { final List members = new ArrayList<>(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java index b9a9344d0b1d..3e1ffb592a7e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java @@ -254,9 +254,8 @@ void patternWithABackslashIsWrittenAsAStringThatReadsItsEscapes() { SELECT DISTINCT t0.id AS k0 FROM shop.customers t0 WHERE t0.id IS NOT NULL - AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+[^\\\\n\\\\r]\\\\@example\\\\.org$')""", - keys( - model, "Customer", model.on("customerEmail").withPattern("^[a-z]+.\\@example\\.org$"))); + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+[^\\\\n\\\\r]@example\\\\.org$')""", + keys(model, "Customer", model.on("customerEmail").withPattern("^[a-z]+.@example\\.org$"))); } @Test diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java index 3e8c96986d9f..b23428cb5e83 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java @@ -92,7 +92,7 @@ private static OntologyCheckedPart listed(final Run run) { List.of( model.targeting( "Customer", model.on("customerEmail").withIn(literals(run.input())))), - new Hidden(Set.of(), Set.of())) + new Hidden(Set.of(), Set.of(), Set.of())) .getFirst() .getConstraints() .getFirst() diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql index 7d055d45a6bc..af76a2ba991b 100644 --- a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql @@ -5,5 +5,5 @@ FROM ( JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id WHERE t0.tenant_id IS NOT NULL AND t0.customer_id IS NOT NULL - AND NOT (CAST(t1.tier AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](\\:|\\.|\\'')*[^ ]{2,}$') + AND NOT (CAST(t1.tier AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](:|\\.|''|\\\\)*[^ ]{2,}$') ) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql index f106a5c82417..60c08e139675 100644 --- a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql @@ -4,5 +4,5 @@ FROM ( FROM shop.parties t0 WHERE t0.id IS NOT NULL AND t0.kind = 'person' - AND NOT (CAST(t0.name AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](\\:|\\.|\\'')*[^ ]{2,}$') + AND NOT (CAST(t0.name AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](:|\\.|''|\\\\)*[^ ]{2,}$') ) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql index b2c3a03cdef2..dd8a49db126a 100644 --- a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql @@ -4,5 +4,5 @@ FROM ( FROM shop.customers t0 JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id WHERE t0.id IS NOT NULL - AND NOT (CAST(t1.city AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](\\:|\\.|\\'')*[^ ]{2,}$') + AND NOT (CAST(t1.city AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](:|\\.|''|\\\\)*[^ ]{2,}$') ) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql index 0c773b575be4..a415b6e1626d 100644 --- a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql @@ -3,5 +3,5 @@ FROM ( SELECT DISTINCT t0.id AS k0 FROM shop.customers t0 WHERE t0.id IS NOT NULL - AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](\\:|\\.|\\'')*[^ ]{2,}$') + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](:|\\.|''|\\\\)*[^ ]{2,}$') ) c From 8ebfd9f0fff2ba317eaf81c75f4e435917af05e7 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 24 Nov 2026 23:06:06 -0800 Subject: [PATCH 091/203] ontology: integration tests for masked class parts, pattern spellings and the draft's single read, and the records --- ...-keeps-typed-values-apart-from-its-text.md | 22 ++- ...ape-check-is-exact-or-it-is-not-offered.md | 67 +++++-- .../OntologyShapeCheckDefinitionRightsIT.java | 150 +++++++++++++++ .../it/tests/OntologyShapeCheckPatternIT.java | 173 +++++++++++++++++- .../it/tests/OntologyShapeCheckReadsIT.java | 130 ++++++++++++- 5 files changed, 517 insertions(+), 25 deletions(-) diff --git a/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md b/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md index b4cd4b21e0cc..45a0ec875d06 100644 --- a/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md +++ b/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md @@ -1,7 +1,7 @@ # Generated SQL keeps typed values apart from its text - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (finished text comes in a form to read and a form to run) · v3 2026-11-24 (statement text takes the tilde) +- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (finished text comes in a form to read and a form to run) · v3 2026-11-24 (statement text takes the tilde) · v4 2026-11-24 (how a pattern is written into the statement) - **Deciders:** Ontology Studio maintainers - **Guard:** `OntologySqlValueCasesTest`, `SqlEngineFamilyTest`, `TypedValuesTest`, `TypedStatementTest`, `OntologyConceptSqlGeneratorTest`, `OntologySqlLiteralIT`, `OntologyRowFilterValueIT`, `OntologyConceptQueryIT` - **Related:** ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension (two of its rules @@ -156,3 +156,23 @@ Where this record lists the characters of statement text, add `~`. A tilde opens name, parameter, or comment, so the rule that text can put no value into a statement still holds. The pattern that the operator matches is a typed value like any other. The one statement that uses the operator is in ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered. + +v4 (2026-11-24): how a pattern is written into the statement. The pattern of a shape check is a +typed text value, and the family `postgres` writes it with the rule for its strings, which does +not change with the pattern: + +- Text with no backslash is written as `'…'`, with each quote doubled. `^O'Brien$` is + `'^O''Brien$'`. +- Text with a backslash is written as `E'…'`, with each backslash doubled and each quote doubled. + The server reads the string literal first and gets the original pattern back, so the regular + expression engine sees the pattern as the shape states it, whether `standard_conforming_strings` + is on or off. `^a\tb$` is `E'^a\\tb$'`, and the `.` that the check rewrites as `[^\n\r]` is + `E'^a[^\\n\\r]b$'`. `^x'\); DROP TABLE t; --$` is `E'^x''\\); DROP TABLE t; --$'`, so the + quote, the semicolon and the dashes stay inside the string. +- The `E` prefix is the only difference between the two forms. Code does not choose the form by + the pattern's meaning, only by whether the text holds a backslash. +- `escapedSql` also writes each colon of the pattern as `\:`, as it does for any value. A reader of + `:name` parameters removes that backslash before the server sees the statement, so the pattern + that runs holds the colon. + +The pattern is never part of statement text. `~` is, and the pattern follows it as the one value. diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index b0d3c85c5a4b..23a103d4ef30 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -1,7 +1,7 @@ # A shape check is exact or it is not offered - **Status:** Accepted -- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) +- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) - **Deciders:** Ontology Studio maintainers - **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads) - **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) @@ -150,14 +150,24 @@ shows that it reads each construct the same way. - The column is a text column of any table of the class. A `CHAR` column is refused, because the engine pads its values with spaces and nothing says whether the pattern is asked of the padding. - The pattern starts with `^` and ends with an unescaped `$`. Between them it holds only ASCII - letters, digits and spaces, a backslash before an ASCII punctuation character, `.`, character - classes, groups with no prefix, alternation inside a group, and the quantifiers `?`, `*`, `+`, - `{n}`, `{n,}` and `{n,m}` with counts up to 255. A character class holds ASCII letters, digits, - spaces and ranges of two digits or of two letters of one case, and may be negated. + letters, digits, spaces and punctuation, `.`, character classes, groups with no prefix, + alternation inside a group, and the quantifiers `?`, `*`, `+`, `{n}`, `{n,}` and `{n,m}` with + counts up to 255. No control character and no character outside ASCII is taken. +- An ASCII punctuation character that is not a metacharacter stands for itself, outside a character + class and inside one. The metacharacters are `.`, `\`, `?`, `*`, `+`, `{`, `}`, `(`, `)`, `[`, + `]`, `|`, `^` and `$`, and inside a class also `-`. So `^O'Brien$`, `^a:b$`, `^[^@ ]+@[^@ ]+$` and + `^[A-Z]{2}-[0-9]{4}$` are taken. +- A backslash is taken only before a character of the single-character escape set of XPath (XPath + and XQuery Functions and Operators 3.1, section 5.6.1): `n`, `r`, `t`, `\`, `|`, `.`, `?`, `*`, + `+`, `(`, `)`, `{`, `}`, `-`, `[`, `]`, `^` and `$`. `\n`, `\r` and `\t` are a line feed, a + carriage return and a tab, which Postgres reads the same way, in a class and outside one. Every + other escape is an error in XPath, so the pattern is `patternNotPortable`, `\:`, `\'`, `\@`, + `\;` and `\=` among them. The class escapes `\d`, `\s`, `\w`, `\i`, `\c`, `\p{...}` and their + capitals are refused as well. A character class holds the same literal characters and escapes, + and ranges of two digits or of two letters of one case, and may be negated. - An alternation outside a group is refused, because `^a|b$` means something else on an engine that - anchors a pattern by itself. A back reference, a look-around, a lazy or possessive quantifier, a - class such as `\d`, an anchor in the middle and a flag are refused. A refused pattern is - `patternNotPortable`. + anchors a pattern by itself. A back reference, a look-around, a lazy or possessive quantifier, an + anchor in the middle and a flag are refused too. A refused pattern is `patternNotPortable`. - Postgres reads one construct of that core in another way. Its `.` matches a line feed and a carriage return, and the `.` of XPath matches neither. The statement therefore holds `[^\n\r]` in place of each `.`. Refusing every pattern with a `.` was the other choice, and it @@ -259,24 +269,35 @@ binds the filtered table later changes the answer, and a caller sees it when it that target the class, the properties their constraints name, the classes their `class` parts name, the binding rows, and the tables those rows name. It checks the caller's right to view once for the shapes, once for the properties and once for the tables. The number of statements does not -grow with the number of shapes, of constraints or of tables. An administrator's request runs 46 -`SELECT` statements from the draft and 52 from a release, and no statement locks the rows it reads. +grow with the number of shapes, of constraints or of tables. An administrator's request runs 48 +`SELECT` statements from the draft and 56 from a release, and no statement locks the rows it reads. `OntologyShapeCheckReadsIT` counts those two numbers for 1, 40 and 80 constraints on a class of 6 -tables, and for 40 constraints on a class of 3 tables and of 12, and it finds no locking read in -any request. Of the statements, 23 read the tables with what the check of the right to view them -needs. The two checks of the shapes and the properties take 10 in a draft and 8 in a release. A -server setting whose cached value has lapsed is read on top of them. Two questions cost further +tables, for 40 constraints on a class of 3 tables and of 12, and for `class` parts that name 1 +class and 8 classes, and it finds no locking read in any request. A draft reads the shapes once and the properties once, and authorizes the rows it read, with no +second read of them. The check of the right to view reads the owners and the domains of the rows +it checks, and the compile reads none of the other fields that the check clears. A second read +would let a row that changed between the two be compiled from one version and authorized from the +other. A server setting whose cached value has lapsed is read on top of the statements. Two questions cost further reads, and only when a constraint asks them: the declared inverse of a relation that the class binds nowhere, and a subclass on a filtered identity table that a `class` part arrives at. **An answer is whole or it is refused.** A class that binds more than 100 tables, and a draft -class that more than 1,000 shapes name, get 409. An answer built from a part of them would leave a +class that more than 1,000 shapes name, get 409. The draft cap counts every live shape that names +the class, including shapes the caller may not view, so a caller who may edit learns that more than +1,000 exist. Counting only the shapes the caller may view would read every row the cap exists to +bound. An answer built from a part of them would leave a constraint unchecked or a count short. **What a caller may not view is left out or masked.** A shape that the caller may not view is not in the answer, and nothing is read for it. The compile of the other shapes is the same for every caller, and one step after it masks the rest. A constraint about a property the caller may not view -keeps its id, has no `path`, and has every part `hidden`. A constraint whose answer rests on a +keeps its id, has no `path`, and has every part `hidden`. A constraint that a `class` part ties to +a class the caller may not view has every part `hidden` too and keeps its `path`, and nothing of +that class is in the answer: no id, binding revision, table, key column or row filter. May not +view means `VIEW_BASIC` on `ontologyConcept`, judged on the class as this version holds it. +`OntologyShapeCheckDefinitionRightsIT` guards it for a draft and a release, and +`OntologyShapeCheckAnswerTest` and `OntologyShapeCheckReaderTest` guard the masking. A constraint +whose answer rests on a table the caller may not view has every part `hidden` too, with no check, no reason and no column. Such a table is the identity table, a table that binds the property in whatever role, or the table a join arrives at. A hidden constraint has one entry for each part, so it does not tell how many @@ -329,3 +350,17 @@ v2 (2026-11-24): the text above is the amended rule. Four things changed from th - A shape that the caller may not view is left out, and a constraint about a property that the caller may not view is hidden. The first version showed both to every caller who could read the class. The two checks add 10 statements to a draft and 8 to a release. + +v3 (2026-11-24): three things changed. + +- A `class` part whose class the caller may not view is masked. Each of its parts is `hidden`, the + `path` stays, and no id, binding revision, table, key column or row filter of that class is in + the answer. +- The portable pattern subset takes what XPath reads (XPath Functions 3.1, section 5.6.1). A + backslash is taken only before one of `n r t \ | . ? * + ( ) { } - [ ] ^ $`, inside a class and + outside one. Any other escape, the multi-character escapes `\d \s \w \i \c \p` and their + capitals, and a backslash before a character outside ASCII are `patternNotPortable`. ASCII + punctuation that is no metacharacter stands for itself, so `^a_b$`, `^O'Brien$` and `^a:b$` are + taken and `^a\:b$` is refused. Postgres 15 reads each of these as XPath does. +- A draft authorizes the shape, property and class rows it read and reads none of them again. The + statements are 48 from a draft and 56 from a release, where they were 46 and 52. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java index 4cf3db7b2e3d..de3cd95c43b8 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java @@ -15,17 +15,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.openmetadata.it.tests.OntologyBindingFixtures.client; import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.answer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.parts; import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.HIDDEN; import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; import static org.openmetadata.schema.api.data.OntologyShapePart.IN; @@ -37,6 +41,7 @@ import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; import java.util.Arrays; +import java.util.EnumMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; @@ -48,6 +53,7 @@ import org.openmetadata.schema.api.data.OntologyCheckedConstraint; import org.openmetadata.schema.api.data.OntologyCheckedPart; import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.api.data.OntologyShapePart; import org.openmetadata.schema.api.data.OntologyStatementVersion; @@ -55,11 +61,16 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.OntologyShapeSeverity; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; /** * What a reader who may not view a shape, or the property a constraint is about, reads from {@code @@ -74,6 +85,8 @@ class OntologyShapeCheckDefinitionRightsIT extends BaseOntologyApprovalIT { private static final String LINE_SHAPE = "LineShape"; private static final String EVERY_RESOURCE = "All"; private static final String NOT_THE_OWNER = "!isOwner()"; + private static final String FILTER_TEXT = "SecretProductFilter"; + private static final String OTHER_FILTER_TEXT = "OtherProductFilter"; private static final List VERSIONS = List.of(RELEASE, DRAFT); private static final List PROPERTIES = List.of("orderChannel", "contains", "itemQuantity"); @@ -160,6 +173,25 @@ OntologyShapeChecks masking(final OntologyStatementVersion version, final String return whole; } + /** + * The whole answer with the constraint of this id as a reader who may not view the class of + * its class part reads it: hidden for each part it states, and its path kept. + */ + OntologyShapeChecks maskingClassOf(final OntologyStatementVersion version, final String id) { + final OntologyShapeChecks whole = whole(version); + for (final OntologyCheckedShape shape : whole.getShapes()) { + shape.setConstraints( + shape.getConstraints().stream() + .map(found -> found.getId().equals(id) ? hiddenWithPath(found) : found) + .toList()); + } + return whole; + } + + private static OntologyCheckedConstraint hiddenWithPath(final OntologyCheckedConstraint found) { + return hidden(found).withPath(found.getPath()); + } + private static OntologyCheckedConstraint hidden(final OntologyCheckedConstraint found) { return new OntologyCheckedConstraint() .withId(found.getId()) @@ -199,6 +231,18 @@ private static void owns(final OpenMetadataClient reader, final OntologyShape sh .withOwners(List.of(readerReference(reader)))); } + private static void owns(final OpenMetadataClient reader, final OntologyConcept type) { + final String id = type.getId().toString(); + admin() + .ontologyConcepts() + .update( + id, + admin() + .ontologyConcepts() + .get(id, "owners") + .withOwners(List.of(readerReference(reader)))); + } + private static void owns(final OpenMetadataClient reader, final OntologyProperty property) { final String id = property.getId().toString(); admin() @@ -289,6 +333,112 @@ void aReaderReadsTheShapesAndThePropertiesTheyMayViewAsAnyoneReadsThem(final Tes } } + /** Product's identity binding with a row filter whose value is {@code filterValue}. */ + private static void filterProducts(final OntologyShapeFixture fixture, final String filterValue) { + fixture.bind( + new BindingSpec( + "Product", + "products", + OntologyBindingRole.IDENTITY, + List.of("sku"), + new FilterSpec("title", OntologyRowFilterOperator.NOT_EQUALS, filterValue), + List.of(bound("productTitle", "title")))); + } + + @Test + void aReaderWhoMayNotViewTheClassOfAClassPartReadsHiddenAndNothingOfThatClass( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deniedClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("chkCl" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + filterProducts(fixture, FILTER_TEXT); + final OpenMetadataClient reader = + callerWithout( + access, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT, NOT_THE_OWNER); + owns(reader, scene.order()); + final OntologyConcept product = fixture.type("Product"); + final Table products = fixture.table("products"); + + for (final OntologyStatementVersion version : VERSIONS) { + final String body = answer(reader, scene.order(), version); + final String whole = answer(admin(), scene.order(), version); + + assertAnswer(scene.maskingClassOf(version, "onProducts"), body); + final OntologyCheckedConstraint masked = + checks(reader, scene.order(), version).getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .filter(found -> found.getId().equals("onProducts")) + .findFirst() + .orElseThrow(); + assertEquals(fixture.property("contains").getIri(), masked.getPath()); + assertEquals( + List.of(MIN_COUNT, MAX_COUNT, CLASS), + masked.getParts().stream().map(OntologyCheckedPart::getPart).toList()); + masked + .getParts() + .forEach( + part -> { + assertEquals(HIDDEN, part.getOutcome()); + assertNull(part.getChecks()); + }); + assertAbsent( + body, + product.getId().toString(), + product.getIri().toString(), + products.getId().toString(), + products.getName(), + products.getFullyQualifiedName(), + "sku", + FILTER_TEXT); + assertTrue(whole.contains(product.getId().toString()), whole); + assertTrue(whole.contains(products.getName()), whole); + assertTrue(whole.contains(FILTER_TEXT), whole); + assertEquals( + OntologyShapeCheckOutcome.CHECK, + parts(checks(admin(), scene.order(), version), "onProducts", CLASS) + .getFirst() + .getOutcome()); + } + } + } + + @Test + void aWriteToTheBindingOfAClassThatAReaderMayNotViewChangesNothingTheReaderReads( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deniedClassRevision"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("chkCv" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + filterProducts(fixture, FILTER_TEXT); + final OpenMetadataClient reader = + callerWithout( + access, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT, NOT_THE_OWNER); + owns(reader, scene.order()); + final Map before = + new EnumMap<>(OntologyStatementVersion.class); + final Map adminBefore = + new EnumMap<>(OntologyStatementVersion.class); + for (final OntologyStatementVersion version : VERSIONS) { + before.put(version, answer(reader, scene.order(), version)); + adminBefore.put(version, answer(admin(), scene.order(), version)); + } + + filterProducts(fixture, OTHER_FILTER_TEXT); + + for (final OntologyStatementVersion version : VERSIONS) { + assertEquals(before.get(version), answer(reader, scene.order(), version)); + assertNotEquals(adminBefore.get(version), answer(admin(), scene.order(), version)); + } + } + } + + private static void assertAbsent(final String body, final String... texts) { + for (final String text : texts) { + assertFalse(body.contains(text), text + " in " + body); + } + } + @Test void aReaderWhoMayViewEverythingReadsTheBytesAnAdministratorReads(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "allowedReader"); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java index a9d1ebc580f1..9c3d33a81466 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java @@ -35,7 +35,9 @@ import static org.openmetadata.schema.api.data.OntologyShapePart.PATTERN; import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -48,6 +50,10 @@ import org.openmetadata.schema.api.data.OntologyShapeCheckReason; import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; /** @@ -100,12 +106,17 @@ private static OntologyShapeChecks patterns( on(fixture, "pair", "codePair").withPattern("^1.2$"), on(fixture, "digits", "codeDigits").withPattern("^[0-9]+$"), on(fixture, "word", "codeWord").withPattern("^[a-z]+$"), - on(fixture, "mail", "codeMail").withPattern("^[a-z]+\\@[a-z]+\\.org$")); + on(fixture, "mail", "codeMail").withPattern("^[a-z]+@[a-z]+\\.org$")); return checks(admin(), fixture.type("Code"), DRAFT); } private static void assertNoTestOffPostgres(final OntologyShapeChecks checks) { - for (final String constraint : CONSTRAINTS) { + assertNoTestOffPostgres(checks, CONSTRAINTS); + } + + private static void assertNoTestOffPostgres( + final OntologyShapeChecks checks, final List constraints) { + for (final String constraint : constraints) { final OntologyCheckedPart pattern = part(checks, constraint, PATTERN); assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, pattern.getOutcome(), constraint); assertEquals(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED, pattern.getReason(), constraint); @@ -167,6 +178,164 @@ void aPatternCountsTheRecordsWithAValueThatItDoesNotMatch(final TestNamespace ns } } + /** The patterns of {@link #SPELLED} by the id of the constraint, and the column each is about. */ + private static final Map SPELLINGS = + Map.ofEntries( + Map.entry("brien", "^O'Brien$"), + Map.entry("colon", "^a:b$"), + Map.entry("lead", "^:name$"), + Map.entry("mail", "^[^@ ]+@[^@ ]+$"), + Map.entry("tab", "^a\\tb$"), + Map.entry("lines", "^[^\\n\\r]*$"), + Map.entry("drop", "^x'\\); DROP TABLE t; --$"), + Map.entry("or", "^x'\\) OR 1=1 --$"), + Map.entry("slash", "^a\\\\b$"), + Map.entry("dollar", "^\\$1$"), + Map.entry("dot", "^a.b$")); + + private static final List SPELLED = List.copyOf(SPELLINGS.keySet()); + + /** One text column for each pattern of {@link #SPELLINGS}, the column named as the pattern is. */ + private static Shape spelled() { + final List columns = new ArrayList<>(List.of(integer("id"))); + final List properties = new ArrayList<>(); + final List bound = new ArrayList<>(); + for (final String name : SPELLED) { + columns.add(text("col_" + name)); + properties.add(data("spelled" + name, "Spelled")); + bound.add(bound("spelled" + name, "col_" + name)); + } + return mapping( + "spelled", + List.of(table("spelled", columns)), + List.of("Spelled"), + properties, + identityTable( + "Spelled", "spelled", List.of("id"), null, bound.toArray(ColumnBindingSpec[]::new))); + } + + /** A value that matches the pattern of the column, for each column. */ + private static final Map MATCHING = + Map.ofEntries( + Map.entry("brien", "O'Brien"), + Map.entry("colon", "a:b"), + Map.entry("lead", ":name"), + Map.entry("mail", "ada@example.org"), + Map.entry("tab", "a\tb"), + Map.entry("lines", "plain"), + Map.entry("drop", "x'); DROP TABLE t; --"), + Map.entry("or", "x') OR 1=1 --"), + Map.entry("slash", "a\\b"), + Map.entry("dollar", "$1"), + Map.entry("dot", "axb")); + + /** A value that breaks the pattern of the column, for each column. */ + private static final Map BREAKING = + Map.ofEntries( + Map.entry("brien", "OBrien"), + Map.entry("colon", "a b"), + Map.entry("lead", "name"), + Map.entry("mail", "ada.example.org"), + Map.entry("tab", "a b"), + Map.entry("lines", "x\ny"), + Map.entry("drop", "x"), + Map.entry("or", "x"), + Map.entry("slash", "ab"), + Map.entry("dollar", "1"), + Map.entry("dot", "ab")); + + /** A row with this id and a value in each column that {@code byColumn} names, and null in the rest. */ + private static List spelledRow(final int id, final Map byColumn) { + final List values = new ArrayList<>(List.of(id)); + SPELLED.forEach(name -> values.add(byColumn.get(name))); + return row(values.toArray()); + } + + private static OntologyShapeChecks spellings( + final Ontology ontology, final OntologyShapeFixture fixture) { + fixture.bindAll(); + declare( + ontology, + fixture, + "SpelledShape", + "Spelled", + SPELLED.stream() + .map(name -> on(fixture, name, "spelled" + name).withPattern(SPELLINGS.get(name))) + .toArray(OntologyShapeConstraint[]::new)); + return checks(admin(), fixture.type("Spelled"), DRAFT); + } + + @Test + void aPatternWithPunctuationAnEscapeOrAnInjectionCountsTheValuesItDoesNotMatch( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "spelled"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, spelled()).withRows()) { + final OntologyShapeChecks checks = spellings(ontology, fixture); + if (!POSTGRES.equals(fixture.family())) { + assertNoTestOffPostgres(checks, SPELLED); + return; + } + final String spelled = fixture.from("spelled"); + + // Row 1 matches every pattern and row 2 breaks every one. Rows 3 and 4 hold a line feed and a + // carriage return in the one column that allows anything else, and rows 5 and 6 in the + // column whose dot stands for every character but those. Row 7 holds a backslash and a t + // where the tab pattern wants a tab. A column of null is no violation. + addRows( + fixture, + "spelled", + spelledRow(1, MATCHING), + spelledRow(2, BREAKING), + spelledRow(3, Map.of("lines", "a\nb")), + spelledRow(4, Map.of("lines", "a\rb")), + spelledRow(5, Map.of("dot", "a\nb")), + spelledRow(6, Map.of("dot", "a\rb")), + spelledRow(7, Map.of("tab", "a\\tb"))); + final String rows = "SELECT COUNT(*) FROM " + spelled; + assertEquals(List.of(List.of("7")), OntologyShapeFixture.run(rows)); + + final Map>> violating = + Map.of( + "tab", List.of(List.of("2"), List.of("7")), + "lines", List.of(List.of("2"), List.of("3"), List.of("4")), + "dot", List.of(List.of("2"), List.of("5"), List.of("6"))); + for (final String name : SPELLED) { + final List> keys = violating.getOrDefault(name, List.of(List.of("2"))); + assertCounts(String.valueOf(keys.size()), keys, check(checks, name, PATTERN)); + } + assertEquals(List.of(List.of("7")), OntologyShapeFixture.run(rows)); + } + } + + @Test + void anEscapeThatXPathRefusesIsNotEnforceableWithNoStatement(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "refused"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, CODES).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "RefusedShape", + "Code", + on(fixture, "quote", "codePair").withPattern("^O\\'Brien$"), + on(fixture, "colon", "codeDigits").withPattern("^a\\:b$"), + on(fixture, "at", "codeMail").withPattern("^\\@$")); + final OntologyShapeChecks checks = checks(admin(), fixture.type("Code"), DRAFT); + for (final String constraint : List.of("quote", "colon", "at")) { + final OntologyCheckedPart pattern = part(checks, constraint, PATTERN); + assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, pattern.getOutcome(), constraint); + assertEquals( + POSTGRES.equals(fixture.family()) + ? OntologyShapeCheckReason.PATTERN_NOT_PORTABLE + : OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED, + pattern.getReason(), + constraint); + assertNull(pattern.getChecks(), constraint); + } + } + } + @Test void aPatternReadsARangeByCodePointWhateverTheCollationOfItsColumn(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "collated"); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index f822d1fe7935..b5f30b761c6e 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -87,9 +87,9 @@ class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { " lock in share mode"); /** Every statement of one read of the draft, as an administrator, and of the active release. */ - private static final int DRAFT_STATEMENTS = 46; + private static final int DRAFT_STATEMENTS = 48; - private static final int RELEASE_STATEMENTS = 52; + private static final int RELEASE_STATEMENTS = 56; /** A shape holds at most this many of the constraints that a test declares. */ private static final int CONSTRAINTS_OF_A_SHAPE = 5; @@ -145,6 +145,69 @@ private static Shape orders(final String name, final int notes) { bindings.toArray(BindingSpec[]::new)); } + /** Constraints that a shape on {@link #targets} holds, as many as the targets are asked to name. */ + private static final int CONSTRAINTS_ON_TARGETS = 8; + + /** + * An order class that reaches {@code classes} other classes, each through a table of its own and + * each with an identity table of its own, so every relation can state a {@code class} part. + */ + private static Shape targets(final String name, final int classes) { + final List tables = + new ArrayList<>(List.of(table(name + "_orders", List.of(integer("id"), text("channel"))))); + final List types = new ArrayList<>(List.of("Order")); + final List properties = new ArrayList<>(List.of(data("orderChannel", "Order"))); + final List bindings = + new ArrayList<>( + List.of( + identityTable( + "Order", + name + "_orders", + List.of("id"), + null, + bound("orderChannel", "channel")))); + for (int target = 0; target < classes; target++) { + tables.add(table(name + "_targets" + target, List.of(text("sku"), text("title")))); + tables.add(table(name + "_links" + target, List.of(integer("order_id"), text("sku")))); + types.add("Target" + target); + properties.add(data("title" + target, "Target" + target)); + properties.add(relation("reaches" + target, "Order", "Target" + target)); + bindings.add( + identityTable( + "Target" + target, + name + "_targets" + target, + List.of("sku"), + null, + bound("title" + target, "title"))); + bindings.add( + contributing( + "Order", + name + "_links" + target, + List.of("order_id"), + joined("reaches" + target, "sku", name + "_targets" + target, "sku"))); + } + return mapping(name, tables, types, properties, bindings.toArray(BindingSpec[]::new)); + } + + /** + * One shape of the order class with eight {@code class} constraints, which name {@code named} + * distinct classes among them. + */ + private static void declareClassParts( + final Ontology ontology, final OntologyShapeFixture fixture, final int named) { + declare( + ontology, + fixture, + "Targets", + "Order", + IntStream.range(0, CONSTRAINTS_ON_TARGETS) + .mapToObj( + constraint -> + on(fixture, "class" + constraint, "reaches" + constraint % named) + .withClassIri(fixture.type("Target" + constraint % named).getIri())) + .toArray(OntologyShapeConstraint[]::new)); + } + /** The statements of one request, as the server rendered them. */ private record Reads(OntologyShapeChecks answer, List statements) { long of(final String fragment) { @@ -363,6 +426,57 @@ void aReleaseOfTwelveTablesWithFortyConstraintsIsReadInTheStatementsOfAnyRelease assertReleaseReads(twelve); } + @Test + void aDraftWhoseClassPartsNameOneClassIsReadInTheStatementsOfEight(final TestNamespace ns) { + final Reads one = classParts(ns, "oneTarget", 1, DRAFT); + + assertEquals(List.of(1, 8, 3), sizes(one)); + assertEquals(DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertDraftReads(one); + } + + @Test + void aDraftWhoseClassPartsNameEightClassesIsReadInTheStatementsOfOne(final TestNamespace ns) { + final Reads eight = classParts(ns, "eightTargets", 8, DRAFT); + + assertEquals(List.of(1, 8, 17), sizes(eight)); + assertEquals(DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertDraftReads(eight); + } + + @Test + void aReleaseWhoseClassPartsNameOneClassIsReadInTheStatementsOfEight(final TestNamespace ns) { + final Reads one = classParts(ns, "oneTarget", 1, RELEASE); + + assertEquals(List.of(1, 8, 3), sizes(one)); + assertReleaseReads(one, RELEASE_STATEMENTS); + } + + @Test + void aReleaseWhoseClassPartsNameEightClassesIsReadInTheStatementsOfOne(final TestNamespace ns) { + final Reads eight = classParts(ns, "eightTargets", 8, RELEASE); + + assertEquals(List.of(1, 8, 17), sizes(eight)); + assertReleaseReads(eight, RELEASE_STATEMENTS); + } + + /** The statements of a read of an order class whose class parts name {@code named} classes. */ + private static Reads classParts( + final TestNamespace ns, + final String name, + final int named, + final OntologyStatementVersion version) { + final Ontology ontology = createOntology(ns, name + version.value()); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, targets(name, 8))) { + fixture.bindAll(); + declareClassParts(ontology, fixture, named); + if (version == RELEASE) { + activate(ns, ontology); + } + return reads(fixture, version); + } + } + /** The statements of a read of the draft of an order class with this many constraints. */ private static Reads drafted( final TestNamespace ns, final String name, final int notes, final int constraints) { @@ -388,17 +502,21 @@ private static Reads released( } } - /** A draft reads the shapes and the properties twice: as rows, then for the right to view. */ + /** A draft reads the shapes and the properties once, and authorizes the rows it read. */ private static void assertDraftReads(final Reads reads) { - assertEquals(2, reads.of(SHAPES), reads::listed); - assertEquals(2, reads.of(PROPERTIES), reads::listed); + assertEquals(1, reads.of(SHAPES), reads::listed); + assertEquals(1, reads.of(PROPERTIES), reads::listed); assertEquals(2, reads.of(BINDING_ROWS), reads::listed); assertEquals(0, reads.of(RELEASE_MEMBERS), reads::listed); assertNoLock(reads); } private static void assertReleaseReads(final Reads reads) { - assertEquals(RELEASE_STATEMENTS, reads.statements().size(), reads::listed); + assertReleaseReads(reads, RELEASE_STATEMENTS); + } + + private static void assertReleaseReads(final Reads reads, final int statements) { + assertEquals(statements, reads.statements().size(), reads::listed); assertEquals(0, reads.of(SHAPES), reads::listed); assertEquals(1, reads.of(PROPERTIES), reads::listed); assertEquals(2, reads.of(BINDING_ROWS), reads::listed); From 15f1573c2794b55ae6e7a972119f95d83b8997c7 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 25 Nov 2026 22:30:57 -0800 Subject: [PATCH 092/203] Read the binding rows of every filtered class table in one statement --- .../it/tests/OntologyShapeCheckReadsIT.java | 83 +++++++++++++++++-- .../jdbi3/OntologyConceptBindingDAO.java | 13 +++ .../jdbi3/OntologyConceptBindingStore.java | 9 ++ .../ontology/OntologyShapeCheckReader.java | 50 +++++++---- .../service/ontology/OntologyVersion.java | 58 +++++++++---- 5 files changed, 175 insertions(+), 38 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index b5f30b761c6e..15c4dceca0dd 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -52,10 +52,12 @@ import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.api.data.OntologyStatementVersion; import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.Entity; import org.openmetadata.service.monitoring.RequestLatencyContext; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; @@ -91,6 +93,18 @@ class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { private static final int RELEASE_STATEMENTS = 56; + /** + * The same reads when the identity binding of every class a part names has a row filter. The + * filter costs one statement that reads the binding rows of all those tables, and the count does + * not depend on how many classes are named. + */ + private static final int FILTERED_DRAFT_STATEMENTS = DRAFT_STATEMENTS + 1; + + private static final int FILTERED_RELEASE_STATEMENTS = RELEASE_STATEMENTS + 1; + + private static final FilterSpec NOT_X = + new FilterSpec("title", OntologyRowFilterOperator.NOT_EQUALS, "x"); + /** A shape holds at most this many of the constraints that a test declares. */ private static final int CONSTRAINTS_OF_A_SHAPE = 5; @@ -152,7 +166,7 @@ private static Shape orders(final String name, final int notes) { * An order class that reaches {@code classes} other classes, each through a table of its own and * each with an identity table of its own, so every relation can state a {@code class} part. */ - private static Shape targets(final String name, final int classes) { + private static Shape targets(final String name, final int classes, final FilterSpec filter) { final List tables = new ArrayList<>(List.of(table(name + "_orders", List.of(integer("id"), text("channel"))))); final List types = new ArrayList<>(List.of("Order")); @@ -177,7 +191,7 @@ private static Shape targets(final String name, final int classes) { "Target" + target, name + "_targets" + target, List.of("sku"), - null, + filter, bound("title" + target, "title"))); bindings.add( contributing( @@ -460,14 +474,62 @@ void aReleaseWhoseClassPartsNameEightClassesIsReadInTheStatementsOfOne(final Tes assertReleaseReads(eight, RELEASE_STATEMENTS); } - /** The statements of a read of an order class whose class parts name {@code named} classes. */ + @Test + void aDraftWhoseFilteredClassPartsNameOneClassIsReadInTheStatementsOfEight( + final TestNamespace ns) { + final Reads one = classParts(ns, "oneFiltered", 1, DRAFT, NOT_X); + + assertEquals(List.of(1, 8, 3), sizes(one)); + assertEquals(FILTERED_DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertDraftReads(one, 3); + } + + @Test + void aDraftWhoseFilteredClassPartsNameEightClassesIsReadInTheStatementsOfOne( + final TestNamespace ns) { + final Reads eight = classParts(ns, "eightFiltered", 8, DRAFT, NOT_X); + + assertEquals(List.of(1, 8, 17), sizes(eight)); + assertEquals(FILTERED_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertDraftReads(eight, 3); + } + + @Test + void aReleaseWhoseFilteredClassPartsNameOneClassIsReadInTheStatementsOfEight( + final TestNamespace ns) { + final Reads one = classParts(ns, "oneFiltered", 1, RELEASE, NOT_X); + + assertEquals(List.of(1, 8, 3), sizes(one)); + assertReleaseReads(one, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWhoseFilteredClassPartsNameEightClassesIsReadInTheStatementsOfOne( + final TestNamespace ns) { + final Reads eight = classParts(ns, "eightFiltered", 8, RELEASE, NOT_X); + + assertEquals(List.of(1, 8, 17), sizes(eight)); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + private static Reads classParts( final TestNamespace ns, final String name, final int named, final OntologyStatementVersion version) { + return classParts(ns, name, named, version, null); + } + + /** The statements of a read of an order class whose class parts name {@code named} classes. */ + private static Reads classParts( + final TestNamespace ns, + final String name, + final int named, + final OntologyStatementVersion version, + final FilterSpec filter) { final Ontology ontology = createOntology(ns, name + version.value()); - try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, targets(name, 8))) { + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, targets(name, 8, filter))) { fixture.bindAll(); declareClassParts(ontology, fixture, named); if (version == RELEASE) { @@ -504,9 +566,13 @@ private static Reads released( /** A draft reads the shapes and the properties once, and authorizes the rows it read. */ private static void assertDraftReads(final Reads reads) { + assertDraftReads(reads, 2); + } + + private static void assertDraftReads(final Reads reads, final int bindingReads) { assertEquals(1, reads.of(SHAPES), reads::listed); assertEquals(1, reads.of(PROPERTIES), reads::listed); - assertEquals(2, reads.of(BINDING_ROWS), reads::listed); + assertEquals(bindingReads, reads.of(BINDING_ROWS), reads::listed); assertEquals(0, reads.of(RELEASE_MEMBERS), reads::listed); assertNoLock(reads); } @@ -516,10 +582,15 @@ private static void assertReleaseReads(final Reads reads) { } private static void assertReleaseReads(final Reads reads, final int statements) { + assertReleaseReads(reads, statements, 2); + } + + private static void assertReleaseReads( + final Reads reads, final int statements, final int bindingReads) { assertEquals(statements, reads.statements().size(), reads::listed); assertEquals(0, reads.of(SHAPES), reads::listed); assertEquals(1, reads.of(PROPERTIES), reads::listed); - assertEquals(2, reads.of(BINDING_ROWS), reads::listed); + assertEquals(bindingReads, reads.of(BINDING_ROWS), reads::listed); assertEquals(4, reads.of(RELEASE_MEMBERS), reads::listed); assertNoLock(reads); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java index b1aaa8329b5a..c4fbd6646d62 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java @@ -163,6 +163,19 @@ void deleteAssets( List listForAssetAfter( @BindUUID("assetId") UUID assetId, @Bind("after") String after, @Bind("limit") int limit); + /** The first {@code perAsset} rows of each asset in concept id order, in one statement. */ + @SqlQuery( + "SELECT " + + COLUMNS + + " FROM (SELECT " + + COLUMNS + + ", ROW_NUMBER() OVER (PARTITION BY assetId ORDER BY conceptId ASC) AS bindingOrder " + + "FROM ontology_concept_binding WHERE assetId IN ()) ranked " + + "WHERE bindingOrder <= :perAsset ORDER BY assetId ASC, conceptId ASC") + @RegisterRowMapper(BindingRowMapper.class) + List listFirstForAssets( + @BindList("assetIds") List assetIds, @Bind("perAsset") int perAsset); + @SqlQuery( "SELECT " + COLUMNS diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 3a9010bde2f6..529c65f7ce10 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -119,6 +119,15 @@ public List forAssetAfter(final UUID assetId, final UUID after, fina .listForAssetAfter(assetId, after == null ? FIRST_PAGE : after.toString(), limit); } + /** The first {@code perAsset} bindings of each of these assets in concept id order. */ + public List firstForAssets(final Collection assetIds, final int perAsset) { + return assetIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + assetIds.stream().map(UUID::toString).distinct().toList(), + chunk -> dao.ontologyConceptBindingDAO().listFirstForAssets(chunk, perAsset)); + } + public List page(final UUID conceptId, final UUID after, final int limit) { return dao.ontologyConceptBindingDAO() .listAfter(conceptId, after == null ? FIRST_PAGE : after.toString(), limit); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java index 4ddc5749a519..fa8a97c5508b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java @@ -318,28 +318,48 @@ private Set sharing( final Asked asked, final Collection classes, final Map identity) { + final List filtered = + classes.stream() + .filter(type -> identity.get(type.getId()) != null) + .filter(type -> identity.get(type.getId()).rowFilter() != null) + .toList(); + final Map> byTable = + store + .firstForAssets( + filtered.stream().map(type -> identity.get(type.getId()).assetId()).toList(), + MOST_CLASSES_ON_A_TABLE + 1) + .stream() + .collect(Collectors.groupingBy(BindingRow::assetId)); final Set sharing = new HashSet<>(); - for (final OntologyConcept type : classes) { - final BindingRow row = identity.get(type.getId()); - if (row != null && row.rowFilter() != null && sharesTable(asked, type, row)) { + final Map> asking = new HashMap<>(); + for (final OntologyConcept type : filtered) { + final List onTable = + byTable.getOrDefault(identity.get(type.getId()).assetId(), List.of()); + if (onTable.size() > MOST_CLASSES_ON_A_TABLE) { sharing.add(type.getId()); + } else { + final List others = identityOthers(onTable, type.getId()); + if (!others.isEmpty()) { + asking.put(type.getIri(), others); + } } } + final Set subclassed = + asking.isEmpty() + ? Set.of() + : asked.version().withSubclassAmong(store, asked.ontologyId(), asking); + filtered.stream() + .filter(type -> subclassed.contains(type.getIri())) + .forEach(type -> sharing.add(type.getId())); return sharing; } - private boolean sharesTable(final Asked asked, final OntologyConcept type, final BindingRow row) { - final List onTable = - store.forAssetAfter(row.assetId(), null, MOST_CLASSES_ON_A_TABLE + 1); - final List others = - onTable.stream() - .filter(other -> other.role() == OntologyBindingRole.IDENTITY) - .map(BindingRow::conceptId) - .filter(id -> !id.equals(type.getId())) - .toList(); - return onTable.size() > MOST_CLASSES_ON_A_TABLE - || (!others.isEmpty() - && asked.version().anySubclassOf(store, asked.ontologyId(), others, type.getIri())); + private static List identityOthers(final List onTable, final UUID self) { + return onTable.stream() + .filter(other -> other.role() == OntologyBindingRole.IDENTITY) + .map(BindingRow::conceptId) + .filter(id -> !id.equals(self)) + .toList(); } /** The id of every table an answer can rest on or name. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java index 9550b3dbe001..cd892eb8a79a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -125,11 +125,14 @@ List classesNamed( OntologyConceptBindingStore store, UUID ontologyId, Collection iris); /** - * True when this version declares one of the classes {@code candidates} as a subclass of the - * class {@code iri}, however many named subclass steps apart. + * The IRIs among the keys of {@code candidatesByIri} for which this version declares one of the + * classes in the entry as a subclass of the class with that IRI, however many named subclass + * steps apart. All the entries are answered together, so the statements do not grow with them. */ - boolean anySubclassOf( - OntologyConceptBindingStore store, UUID ontologyId, Collection candidates, URI iri); + Set withSubclassAmong( + OntologyConceptBindingStore store, + UUID ontologyId, + Map> candidatesByIri); /** The active release of {@code ontology}, or a 404 that says it has none. */ static OntologyVersion release(final CollectionDAO dao, final EntityReference ontology) { @@ -222,14 +225,26 @@ public List classesNamed( } @Override - public boolean anySubclassOf( + public Set withSubclassAmong( final OntologyConceptBindingStore store, final UUID ontologyId, - final Collection candidates, - final URI iri) { - return store.liveConcepts(candidates).stream() + final Map> candidatesByIri) { + final Map> ancestors = new HashMap<>(); + store + .liveConcepts( + candidatesByIri.values().stream().flatMap(Collection::stream).distinct().toList()) + .stream() .filter(candidate -> ontologyId.equals(candidate.getOntology().getId())) - .anyMatch(candidate -> store.ancestors(candidate).contains(iri.toString())); + .forEach(candidate -> ancestors.put(candidate.getId(), store.ancestors(candidate))); + return candidatesByIri.entrySet().stream() + .filter( + entry -> + entry.getValue().stream() + .map(ancestors::get) + .anyMatch( + found -> found != null && found.contains(entry.getKey().toString()))) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } } @@ -316,24 +331,33 @@ public List classesNamed( * whole read of a sealed release shares. */ @Override - public boolean anySubclassOf( + public Set withSubclassAmong( final OntologyConceptBindingStore store, final UUID ontologyId, - final Collection candidates, - final URI iri) { + final Map> candidatesByIri) { final List members = new OntologyReleaseReader(dao) .read(release, unchecked -> {}).stream() .map(member -> OntologyReleaseReader.definition(release, member)) .toList(); - final Set starts = + final List classes = members.stream() .filter(OntologyConcept.class::isInstance) .map(OntologyConcept.class::cast) - .filter(type -> candidates.contains(type.getId())) - .map(type -> type.getIri().toString()) - .collect(Collectors.toSet()); - return reaches(namedParents(members), starts, iri.toString()); + .toList(); + final Map> parents = namedParents(members); + return candidatesByIri.entrySet().stream() + .filter( + entry -> + reaches( + parents, + classes.stream() + .filter(type -> entry.getValue().contains(type.getId())) + .map(type -> type.getIri().toString()) + .collect(Collectors.toSet()), + entry.getKey().toString())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } /** The named parents that the subclass axioms give each class, by the IRI of the class. */ From 7cd349a2cf4b59664ec6a7d18e75cd7879bd703b Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 25 Nov 2026 22:31:03 -0800 Subject: [PATCH 093/203] Test that a release authorizes its classes against the released rows --- .../OntologyShapeCheckDefinitionRightsIT.java | 39 +++++++++++++++++++ .../OntologyShapeCheckReaderTest.java | 16 ++++++++ 2 files changed, 55 insertions(+) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java index de3cd95c43b8..5407b9df2921 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java @@ -490,4 +490,43 @@ void aReleasedShapeIsReadAsReleasedAfterItsWorkingRowIsDeleted(final TestNamespa .toList()); } } + + @Test + void aReleasedClassPartIsReadAsReleasedAfterItsClassIsDeleted(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("chkClD" + ns.shortPrefix())) { + fixture.bindAll(); + fixture.bind( + new BindingSpec( + "Stock", "products", OntologyBindingRole.IDENTITY, List.of("sku"), null, List.of())); + final OntologyConcept stock = fixture.type("Stock"); + final OntologyShape shape = + declare( + ontology, + fixture, + ORDER_SHAPE, + "Order", + on(fixture, "onStock", "contains").withClassIri(stock.getIri())); + final OpenMetadataClient owner = + callerWithout( + access, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT, NOT_THE_OWNER); + owns(owner, fixture.type("Order")); + owns(owner, stock); + activate(ns, ontology); + final String ownerRead = answer(owner, fixture.type("Order"), RELEASE); + final String everyoneRead = answer(admin(), fixture.type("Order"), RELEASE); + assertEquals( + OntologyShapeCheckOutcome.CHECK, + parts(checks(owner, fixture.type("Order"), RELEASE), "onStock", CLASS) + .getFirst() + .getOutcome()); + + admin().ontologyShapes().delete(shape.getId().toString()); + admin().ontologyConcepts().delete(stock.getId().toString()); + + assertEquals(ownerRead, answer(owner, fixture.type("Order"), RELEASE)); + assertEquals(everyoneRead, answer(admin(), fixture.type("Order"), RELEASE)); + } + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java index 199045acc28f..ecb554578369 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java @@ -25,6 +25,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import jakarta.ws.rs.ClientErrorException; @@ -320,6 +321,21 @@ void theShapesOfAReleaseAreReadFromEveryPageOfItsMembers() { .toList()); } + @Test + void aReleaseAuthorizesTheClassRowsItWasGivenAndNotTheirIds() { + final OntologyConcept released = + new OntologyConcept().withId(new UUID(4, 1)).withIri(PRODUCT_IRI); + when(catalog.viewable(null, Entity.ONTOLOGY_CONCEPT, List.of(released))) + .thenReturn(Map.of(released.getId(), released)); + + final Set viewable = + release(List.of()).viewable(catalog, null, Entity.ONTOLOGY_CONCEPT, List.of(released)); + + assertEquals(Set.of(released.getId()), viewable); + verify(catalog).viewable(null, Entity.ONTOLOGY_CONCEPT, List.of(released)); + verifyNoMoreInteractions(catalog); + } + /** A sealed release whose shape members are {@code shapes}, listed a page at a time by id. */ private static OntologyVersion release(final List shapes) { final OntologyReleaseDAO releases = mock(OntologyReleaseDAO.class); From b19e19ccf886b4be7f0d57cbf11a9291418732c5 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 25 Nov 2026 22:31:07 -0800 Subject: [PATCH 094/203] Correct what the shape check record says the hydration loads, and state the filtered counts --- ...ape-check-is-exact-or-it-is-not-offered.md | 47 +++++++++++++------ 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index 23a103d4ef30..4cbebb2b6031 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -1,7 +1,7 @@ # A shape check is exact or it is not offered - **Status:** Accepted -- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) +- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) · v4 2026-11-25 (the statements do not grow with the classes a `class` part names, a filtered one included) - **Deciders:** Ontology Studio maintainers - **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads) - **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) @@ -265,21 +265,31 @@ after three attempts it answers 409. So every row that a check was compiled from revision the check names. A binding that does not exist has no revision to name: a subclass that binds the filtered table later changes the answer, and a caller sees it when it asks again. -**Each kind of input is read once.** After the class and the version, one request reads the shapes -that target the class, the properties their constraints name, the classes their `class` parts -name, the binding rows, and the tables those rows name. It checks the caller's right to view once -for the shapes, once for the properties and once for the tables. The number of statements does not -grow with the number of shapes, of constraints or of tables. An administrator's request runs 48 -`SELECT` statements from the draft and 56 from a release, and no statement locks the rows it reads. -`OntologyShapeCheckReadsIT` counts those two numbers for 1, 40 and 80 constraints on a class of 6 +**Each kind of input is read once.** After the class and the version, one request reads the +shapes that target the class, the properties their constraints name, the classes their `class` +parts name, the binding rows, and the tables those rows name. It checks the caller's right to view +once for the shapes, once for the properties and once for the tables. The number of statements does +not grow with the number of shapes, of constraints, of tables or of named classes. An +administrator's request runs 48 `SELECT` statements from the draft and 56 from a release, and no +statement locks the rows it reads. A `class` part whose class has a row filter on its identity +binding adds one statement that reads the binding rows of every such table together, with the +first 101 rows of each table, so those requests run 49 and 57 whether the parts name 1 class or 8. +When another class has its identity binding on one of those tables, one more question asks the +version once for all the classes that have a subclass there. + +`OntologyShapeCheckReadsIT` counts those numbers for 1, 40 and 80 constraints on a class of 6 tables, for 40 constraints on a class of 3 tables and of 12, and for `class` parts that name 1 -class and 8 classes, and it finds no locking read in any request. A draft reads the shapes once and the properties once, and authorizes the rows it read, with no -second read of them. The check of the right to view reads the owners and the domains of the rows -it checks, and the compile reads none of the other fields that the check clears. A second read -would let a row that changed between the two be compiled from one version and authorized from the -other. A server setting whose cached value has lapsed is read on top of the statements. Two questions cost further -reads, and only when a constraint asks them: the declared inverse of a relation that the class -binds nowhere, and a subclass on a filtered identity table that a `class` part arrives at. +class and 8 classes, with and without a row filter on the identity bindings of those classes. It +finds no locking read in any request. + +A draft reads the shapes once and the properties once, and authorizes the rows it read, with no +second read of them. The check of the right to view loads the owners, the domains, the reviewers +and the certification of the rows it checks, where the repository supports them, and the compile +reads none of the other fields that the check clears. A second read would let a row that changed +between the two be compiled from one version and authorized from the other. A server setting whose +cached value has lapsed is read on top of the statements. Two questions cost further reads, and +only when a constraint asks them: the declared inverse of a relation that the class binds nowhere, +and a subclass on a filtered identity table that a `class` part arrives at. **An answer is whole or it is refused.** A class that binds more than 100 tables, and a draft class that more than 1,000 shapes name, get 409. The draft cap counts every live shape that names @@ -364,3 +374,10 @@ v3 (2026-11-24): three things changed. taken and `^a\:b$` is refused. Postgres 15 reads each of these as XPath does. - A draft authorizes the shape, property and class rows it read and reads none of them again. The statements are 48 from a draft and 56 from a release, where they were 46 and 52. + +v4 (2026-11-25): the statements of a request do not grow with the number of classes that `class` +parts name. The first read of the filtered identity tables ran one statement for each such class, +and another for each class that shared the table. It now reads the binding rows of all those tables +in one statement and asks the version once for every class that may have a subclass there. A +request with filtered identity bindings runs 49 statements from a draft and 57 from a release, +for 1 named class and for 8. From 038fafdf075a9350eba555d896d8ba3584e74b54 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 25 Nov 2026 22:32:46 -0800 Subject: [PATCH 095/203] Test that filtered classes cost one read of the rows and one question for their subclasses --- .../OntologyShapeCheckReaderTest.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java index ecb554578369..18442325be4c 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java @@ -54,6 +54,8 @@ import org.openmetadata.schema.type.OntologyPropertyKind; import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -165,6 +167,62 @@ void aBindingWriteOfAClassThatAPartNamesMakesTheReaderReadTheRowsAgain() { verify(store, times(2)).identityRows(List.of(PERSON)); } + @Test + void filteredClassesAreReadForTheirSubclassesInOneReadOfTheRowsAndOneQuestion() { + final UUID placer = new UUID(5, 1); + final UUID buyer = new UUID(5, 2); + final URI placerIri = URI.create("https://example.org/shop#Placer"); + final URI buyerIri = URI.create("https://example.org/shop#Buyer"); + final OntologyConcept subOfPerson = + new OntologyConcept() + .withId(placer) + .withIri(placerIri) + .withOntology(new EntityReference().withId(ONTOLOGY)); + final OntologyConcept unrelated = + new OntologyConcept() + .withId(buyer) + .withIri(buyerIri) + .withOntology(new EntityReference().withId(ONTOLOGY)); + final BindingRow person = filtered(PERSON, 2, OntologyBindingRole.IDENTITY); + final BindingRow product = filtered(new UUID(4, 1), 3, OntologyBindingRole.IDENTITY); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn( + List.of( + shape( + 1, + "a", + ORDER_IRI, + on(PLACED_BY_IRI).withClassIri(PERSON_IRI), + on(CHANNEL_IRI).withId("c2").withClassIri(PRODUCT_IRI)))); + when(store.liveConcepts(ONTOLOGY, Set.of(PERSON_IRI, PRODUCT_IRI))) + .thenReturn( + List.of( + new OntologyConcept().withId(PERSON).withIri(PERSON_IRI), + new OntologyConcept().withId(product.conceptId()).withIri(PRODUCT_IRI))); + when(store.identityFirstTables(List.of(ORDER), 101)) + .thenReturn(List.of(row(1, OntologyBindingRole.IDENTITY))); + when(store.identityRows(anyCollection())).thenReturn(List.of(person, product)); + when(store.firstForAssets(anyCollection(), eq(101))) + .thenReturn( + List.of( + person, + row(placer, 2, OntologyBindingRole.IDENTITY), + product, + row(buyer, 3, OntologyBindingRole.IDENTITY))); + when(store.liveConcepts(ArgumentMatchers.>any())) + .thenReturn(List.of(subOfPerson, unrelated)); + when(store.ancestors(subOfPerson)) + .thenReturn(Set.of(placerIri.toString(), PERSON_IRI.toString())); + when(store.ancestors(unrelated)).thenReturn(Set.of(buyerIri.toString())); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(true, read.facts().targets().get(PERSON_IRI).subclassSharesTable()); + assertEquals(false, read.facts().targets().get(PRODUCT_IRI).subclassSharesTable()); + verify(store, times(1)).firstForAssets(anyCollection(), eq(101)); + verify(store, times(1)).liveConcepts(ArgumentMatchers.>any()); + } + @Test void bindingsThatChangeOnEveryReadGiveNoAnswer() { when(store.revisions(anyCollection())) @@ -397,6 +455,23 @@ private static BindingRow row(final int table, final OntologyBindingRole role) { return row(ORDER, table, role); } + private static BindingRow filtered( + final UUID type, final int table, final OntologyBindingRole role) { + final BindingRow plain = row(type, table, role); + return new BindingRow( + plain.conceptId(), + plain.assetId(), + plain.assetType(), + plain.assetFqnHash(), + plain.columns(), + plain.role(), + plain.subjectKey(), + new OntologyRowFilter() + .withColumn(List.of("title")) + .withOperator(OntologyRowFilterOperator.NOT_EQUALS) + .withValue("x")); + } + private static BindingRow row(final UUID type, final int table, final OntologyBindingRole role) { return new BindingRow( type, From f8c211a64b20f92d8d7143450f3957ef2795ba70 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 08:22:16 -0800 Subject: [PATCH 096/203] Walk the ancestors of every class that shares a filtered table together A draft asks which named classes have a subclass on a filtered table with one statement per level over the whole frontier, then decides each class in memory with the helper a release uses. Binding inheritance reads its ancestors through the same walk. --- .../OntologyConceptBindingFirstRowsIT.java | 116 ++++++ .../it/tests/OntologyShapeCheckAnswerIT.java | 85 +++++ .../it/tests/OntologyShapeCheckFixtures.java | 42 +++ .../it/tests/OntologyShapeCheckReadsIT.java | 339 +++++++++++++++--- .../jdbi3/OntologyConceptBindingStore.java | 45 ++- .../ontology/OntologyClassHierarchy.java | 20 +- .../service/ontology/OntologyVersion.java | 67 ++-- .../OntologyShapeCheckReaderTest.java | 6 +- 8 files changed, 615 insertions(+), 105 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingFirstRowsIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingFirstRowsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingFirstRowsIT.java new file mode 100644 index 000000000000..2e8a4dac74e5 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingFirstRowsIT.java @@ -0,0 +1,116 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.EntityDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; + +/** + * The first rows of many tables, read in one call, are the first rows of each table read on its + * own: the cap counts the rows of one table, never of all of them. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyConceptBindingFirstRowsIT extends BaseOntologyApprovalIT { + private static final int CAP = 101; + private static final List TABLE_SIZES = List.of(150, 5, 101, 102); + private static final List ROLES = List.of("identity", "contributing", ""); + + @Test + void theFirstRowsOfSeveralTablesAreTheFirstRowsOfEachTableOnItsOwn() { + final OntologyConceptBindingDAO dao = Entity.getCollectionDAO().ontologyConceptBindingDAO(); + final OntologyConceptBindingStore store = + new OntologyConceptBindingStore(Entity.getCollectionDAO(), type -> "table_entity"); + final Map> written = new LinkedHashMap<>(); + TABLE_SIZES.forEach(size -> written.put(UUID.randomUUID(), new ArrayList<>())); + try { + writeRows(dao, written); + final List tables = List.copyOf(written.keySet()); + + assertEachTableReadsAsItDoesOnItsOwn(dao, grouped(store.firstForAssets(tables, CAP)), tables); + + final Map> acrossTwoChunks = + grouped(store.firstForAssets(idsSplitOverTwoChunks(tables), CAP)); + assertEachTableReadsAsItDoesOnItsOwn(dao, acrossTwoChunks, tables); + assertEquals( + List.of(CAP, 5, CAP, CAP), + tables.stream().map(t -> acrossTwoChunks.get(t).size()).toList()); + } finally { + written.forEach((table, concepts) -> concepts.forEach(concept -> dao.delete(concept, table))); + } + } + + private static void writeRows( + final OntologyConceptBindingDAO dao, final Map> written) { + final List tables = List.copyOf(written.keySet()); + for (int table = 0; table < tables.size(); table++) { + for (int row = 0; row < TABLE_SIZES.get(table); row++) { + final UUID concept = UUID.randomUUID(); + final String role = ROLES.get(row % ROLES.size()); + dao.upsert( + new StoredBinding( + concept.toString(), + tables.get(table).toString(), + "table", + "firstRows" + row, + "[]", + role.isEmpty() ? null : role, + null, + null)); + written.get(tables.get(table)).add(concept); + } + } + } + + /** Ids of the four tables, with enough others between them that a chunk ends between the two pairs. */ + private static List idsSplitOverTwoChunks(final List tables) { + final List ids = new ArrayList<>(List.of(tables.get(0), tables.get(2))); + IntStream.range(0, EntityDAO.MAX_IN_LIST_CHUNK_SIZE - 2) + .forEach(i -> ids.add(UUID.randomUUID())); + ids.add(tables.get(1)); + ids.add(tables.get(3)); + return ids; + } + + private static void assertEachTableReadsAsItDoesOnItsOwn( + final OntologyConceptBindingDAO dao, + final Map> together, + final List tables) { + for (final UUID table : tables) { + final List alone = dao.listForAssetAfter(table, "", CAP); + assertEquals(alone, together.get(table), "table " + table); + } + } + + private static Map> grouped(final List rows) { + return rows.stream() + .collect( + Collectors.groupingBy(BindingRow::assetId, LinkedHashMap::new, Collectors.toList())); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java index 52d9042661e4..e67e8ad44adc 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java @@ -44,6 +44,7 @@ import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.reference; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.row; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.targets; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.CHECK; import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.HELD_BY_MAPPING; @@ -58,6 +59,7 @@ import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.NOT_EQUALS; import java.net.URI; import java.util.List; @@ -76,6 +78,7 @@ import org.openmetadata.schema.api.data.OntologyShapeCheckReason; import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; import org.openmetadata.schema.api.data.OntologyStatementVersionRead; import org.openmetadata.schema.entity.data.Ontology; import org.openmetadata.schema.entity.data.OntologyAxiom; @@ -84,6 +87,7 @@ import org.openmetadata.schema.entity.data.OntologyRelease; import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyExpression; import org.openmetadata.schema.type.OntologyExpressionKind; import org.openmetadata.schema.type.OntologyPropertyKind; @@ -92,6 +96,8 @@ import org.openmetadata.schema.type.RelationProvenance; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; /** @@ -407,6 +413,85 @@ void aSubclassOnTheFilteredTableOfTheNamedClassLeavesNoExactTest(final TestNames } } + @Test + void aCrowdOnOneFilteredTableOfADraftDoesNotHideASubclassOnAnotherFromTheCap( + final TestNamespace ns) { + assertBothClassPartsShareTheirTables(ns, DRAFT); + } + + @Test + void aCrowdOnOneFilteredTableOfAReleaseDoesNotHideASubclassOnAnotherFromTheCap( + final TestNamespace ns) { + assertBothClassPartsShareTheirTables(ns, RELEASE); + } + + /** + * Target0's table holds 101 identity bindings of classes that are no subclass of it, which is one + * more than the cap. Target1's table holds one subclass of Target1. A cap that counted both tables + * together would leave one of them unread and answer {@code check} for its class. + */ + private static void assertBothClassPartsShareTheirTables( + final TestNamespace ns, final OntologyStatementVersion version) { + final String name = "cap" + version.value(); + final Ontology ontology = createOntology(ns, name); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture( + ns, ontology, targets(name, 2, new FilterSpec("title", NOT_EQUALS, "x")))) { + fixture.bindAll(); + for (int crowd = 0; crowd < 101; crowd++) { + sharesTable(fixture, "Crowd" + crowd, name + "_targets0"); + } + sharesTable(fixture, "Sub1", name + "_targets1"); + subclassOf(ontology, fixture.type("Sub1"), fixture.type("Target1")); + declare( + ontology, + fixture, + "Targets", + "Order", + on(fixture, "class0", "reaches0").withClassIri(fixture.type("Target0").getIri()), + on(fixture, "class1", "reaches1").withClassIri(fixture.type("Target1").getIri())); + if (version == RELEASE) { + activate(ns, ontology); + } + final OntologyShapeChecks answered = checks(admin(), fixture.type("Order"), version); + + for (final String constraint : List.of("class0", "class1")) { + assertEquals(NOT_ENFORCEABLE, outcome(answered, constraint, CLASS), constraint); + assertEquals( + OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE, + reason(answered, constraint, CLASS), + constraint); + } + } + } + + private static void sharesTable( + final OntologyShapeFixture fixture, final String type, final String table) { + fixture.bind( + new BindingSpec( + type, table, OntologyBindingRole.IDENTITY, List.of("sku"), null, List.of())); + } + + private static void subclassOf( + final Ontology ontology, final OntologyConcept child, final OntologyConcept parent) { + admin() + .ontologyAxioms() + .create( + new CreateOntologyAxiom() + .withName(child.getName() + "Is" + parent.getName()) + .withDisplayName(child.getName() + "Is" + parent.getName()) + .withDescription("A subclass step of a class that shares a table") + .withOntology(ontology.getFullyQualifiedName()) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(child.getIri()) + .withProvenance(RelationProvenance.MANUAL) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(parent.getIri())))); + } + @Test void aRelationBoundOnlyOnItsInverseIsNotEnforceableFromThisSide(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "inverse"); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java index e4303c9584d6..7dcabf63afc5 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java @@ -23,6 +23,7 @@ import java.nio.charset.StandardCharsets; import java.sql.PreparedStatement; import java.sql.SQLException; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; @@ -138,6 +139,47 @@ final class OntologyShapeCheckFixtures { private OntologyShapeCheckFixtures() {} + /** + * An order class that reaches {@code classes} other classes, each through a table of its own and + * each with an identity table of its own, so every relation can state a {@code class} part. + */ + static Shape targets(final String name, final int classes, final FilterSpec filter) { + final List tables = + new ArrayList<>(List.of(table(name + "_orders", List.of(integer("id"), text("channel"))))); + final List types = new ArrayList<>(List.of("Order")); + final List properties = new ArrayList<>(List.of(data("orderChannel", "Order"))); + final List bindings = + new ArrayList<>( + List.of( + identityTable( + "Order", + name + "_orders", + List.of("id"), + null, + bound("orderChannel", "channel")))); + for (int target = 0; target < classes; target++) { + tables.add(table(name + "_targets" + target, List.of(text("sku"), text("title")))); + tables.add(table(name + "_links" + target, List.of(integer("order_id"), text("sku")))); + types.add("Target" + target); + properties.add(data("title" + target, "Target" + target)); + properties.add(relation("reaches" + target, "Order", "Target" + target)); + bindings.add( + identityTable( + "Target" + target, + name + "_targets" + target, + List.of("sku"), + filter, + bound("title" + target, "title"))); + bindings.add( + contributing( + "Order", + name + "_links" + target, + List.of("order_id"), + joined("reaches" + target, "sku", name + "_targets" + target, "sku"))); + } + return mapping(name, tables, types, properties, bindings.toArray(BindingSpec[]::new)); + } + static ColumnSpec integer(final String name) { return new ColumnSpec(name, ColumnDataType.INT); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index 15c4dceca0dd..aa6f97c50f1a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -27,11 +27,15 @@ import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.part; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.relation; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.targets; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE; import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; import java.util.ArrayList; import java.util.Collections; @@ -48,12 +52,22 @@ import org.openmetadata.it.util.SqlQueryCounter; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyAxiom; +import org.openmetadata.schema.api.data.OntologyCheckedPart; import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; import org.openmetadata.schema.api.data.OntologyStatementVersion; import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyExpression; +import org.openmetadata.schema.type.OntologyExpressionKind; import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.RelationProvenance; import org.openmetadata.service.Entity; import org.openmetadata.service.monitoring.RequestLatencyContext; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; @@ -102,6 +116,15 @@ class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { private static final int FILTERED_RELEASE_STATEMENTS = RELEASE_STATEMENTS + 1; + /** + * A draft that finds classes sharing a filtered table reads those classes once and then walks the + * subclass steps above them, one statement for each level of the hierarchy and one more that finds + * nothing above the top. A release reads no more, because it is read through its cache. + */ + private static final int SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS = FILTERED_DRAFT_STATEMENTS + 3; + + private static final int SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS = FILTERED_DRAFT_STATEMENTS + 5; + private static final FilterSpec NOT_X = new FilterSpec("title", OntologyRowFilterOperator.NOT_EQUALS, "x"); @@ -162,47 +185,6 @@ private static Shape orders(final String name, final int notes) { /** Constraints that a shape on {@link #targets} holds, as many as the targets are asked to name. */ private static final int CONSTRAINTS_ON_TARGETS = 8; - /** - * An order class that reaches {@code classes} other classes, each through a table of its own and - * each with an identity table of its own, so every relation can state a {@code class} part. - */ - private static Shape targets(final String name, final int classes, final FilterSpec filter) { - final List tables = - new ArrayList<>(List.of(table(name + "_orders", List.of(integer("id"), text("channel"))))); - final List types = new ArrayList<>(List.of("Order")); - final List properties = new ArrayList<>(List.of(data("orderChannel", "Order"))); - final List bindings = - new ArrayList<>( - List.of( - identityTable( - "Order", - name + "_orders", - List.of("id"), - null, - bound("orderChannel", "channel")))); - for (int target = 0; target < classes; target++) { - tables.add(table(name + "_targets" + target, List.of(text("sku"), text("title")))); - tables.add(table(name + "_links" + target, List.of(integer("order_id"), text("sku")))); - types.add("Target" + target); - properties.add(data("title" + target, "Target" + target)); - properties.add(relation("reaches" + target, "Order", "Target" + target)); - bindings.add( - identityTable( - "Target" + target, - name + "_targets" + target, - List.of("sku"), - filter, - bound("title" + target, "title"))); - bindings.add( - contributing( - "Order", - name + "_links" + target, - List.of("order_id"), - joined("reaches" + target, "sku", name + "_targets" + target, "sku"))); - } - return mapping(name, tables, types, properties, bindings.toArray(BindingSpec[]::new)); - } - /** * One shape of the order class with eight {@code class} constraints, which name {@code named} * distinct classes among them. @@ -512,6 +494,281 @@ void aReleaseWhoseFilteredClassPartsNameEightClassesIsReadInTheStatementsOfOne( assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); } + @Test + void aDraftWithNoClassOnTheFilteredTableReadsNoSubclassStep(final TestNamespace ns) { + final Reads none = sharing(ns, "none", 0, 1, true, DRAFT); + + assertEquals(FILTERED_DRAFT_STATEMENTS, none.statements().size(), none::listed); + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(none).getOutcome()); + assertDraftReads(none, 3); + } + + @Test + void aDraftWithOneSharingClassOneStepBelowTheNamedClassWalksOneLevelAndASecond( + final TestNamespace ns) { + final Reads one = sharing(ns, "oneBelow", 1, 1, true, DRAFT); + + assertEquals(SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(one).getReason()); + assertDraftReads(one, 3); + } + + @Test + void aDraftWithOneSharingClassThreeStepsBelowTheNamedClassWalksThreeLevelsAndASecond( + final TestNamespace ns) { + final Reads one = sharing(ns, "oneDeep", 1, 3, true, DRAFT); + + assertEquals(SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(one).getReason()); + assertDraftReads(one, 3); + } + + @Test + void aDraftWithEightSharingClassesOneStepDeepIsReadInTheStatementsOfOne(final TestNamespace ns) { + final Reads eight = sharing(ns, "eightBelow", 8, 1, true, DRAFT); + + assertEquals(SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(eight).getReason()); + assertDraftReads(eight, 3); + } + + @Test + void aDraftWithEightSharingClassesThreeStepsDeepIsReadInTheStatementsOfOne( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightDeep", 8, 3, true, DRAFT); + + assertEquals(SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(eight).getReason()); + assertDraftReads(eight, 3); + } + + @Test + void aDraftWhoseSharingClassesReachAnotherClassStillWalksThemInOneStatementPerLevel( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightElsewhere", 8, 3, false, DRAFT); + + assertEquals(SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(eight).getOutcome()); + assertDraftReads(eight, 3); + } + + @Test + void aDraftWithOneSharingClassThatReachesAnotherClassAnswersWithATest(final TestNamespace ns) { + final Reads one = sharing(ns, "oneElsewhere", 1, 1, false, DRAFT); + + assertEquals(SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(one).getOutcome()); + } + + @Test + void aReleaseWithNoClassOnTheFilteredTableIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads none = sharing(ns, "none", 0, 1, true, RELEASE); + + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(none).getOutcome()); + assertReleaseReads(none, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWithOneSharingClassOneStepBelowIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads one = sharing(ns, "oneBelow", 1, 1, true, RELEASE); + + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(one).getReason()); + assertReleaseReads(one, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWithOneSharingClassThreeStepsBelowIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads one = sharing(ns, "oneDeep", 1, 3, true, RELEASE); + + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(one).getReason()); + assertReleaseReads(one, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWithEightSharingClassesOneStepBelowIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightBelow", 8, 1, true, RELEASE); + + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(eight).getReason()); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWithEightSharingClassesThreeStepsBelowIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightDeep", 8, 3, true, RELEASE); + + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(eight).getReason()); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWhoseSharingClassesReachAnotherClassIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightElsewhere", 8, 3, false, RELEASE); + + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(eight).getOutcome()); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aDraftNamingEightFilteredClassesWithOneSharingClassEachCostsWhatOneNamedClassCosts( + final TestNamespace ns) { + final Reads eight = namedWithSharers(ns, "eightNamed", DRAFT); + + assertEquals(List.of(1, 8, 0), sizes(eight)); + assertEquals(SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertEveryClassPartIsNotEnforceable(eight); + assertDraftReads(eight, 3); + } + + @Test + void aReleaseNamingEightFilteredClassesWithOneSharingClassEachCostsWhatOneNamedClassCosts( + final TestNamespace ns) { + final Reads eight = namedWithSharers(ns, "eightNamed", RELEASE); + + assertEquals(List.of(1, 8, 0), sizes(eight)); + assertEveryClassPartIsNotEnforceable(eight); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + private static void assertEveryClassPartIsNotEnforceable(final Reads reads) { + final List classParts = + reads.answer().getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .flatMap(constraint -> constraint.getParts().stream()) + .filter(part -> part.getPart() == OntologyShapePart.CLASS) + .toList(); + assertEquals(CONSTRAINTS_ON_TARGETS, classParts.size()); + classParts.forEach( + part -> { + assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, part.getOutcome()); + assertEquals(SUBCLASS_ON_JOIN_TABLE, part.getReason()); + }); + } + + private static OntologyCheckedPart classPart(final Reads reads) { + return part(reads.answer(), "onProducts", OntologyShapePart.CLASS); + } + + /** + * Product's identity binding has a row filter and {@code sharers} classes bind the same table as + * their identity table, each below a chain of {@code depth} subclass steps. With {@code + * subclasses} the even ones are chained up to Product and the odd ones up to another class. With + * it false every one is chained up to the other class. + */ + private static Reads sharing( + final TestNamespace ns, + final String name, + final int sharers, + final int depth, + final boolean subclasses, + final OntologyStatementVersion version) { + final Ontology ontology = createOntology(ns, name + version.value()); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE)) { + fixture.bindAll(); + fixture.bind( + new BindingSpec( + "Product", + "products", + OntologyBindingRole.IDENTITY, + List.of("sku"), + NOT_X, + List.of(bound("productTitle", "title")))); + final OntologyConcept product = fixture.type("Product"); + final OntologyConcept elsewhere = fixture.type("Elsewhere"); + for (int sharer = 0; sharer < sharers; sharer++) { + final String sharerName = "Sharer" + sharer; + sharesTable(fixture, sharerName, "products"); + chain( + ontology, + fixture, + fixture.type(sharerName), + subclasses && sharer % 2 == 0 ? product : elsewhere, + depth); + } + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "onProducts", "contains").withClassIri(product.getIri())); + if (version == RELEASE) { + activate(ns, ontology); + } + return reads(fixture, version); + } + } + + /** + * Eight filtered classes, each on a table of its own, with one class below it that binds the same + * table as its identity table. + */ + private static Reads namedWithSharers( + final TestNamespace ns, final String name, final OntologyStatementVersion version) { + final Ontology ontology = createOntology(ns, name + version.value()); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, targets(name, CONSTRAINTS_ON_TARGETS, NOT_X))) { + fixture.bindAll(); + for (int target = 0; target < CONSTRAINTS_ON_TARGETS; target++) { + final String sharerName = "Sharer" + target; + sharesTable(fixture, sharerName, name + "_targets" + target); + chain(ontology, fixture, fixture.type(sharerName), fixture.type("Target" + target), 1); + } + declareClassParts(ontology, fixture, CONSTRAINTS_ON_TARGETS); + if (version == RELEASE) { + activate(ns, ontology); + } + return reads(fixture, version); + } + } + + private static void sharesTable( + final OntologyShapeFixture fixture, final String type, final String table) { + fixture.bind( + new BindingSpec( + type, table, OntologyBindingRole.IDENTITY, List.of("sku"), null, List.of())); + } + + /** Declares {@code depth} subclass steps from {@code bottom} up to {@code top}. */ + private static void chain( + final Ontology ontology, + final OntologyShapeFixture fixture, + final OntologyConcept bottom, + final OntologyConcept top, + final int depth) { + OntologyConcept child = bottom; + for (int step = 1; step < depth; step++) { + final OntologyConcept middle = fixture.type(bottom.getName() + "Mid" + step); + subclassOf(ontology, child, middle); + child = middle; + } + subclassOf(ontology, child, top); + } + + private static void subclassOf( + final Ontology ontology, final OntologyConcept child, final OntologyConcept parent) { + admin() + .ontologyAxioms() + .create( + new CreateOntologyAxiom() + .withName(child.getName() + "Is" + parent.getName()) + .withDisplayName(child.getName() + "Is" + parent.getName()) + .withDescription("A subclass step of the hierarchy a test walks") + .withOntology(ontology.getFullyQualifiedName()) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(child.getIri()) + .withProvenance(RelationProvenance.MANUAL) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(parent.getIri())))); + } + private static Reads classParts( final TestNamespace ns, final String name, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 529c65f7ce10..ca32c0fbc0a6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -403,35 +403,54 @@ public void deleteConcept(final UUID conceptId) { } public Set ancestors(final OntologyConcept concept) { - final Set visited = new HashSet<>(); - Set pending = Set.of(concept.getIri().toString()); + final String start = concept.getIri().toString(); + return OntologyClassHierarchy.reachable( + namedParentsAbove(concept.getOntology().getId(), Set.of(start)), Set.of(start)); + } + + /** + * The named parents of every class that a walk up from {@code starts} reaches, by the IRI of the + * class. One statement reads each level for the whole frontier, so the statements are one per + * level whatever the number of starts. + */ + public Map> namedParentsAbove( + final UUID ontologyId, final Collection starts) { + final Map> parents = new HashMap<>(); + final Set visited = new HashSet<>(starts); + Set pending = Set.copyOf(starts); int traversed = 0; while (!pending.isEmpty()) { - visited.addAll(pending); final var axioms = dao.ontologyReferenceDAO() .ancestors( - concept.getOntology().getId(), + ontologyId, pending.stream().map(DigestUtils::sha256Hex).toList(), MAX_ANCESTORS + 1, ""); traversed += axioms.size(); requireBound(Math.max(visited.size(), traversed)); - pending = parents(axioms, pending, visited); + pending = levelAbove(axioms, pending, visited, parents); + visited.addAll(pending); } - return Set.copyOf(visited); + return parents; } - private static Set parents( - final List rows, final Set pending, final Set visited) { + private static Set levelAbove( + final List rows, + final Set pending, + final Set visited, + final Map> parents) { final Set result = new HashSet<>(); for (final String json : rows) { final var axiom = JsonUtils.readValue(json, OntologyAxiom.class); - if (pending.contains(axiom.getSubjectIri().toString())) { - OntologyClassHierarchy.namedParents(axiom).stream() - .map(URI::toString) - .filter(iri -> !visited.contains(iri)) - .forEach(result::add); + final String subject = axiom.getSubjectIri().toString(); + if (pending.contains(subject)) { + for (final URI parent : OntologyClassHierarchy.namedParents(axiom)) { + parents.computeIfAbsent(subject, ignored -> new HashSet<>()).add(parent.toString()); + if (!visited.contains(parent.toString())) { + result.add(parent.toString()); + } + } requireBound(result.size()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyClassHierarchy.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyClassHierarchy.java index 68fdcd1d93a9..f198fa755a5c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyClassHierarchy.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyClassHierarchy.java @@ -5,6 +5,8 @@ import java.net.URI; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -281,7 +283,23 @@ public static List namedParents(final OntologyAxiom axiom) { .toList(); } - private static Map> namedEdges( + /** Every IRI that a walk up the named parents reaches from {@code starts}, the starts included. */ + public static Set reachable( + final Map> parents, final Collection starts) { + final Set visited = new HashSet<>(starts); + final Deque pending = new ArrayDeque<>(starts); + while (!pending.isEmpty()) { + for (final String parent : parents.getOrDefault(pending.pop(), Set.of())) { + if (visited.add(parent)) { + pending.push(parent); + } + } + } + return visited; + } + + /** The named parents that the subclass axioms give each class, by the IRI of the class. */ + public static Map> namedEdges( final List definitions) { final Map> edges = new HashMap<>(); definitions.stream() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java index cd892eb8a79a..9861f1fe6932 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -14,14 +14,12 @@ package org.openmetadata.service.ontology; import java.net.URI; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; -import java.util.Deque; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -31,7 +29,6 @@ import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.api.data.OntologyStatementVersion; import org.openmetadata.schema.api.data.OntologyStatementVersionRead; -import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; @@ -229,20 +226,25 @@ public Set withSubclassAmong( final OntologyConceptBindingStore store, final UUID ontologyId, final Map> candidatesByIri) { - final Map> ancestors = new HashMap<>(); + final Map iriById = new HashMap<>(); store .liveConcepts( candidatesByIri.values().stream().flatMap(Collection::stream).distinct().toList()) .stream() .filter(candidate -> ontologyId.equals(candidate.getOntology().getId())) - .forEach(candidate -> ancestors.put(candidate.getId(), store.ancestors(candidate))); + .forEach(candidate -> iriById.put(candidate.getId(), candidate.getIri().toString())); + final Map> parents = + store.namedParentsAbove(ontologyId, Set.copyOf(iriById.values())); return candidatesByIri.entrySet().stream() .filter( entry -> - entry.getValue().stream() - .map(ancestors::get) - .anyMatch( - found -> found != null && found.contains(entry.getKey().toString()))) + OntologyClassHierarchy.reachable( + parents, + entry.getValue().stream() + .map(iriById::get) + .filter(Objects::nonNull) + .toList()) + .contains(entry.getKey().toString())) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } @@ -345,50 +347,21 @@ public Set withSubclassAmong( .filter(OntologyConcept.class::isInstance) .map(OntologyConcept.class::cast) .toList(); - final Map> parents = namedParents(members); + final Map> parents = OntologyClassHierarchy.namedEdges(members); return candidatesByIri.entrySet().stream() .filter( entry -> - reaches( - parents, - classes.stream() - .filter(type -> entry.getValue().contains(type.getId())) - .map(type -> type.getIri().toString()) - .collect(Collectors.toSet()), - entry.getKey().toString())) + OntologyClassHierarchy.reachable( + parents, + classes.stream() + .filter(type -> entry.getValue().contains(type.getId())) + .map(type -> type.getIri().toString()) + .toList()) + .contains(entry.getKey().toString())) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } - /** The named parents that the subclass axioms give each class, by the IRI of the class. */ - private static Map> namedParents(final List members) { - final Map> parents = new HashMap<>(); - for (final OntologyDefinition member : members) { - if (member instanceof OntologyAxiom axiom && axiom.getSubjectIri() != null) { - final Set named = - parents.computeIfAbsent(axiom.getSubjectIri().toString(), subject -> new HashSet<>()); - OntologyClassHierarchy.namedParents(axiom) - .forEach(parent -> named.add(parent.toString())); - } - } - return parents; - } - - /** True when a walk up the named parents from one of {@code starts} arrives at {@code iri}. */ - private static boolean reaches( - final Map> parents, final Set starts, final String iri) { - final Set visited = new HashSet<>(starts); - final Deque pending = new ArrayDeque<>(starts); - while (!pending.isEmpty()) { - for (final String parent : parents.getOrDefault(pending.pop(), Set.of())) { - if (visited.add(parent)) { - pending.push(parent); - } - } - } - return visited.contains(iri); - } - /** * The members of one kind with these ids that the release declares with a wanted IRI, in one * statement. The ids come from the working rows, deleted ones too, so a definition is found diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java index 18442325be4c..975066bdaa25 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java @@ -211,9 +211,8 @@ void filteredClassesAreReadForTheirSubclassesInOneReadOfTheRowsAndOneQuestion() row(buyer, 3, OntologyBindingRole.IDENTITY))); when(store.liveConcepts(ArgumentMatchers.>any())) .thenReturn(List.of(subOfPerson, unrelated)); - when(store.ancestors(subOfPerson)) - .thenReturn(Set.of(placerIri.toString(), PERSON_IRI.toString())); - when(store.ancestors(unrelated)).thenReturn(Set.of(buyerIri.toString())); + when(store.namedParentsAbove(ONTOLOGY, Set.of(placerIri.toString(), buyerIri.toString()))) + .thenReturn(Map.of(placerIri.toString(), Set.of(PERSON_IRI.toString()))); final Read read = reader.read(null, DRAFT_ORDER); @@ -221,6 +220,7 @@ void filteredClassesAreReadForTheirSubclassesInOneReadOfTheRowsAndOneQuestion() assertEquals(false, read.facts().targets().get(PRODUCT_IRI).subclassSharesTable()); verify(store, times(1)).firstForAssets(anyCollection(), eq(101)); verify(store, times(1)).liveConcepts(ArgumentMatchers.>any()); + verify(store, times(1)).namedParentsAbove(eq(ONTOLOGY), anyCollection()); } @Test From c442f0745ff3501ba5a5422b787146221a3e73d6 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 08:22:21 -0800 Subject: [PATCH 097/203] State the cost of the subclass question in the shape check record --- ...ape-check-is-exact-or-it-is-not-offered.md | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index 4cbebb2b6031..326068b91108 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -1,9 +1,9 @@ # A shape check is exact or it is not offered - **Status:** Accepted -- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) · v4 2026-11-25 (the statements do not grow with the classes a `class` part names, a filtered one included) +- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) · v4 2026-11-25 (the statements do not grow with the classes a `class` part names, a filtered one included) · v5 2026-11-26 (the subclass question walks the ancestors of all the sharing classes together) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads) +- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads, and the cost of the subclass question), `OntologyConceptBindingFirstRowsIT` (the cap of the first rows is per table) - **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) ## Context @@ -275,7 +275,13 @@ statement locks the rows it reads. A `class` part whose class has a row filter o binding adds one statement that reads the binding rows of every such table together, with the first 101 rows of each table, so those requests run 49 and 57 whether the parts name 1 class or 8. When another class has its identity binding on one of those tables, one more question asks the -version once for all the classes that have a subclass there. +version once for all the classes that have a subclass there. On a draft that question reads the +sharing classes in one statement and then walks the subclass steps above all of them together, one +statement for each level of the hierarchy and one more that finds nothing above the top. So a draft +runs 52 statements when the sharing classes are one step below the named class and 54 when they are +three, whether one class shares the table or eight, and whether the classes of the named parts are +1 or 8. A release runs 57 in every case, because it answers the question from its members, which it +reads through the cache that every sealed release shares. `OntologyShapeCheckReadsIT` counts those numbers for 1, 40 and 80 constraints on a class of 6 tables, for 40 constraints on a class of 3 tables and of 12, and for `class` parts that name 1 @@ -381,3 +387,16 @@ and another for each class that shared the table. It now reads the binding rows in one statement and asks the version once for every class that may have a subclass there. A request with filtered identity bindings runs 49 statements from a draft and 57 from a release, for 1 named class and for 8. + +v5 (2026-11-26): the subclass question walks the ancestors of every sharing class together. The +first form of it walked each sharing class on its own, which cost one statement for each level of +each class, so 8 sharing classes three steps deep cost 82 statements. A draft now reads the sharing +classes once and runs one statement for each level of the hierarchy over the whole frontier, and it +decides each named class in memory, as a release does. It never reads every subclass axiom of the +ontology to answer, because that would read the whole hierarchy for each answer. The same walk gives +a class its ancestors for binding inheritance. The reads test asserts 52 and 54 statements from a +draft for 1 and for 8 sharing classes at depths 1 and 3, 57 from a release, and 52 for 8 named +classes with one sharing class each. `OntologyConceptBindingFirstRowsIT` guards that the cap of 101 +rows counts the rows of one table and not of all the tables a call reads, and +`OntologyShapeCheckAnswerIT` guards it on a draft and a release where one table is crowded and +another holds one subclass. From a4e7738368a673556550de6b3fb6651743e8b640 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 13:05:32 -0800 Subject: [PATCH 098/203] Bound the ancestor walk by the classes above its starts, not the starts --- .../jdbi3/OntologyConceptBindingStore.java | 15 +- ...ologyConceptBindingStoreAncestorsTest.java | 243 ++++++++++++++++++ 2 files changed, 253 insertions(+), 5 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index ca32c0fbc0a6..748daaa58504 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -404,20 +404,25 @@ public void deleteConcept(final UUID conceptId) { public Set ancestors(final OntologyConcept concept) { final String start = concept.getIri().toString(); - return OntologyClassHierarchy.reachable( - namedParentsAbove(concept.getOntology().getId(), Set.of(start)), Set.of(start)); + final Set reached = + OntologyClassHierarchy.reachable( + namedParentsAbove(concept.getOntology().getId(), Set.of(start)), Set.of(start)); + requireBound(reached.size()); + return reached; } /** * The named parents of every class that a walk up from {@code starts} reaches, by the IRI of the * class. One statement reads each level for the whole frontier, so the statements are one per - * level whatever the number of starts. + * level whatever the number of starts. The walk is bound as a whole, by the classes it finds above + * the starts and by the axioms it reads. The starts themselves are not counted. */ public Map> namedParentsAbove( final UUID ontologyId, final Collection starts) { final Map> parents = new HashMap<>(); final Set visited = new HashSet<>(starts); - Set pending = Set.copyOf(starts); + final int startCount = visited.size(); + Set pending = Set.copyOf(visited); int traversed = 0; while (!pending.isEmpty()) { final var axioms = @@ -428,7 +433,7 @@ public Map> namedParentsAbove( MAX_ANCESTORS + 1, ""); traversed += axioms.size(); - requireBound(Math.max(visited.size(), traversed)); + requireBound(Math.max(visited.size() - startCount, traversed)); pending = levelAbove(axioms, pending, visited, parents); visited.addAll(pending); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java new file mode 100644 index 000000000000..3ab1352fd24b --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java @@ -0,0 +1,243 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.jdbi3; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyAxiom; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyExpression; +import org.openmetadata.schema.type.OntologyExpressionKind; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.BadRequestException; + +/** + * The walk up the named subclass steps of a class, with the axioms served by a stubbed DAO that + * answers as the real one does: the subclass axioms of the classes asked for, by axiom name, up to + * the limit. The walk is bound at 10,000, which {@link OntologyConceptBindingStore#ancestors} reads + * as the classes it returns, the start included, and {@link + * OntologyConceptBindingStore#namedParentsAbove} as the classes above the starts and the axioms it + * reads, all starts together. + */ +class OntologyConceptBindingStoreAncestorsTest { + private static final UUID ONTOLOGY = UUID.randomUUID(); + private static final String BASE = "https://example.org/walk/"; + private static final String REFUSED = + "Binding property inheritance exceeds the 10000 axiom limit"; + + /** A stubbed DAO that counts the statements asked of it. */ + private static final class Axioms { + private final List stored = new ArrayList<>(); + private final AtomicInteger statements = new AtomicInteger(); + private final OntologyConceptBindingStore store; + + private record Stored(String name, String subjectHash, String json) {} + + Axioms() { + final CollectionDAO dao = mock(CollectionDAO.class); + final OntologyReferenceDAO references = mock(OntologyReferenceDAO.class); + when(dao.ontologyReferenceDAO()).thenReturn(references); + when(references.ancestors(any(UUID.class), anyList(), anyInt(), anyString())) + .thenAnswer( + call -> { + statements.incrementAndGet(); + final List hashes = call.getArgument(1); + final int limit = call.getArgument(2); + return stored.stream() + .filter(axiom -> hashes.contains(axiom.subjectHash())) + .sorted(Comparator.comparing(Stored::name)) + .limit(limit) + .map(Stored::json) + .toList(); + }); + store = new OntologyConceptBindingStore(dao, type -> "table"); + } + + /** {@code child} is a subclass of {@code parent}, in an axiom of the given name. */ + Axioms subclass(final String name, final String child, final String parent) { + final OntologyAxiom axiom = + new OntologyAxiom() + .withId(UUID.randomUUID()) + .withName(name) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(iri(child)) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(iri(parent)))); + stored.add( + new Stored( + name, DigestUtils.sha256Hex(iri(child).toString()), JsonUtils.pojoToJson(axiom))); + return this; + } + + /** {@code length} single-parent steps above {@code bottom}, each class named for its step. */ + Axioms chain(final String bottom, final int length) { + String child = bottom; + for (int step = 1; step <= length; step++) { + final String parent = bottom + "Above" + step; + subclass(child + "Is" + parent, child, parent); + child = parent; + } + return this; + } + + Set ancestors(final String start) { + return store.ancestors(concept(start)); + } + + Map> above(final String... starts) { + return store.namedParentsAbove( + ONTOLOGY, java.util.Arrays.stream(starts).map(s -> iri(s).toString()).toList()); + } + + int statements() { + return statements.get(); + } + } + + private static URI iri(final String name) { + return URI.create(BASE + name); + } + + private static OntologyConcept concept(final String name) { + return new OntologyConcept() + .withId(UUID.nameUUIDFromBytes(name.getBytes())) + .withName(name) + .withIri(iri(name)) + .withOntology(new EntityReference().withId(ONTOLOGY).withType("ontology")); + } + + private static Set iris(final String... names) { + return java.util.Arrays.stream(names) + .map(name -> iri(name).toString()) + .collect(java.util.stream.Collectors.toSet()); + } + + /** 5,000 and 4,999 axioms: 9,999 classes above the starts, under the bound of 10,000. */ + @Test + void twoStartsUnderDisjointChainsOf5000And4999AxiomsAreWalkedTogether() { + final Axioms axioms = new Axioms().chain("First", 5_000).chain("Second", 4_999); + + final Map> parents = axioms.above("First", "Second"); + + assertEquals(9_999, parents.size()); + assertEquals(Set.of(iri("FirstAbove1").toString()), parents.get(iri("First").toString())); + assertEquals(Set.of(iri("SecondAbove1").toString()), parents.get(iri("Second").toString())); + assertEquals(5_001, axioms.statements()); + } + + /** 5,000 and 5,000 axioms: exactly 10,000 classes above the starts, which the bound allows. */ + @Test + void twoStartsWhoseChainsHoldExactlyTheBoundAreWalked() { + final Axioms axioms = new Axioms().chain("First", 5_000).chain("Second", 5_000); + + assertEquals(10_000, axioms.above("First", "Second").size()); + } + + /** 5,001 and 5,000 axioms: 10,001 classes above the starts together, over the bound. */ + @Test + void twoStartsWhoseChainsHoldMoreThanTheBoundTogetherAreRefused() { + final Axioms axioms = new Axioms().chain("First", 5_001).chain("Second", 5_000); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> axioms.above("First", "Second")); + + assertEquals(REFUSED, refused.getMessage()); + } + + /** + * One start under 10,000 axioms: 10,000 classes above it, which {@code namedParentsAbove} allows. + * {@code ancestors} counts the start too, 10,001 classes in all, over the bound as it was. + */ + @Test + void oneStartUnderAChainOf10000AxiomsIsWalkedAboveButRefusedAsAnAncestorSet() { + final Axioms axioms = new Axioms().chain("Start", 10_000); + + assertEquals(10_000, axioms.above("Start").size()); + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> axioms.ancestors("Start")); + + assertEquals(REFUSED, refused.getMessage()); + } + + /** 9,999 axioms: 10,000 classes with the start, which the bound allows. */ + @Test + void oneStartUnderAChainOf9999AxiomsHasAnAncestorSetOfExactlyTheBound() { + final Axioms axioms = new Axioms().chain("Start", 9_999); + + assertEquals(10_000, axioms.ancestors("Start").size()); + } + + @Test + void twoChainsThatMeetAreWalkedInThreeStatements() { + final Axioms axioms = twoParentsThatMeet(); + + final Set ancestors = axioms.ancestors("Start"); + + assertEquals(iris("Start", "A", "B", "X", "Top"), ancestors); + assertEquals(3, axioms.statements()); + } + + @Test + void aClassUnderTwoClassesHasBothAndEverythingAboveEach() { + final Axioms axioms = twoParentsThatMeet(); + + final Map> parents = axioms.above("Start"); + + assertEquals( + Set.of(iri("A").toString(), iri("B").toString()), parents.get(iri("Start").toString())); + assertEquals(Set.of(iri("Top").toString()), parents.get(iri("A").toString())); + assertEquals(Set.of(iri("X").toString()), parents.get(iri("B").toString())); + assertEquals(Set.of(iri("Top").toString()), parents.get(iri("X").toString())); + } + + @Test + void aClassWithNoParentIsItsOwnAncestorSetInOneStatement() { + final Axioms axioms = new Axioms(); + + assertEquals(iris("Start"), axioms.ancestors("Start")); + assertEquals(1, axioms.statements()); + } + + /** Start is under A and B, A is under Top, and B is under X, which is under Top. */ + private static Axioms twoParentsThatMeet() { + return new Axioms() + .subclass("StartIsA", "Start", "A") + .subclass("StartIsB", "Start", "B") + .subclass("AIsTop", "A", "Top") + .subclass("BIsX", "B", "X") + .subclass("XIsTop", "X", "Top"); + } +} From 0a1dca37627e6be7d25c277a35fd9956e3a112a5 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 13:11:49 -0800 Subject: [PATCH 099/203] Test the walk over chains that meet, a second parent and a class of another ontology --- .../it/tests/OntologyConceptBindingsIT.java | 51 ++++++ .../it/tests/OntologyShapeCheckReadsIT.java | 149 ++++++++++++++++-- 2 files changed, 188 insertions(+), 12 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingsIT.java index 0f41706bb195..97f4a5b0e7af 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingsIT.java @@ -131,6 +131,37 @@ void inheritedDataPropertyAndExactNestedPathAreValidated(TestNamespace ns) { assertEquals(1L, get(admin(), child).getRevision()); } + /** + * A class under two named classes inherits the properties of both, and of everything above each. + * The axioms are read by name, so the walk meets {@code ChildIsAFirst} before {@code + * ChildIsBSecond}, and only the second parent leads to the root. + */ + @Test + void propertiesOfTheSecondParentAndOfEverythingAboveItAreApplicable(TestNamespace ns) { + final var ontology = createOntology(ns); + final var child = declareClass(ontology, "Child", URI.create("urn:Child")); + final var first = declareClass(ontology, "First", URI.create("urn:First")); + final var second = declareClass(ontology, "Second", URI.create("urn:Second")); + final var other = declareClass(ontology, "Other", URI.create("urn:Other")); + final var root = declareClass(ontology, "Root", URI.create("urn:Root")); + final var stranger = declareClass(ontology, "Stranger", URI.create("urn:Stranger")); + subclassOf(ontology, child, first, "ChildIsAFirst"); + subclassOf(ontology, child, second, "ChildIsBSecond"); + subclassOf(ontology, first, other, "FirstIsOther"); + subclassOf(ontology, second, root, "SecondIsRoot"); + final var table = table(ns); + + assertEquals( + 1L, put(admin(), child, association(table, property(ontology, root)), 0L).getRevision()); + assertEquals( + 2L, put(admin(), child, association(table, property(ontology, second)), 1L).getRevision()); + assertEquals( + 3L, put(admin(), child, association(table, property(ontology, other)), 2L).getRevision()); + assertStatus( + 400, () -> put(admin(), child, association(table, property(ontology, stranger)), 3L)); + assertEquals(3L, get(admin(), child).getRevision()); + } + @Test void hiddenTargetsAreNotReturnedOrOverwrittenByVisibleAssetUpdates(TestNamespace ns) { final var ontology = createOntology(ns); @@ -559,6 +590,26 @@ private static int writeTogether( } } + private static void subclassOf( + Ontology ontology, OntologyConcept child, OntologyConcept parent, String name) { + admin() + .ontologyAxioms() + .create( + new CreateOntologyAxiom() + .withName(name) + .withDisplayName(name) + .withDescription("A named parent that supplies applicable property domains.") + .withOntology(ontology.getFullyQualifiedName()) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(child.getIri()) + .withProvenance(RelationProvenance.MANUAL) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(parent.getIri())))); + } + private static OntologyProperty property(Ontology ontology, OntologyConcept domain) { return admin() .ontologyProperties() diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index aa6f97c50f1a..59e2edf0aace 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -15,6 +15,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.contributing; @@ -44,6 +47,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.function.BiConsumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; @@ -125,6 +129,21 @@ class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { private static final int SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS = FILTERED_DRAFT_STATEMENTS + 5; + /** + * A walk asks for the axioms of a class once. A class that two chains reach is in the frontier of + * the shorter chain's level, so the longer chain finds it read and the walk stops one level + * sooner than a single chain of the same depth: the read of the sharing classes and three levels. + */ + private static final int SHARED_BY_CHAINS_THAT_MEET_DRAFT_STATEMENTS = + FILTERED_DRAFT_STATEMENTS + 4; + + /** + * A class that another ontology binds on the table is no candidate. The draft reads the classes + * that share the table and finds nothing to walk from. + */ + private static final int SHARED_ONLY_BY_ANOTHER_ONTOLOGY_DRAFT_STATEMENTS = + FILTERED_DRAFT_STATEMENTS + 1; + private static final FilterSpec NOT_X = new FilterSpec("title", OntologyRowFilterOperator.NOT_EQUALS, "x"); @@ -560,6 +579,91 @@ void aDraftWithOneSharingClassThatReachesAnotherClassAnswersWithATest(final Test assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(one).getOutcome()); } + /** + * The sharing class is a subclass of Product directly and also through two more classes. The + * class that both chains reach is asked for once, so the walk reads three levels. + */ + @Test + void aDraftWhoseSharingClassReachesTheNamedClassDirectlyAndThroughALongerChainReadsEachClassOnce( + final TestNamespace ns) { + final Reads meeting = + sharedBy( + ns, + "directAndLonger", + DRAFT, + (ontology, fixture) -> { + final OntologyConcept sharer = sharesTable(fixture, "Sharer", "products"); + subclassOf(ontology, sharer, fixture.type("Product")); + subclassOf(ontology, sharer, fixture.type("LongerOne")); + subclassOf(ontology, fixture.type("LongerOne"), fixture.type("LongerTwo")); + subclassOf(ontology, fixture.type("LongerTwo"), fixture.type("Product")); + }); + + assertEquals( + SHARED_BY_CHAINS_THAT_MEET_DRAFT_STATEMENTS, meeting.statements().size(), meeting::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(meeting).getReason()); + assertDraftReads(meeting, 3); + } + + /** + * The sharing class has two named parents. The one that the walk reads first leads away from the + * named class, and only the second leads to it. The axioms are read by name, so the first is the + * one whose name sorts first. + */ + @Test + void aDraftWhoseSharingClassReachesTheNamedClassOnlyThroughItsSecondParentWalksBothParents( + final TestNamespace ns) { + final Reads second = + sharedBy( + ns, + "secondParent", + DRAFT, + (ontology, fixture) -> { + final OntologyConcept sharer = sharesTable(fixture, "Sharer", "products"); + subclassOf(ontology, sharer, fixture.type("FirstParent")); + subclassOf(ontology, sharer, fixture.type("SecondParent")); + subclassOf(ontology, fixture.type("FirstParent"), fixture.type("Elsewhere")); + subclassOf(ontology, fixture.type("SecondParent"), fixture.type("Product")); + }); + + assertEquals( + SHARED_BY_CHAINS_THAT_MEET_DRAFT_STATEMENTS, second.statements().size(), second::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(second).getReason()); + assertDraftReads(second, 3); + } + + /** + * A class of another ontology has the IRI of a subclass of Product and binds the filtered table. + * It is no candidate, so the class part is checked. + */ + @Test + void aDraftWhoseFilteredTableIsSharedOnlyByAClassOfAnotherOntologyChecksTheClassPart( + final TestNamespace ns) { + final Reads foreign = + sharedBy( + ns, + "foreign", + DRAFT, + (ontology, fixture) -> { + final OntologyConcept near = fixture.type("Near"); + subclassOf(ontology, near, fixture.type("Product")); + final OntologyConcept stranger = + declareClass(createOntology(ns, "otherDraft"), "Stranger", near.getIri()); + put( + admin(), + stranger, + binding(fixture.table("products"), OntologyBindingRole.IDENTITY, "sku"), + bindings(admin(), stranger).getRevision()); + }); + + assertEquals( + SHARED_ONLY_BY_ANOTHER_ONTOLOGY_DRAFT_STATEMENTS, + foreign.statements().size(), + foreign::listed); + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(foreign).getOutcome()); + assertDraftReads(foreign, 3); + } + @Test void aReleaseWithNoClassOnTheFilteredTableIsReadInTheStatementsOfAnyFilteredRelease( final TestNamespace ns) { @@ -667,6 +771,35 @@ private static Reads sharing( final int depth, final boolean subclasses, final OntologyStatementVersion version) { + return sharedBy( + ns, + name, + version, + (ontology, fixture) -> { + final OntologyConcept product = fixture.type("Product"); + final OntologyConcept elsewhere = fixture.type("Elsewhere"); + for (int sharer = 0; sharer < sharers; sharer++) { + final String sharerName = "Sharer" + sharer; + sharesTable(fixture, sharerName, "products"); + chain( + ontology, + fixture, + fixture.type(sharerName), + subclasses && sharer % 2 == 0 ? product : elsewhere, + depth); + } + }); + } + + /** + * Product's identity binding has a row filter, one class part of the order shape names Product, + * and {@code declareSharers} adds the classes that share its table and their subclass axioms. + */ + private static Reads sharedBy( + final TestNamespace ns, + final String name, + final OntologyStatementVersion version, + final BiConsumer declareSharers) { final Ontology ontology = createOntology(ns, name + version.value()); try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE)) { fixture.bindAll(); @@ -679,17 +812,8 @@ private static Reads sharing( NOT_X, List.of(bound("productTitle", "title")))); final OntologyConcept product = fixture.type("Product"); - final OntologyConcept elsewhere = fixture.type("Elsewhere"); - for (int sharer = 0; sharer < sharers; sharer++) { - final String sharerName = "Sharer" + sharer; - sharesTable(fixture, sharerName, "products"); - chain( - ontology, - fixture, - fixture.type(sharerName), - subclasses && sharer % 2 == 0 ? product : elsewhere, - depth); - } + fixture.type("Elsewhere"); + declareSharers.accept(ontology, fixture); declare( ontology, fixture, @@ -726,11 +850,12 @@ private static Reads namedWithSharers( } } - private static void sharesTable( + private static OntologyConcept sharesTable( final OntologyShapeFixture fixture, final String type, final String table) { fixture.bind( new BindingSpec( type, table, OntologyBindingRole.IDENTITY, List.of("sku"), null, List.of())); + return fixture.type(type); } /** Declares {@code depth} subclass steps from {@code bottom} up to {@code top}. */ From 9c43d8051c80b343b47917ab8e744b771583b635 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 13:11:53 -0800 Subject: [PATCH 100/203] State how the subclass walk is bound in the shape check record --- ...a-shape-check-is-exact-or-it-is-not-offered.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index 326068b91108..a52ea3b16bcb 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -1,9 +1,9 @@ # A shape check is exact or it is not offered - **Status:** Accepted -- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) · v4 2026-11-25 (the statements do not grow with the classes a `class` part names, a filtered one included) · v5 2026-11-26 (the subclass question walks the ancestors of all the sharing classes together) +- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) · v4 2026-11-25 (the statements do not grow with the classes a `class` part names, a filtered one included) · v5 2026-11-26 (the subclass question walks the ancestors of all the sharing classes together, and its bound leaves the sharing classes out) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads, and the cost of the subclass question), `OntologyConceptBindingFirstRowsIT` (the cap of the first rows is per table) +- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads, and the cost of the subclass question), `OntologyConceptBindingFirstRowsIT` (the cap of the first rows is per table), `OntologyConceptBindingStoreAncestorsTest` (the bound of the walk, the statements of chains that meet, and a class under two classes), `OntologyConceptBindingsIT` (a property of a class reached only through a second parent is applicable) - **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) ## Context @@ -400,3 +400,14 @@ classes with one sharing class each. `OntologyConceptBindingFirstRowsIT` guards rows counts the rows of one table and not of all the tables a call reads, and `OntologyShapeCheckAnswerIT` guards it on a draft and a release where one table is crowded and another holds one subclass. + +The walk is bound once for all the sharing classes together, at 10,000. It counts the classes it +finds above the sharing classes and the axioms it reads. It does not count the sharing classes +themselves, so the bound does not shrink with the number of them. Binding inheritance counts as it +did: the class and the classes above it, 10,000 at most. A draft whose sharing classes have more than +10,000 classes or axioms above them together answers 400, where its release answers, because a +release holds no such bound. The reads test asserts 53 statements from a draft where a sharing +class reaches the named class both directly and through a longer chain, because the class that both +chains reach is asked for once, and where it reaches the named class only through its second parent, +and 50 where the only class on the table is one of another ontology, which is no candidate and +leaves nothing to walk. From 7424969f48414ad24494ccabea93c492fae9978e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 13:25:12 -0800 Subject: [PATCH 101/203] Order the expand statement by the related key and start it after a given key The expand statement orders by the key of the related record and takes an optional key to start after, written as a chain of comparisons instead of a row-value comparison. The plan names the result columns that hold that key. The find statement stays without an order. The text of the measure descriptions now says which rows a record and a link count and what a top-records number counts. --- .../it/tests/OntologyShapeFixture.java | 1 + .../ontology/OntologyConceptSqlGenerator.java | 70 ++++++- .../ontology/OntologyStatementService.java | 6 +- .../service/ontology/sql/TypedValues.java | 10 +- .../ontology/OntologyExpandStatementTest.java | 151 ++++++++++++++- .../ontology/OntologyMappingShapeModel.java | 2 +- .../ontology/OntologyMappingShapes.java | 173 +++++++++++++++++- .../ontology/OntologyStatementGoldenTest.java | 5 +- .../ontology/OntologyStatementGoldens.java | 2 +- .../columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 8 + .../columnRelation-expand-inverse-page.sql | 1 + .../columnRelation-expand-inverse.sql | 1 + .../bigquery/linkTable-expand-forward.sql | 1 + .../linkTable-expand-inverse-after.sql | 9 + .../bigquery/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 8 + ...mpositeRelatedKey-expand-inverse-after.sql | 9 + ...agedCompositeRelatedKey-expand-inverse.sql | 8 + .../columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 8 + .../columnRelation-expand-inverse-page.sql | 1 + .../columnRelation-expand-inverse.sql | 1 + .../clickhouse/linkTable-expand-forward.sql | 1 + .../linkTable-expand-inverse-after.sql | 9 + .../clickhouse/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 8 + ...mpositeRelatedKey-expand-inverse-after.sql | 9 + ...agedCompositeRelatedKey-expand-inverse.sql | 8 + .../mysql/columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 8 + .../columnRelation-expand-inverse-page.sql | 1 + .../mysql/columnRelation-expand-inverse.sql | 1 + .../mysql/linkTable-expand-forward.sql | 1 + .../mysql/linkTable-expand-inverse-after.sql | 9 + .../mysql/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 8 + ...mpositeRelatedKey-expand-inverse-after.sql | 9 + ...agedCompositeRelatedKey-expand-inverse.sql | 8 + .../columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 8 + .../columnRelation-expand-inverse-page.sql | 1 + .../columnRelation-expand-inverse.sql | 1 + .../postgres/linkTable-expand-forward.sql | 1 + .../linkTable-expand-inverse-after.sql | 9 + .../postgres/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 8 + ...mpositeRelatedKey-expand-inverse-after.sql | 9 + ...agedCompositeRelatedKey-expand-inverse.sql | 8 + .../columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 8 + .../columnRelation-expand-inverse-page.sql | 1 + .../columnRelation-expand-inverse.sql | 1 + .../redshift/linkTable-expand-forward.sql | 1 + .../linkTable-expand-inverse-after.sql | 9 + .../redshift/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 8 + ...mpositeRelatedKey-expand-inverse-after.sql | 9 + ...agedCompositeRelatedKey-expand-inverse.sql | 8 + .../columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 8 + .../columnRelation-expand-inverse-page.sql | 1 + .../columnRelation-expand-inverse.sql | 1 + .../snowflake/linkTable-expand-forward.sql | 1 + .../linkTable-expand-inverse-after.sql | 9 + .../snowflake/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 8 + ...mpositeRelatedKey-expand-inverse-after.sql | 9 + ...agedCompositeRelatedKey-expand-inverse.sql | 8 + .../spark/columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 8 + .../columnRelation-expand-inverse-page.sql | 1 + .../spark/columnRelation-expand-inverse.sql | 1 + .../spark/linkTable-expand-forward.sql | 1 + .../spark/linkTable-expand-inverse-after.sql | 9 + .../spark/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 8 + ...mpositeRelatedKey-expand-inverse-after.sql | 9 + ...agedCompositeRelatedKey-expand-inverse.sql | 8 + .../trino/columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 8 + .../columnRelation-expand-inverse-page.sql | 1 + .../trino/columnRelation-expand-inverse.sql | 1 + .../trino/linkTable-expand-forward.sql | 1 + .../trino/linkTable-expand-inverse-after.sql | 9 + .../trino/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 8 + ...mpositeRelatedKey-expand-inverse-after.sql | 9 + ...agedCompositeRelatedKey-expand-inverse.sql | 8 + .../tsql/columnRelation-expand-forward.sql | 1 + .../columnRelation-expand-inverse-after.sql | 7 + .../columnRelation-expand-inverse-page.sql | 1 + .../tsql/columnRelation-expand-inverse.sql | 1 + .../tsql/linkTable-expand-forward.sql | 1 + .../tsql/linkTable-expand-inverse-after.sql | 8 + .../tsql/linkTable-expand-inverse.sql | 1 + ...agedCompositeRelatedKey-expand-forward.sql | 7 + ...mpositeRelatedKey-expand-inverse-after.sql | 8 + ...agedCompositeRelatedKey-expand-inverse.sql | 7 + .../ontologyAggregateStatementRequest.json | 2 +- .../data/ontologyExpandStatementRequest.json | 6 +- .../api/data/ontologyStatementPlan.json | 8 +- 102 files changed, 821 insertions(+), 33 deletions(-) create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse.sql diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java index 0aeac7490834..8bd5c9f6977d 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java @@ -338,6 +338,7 @@ private Object request(final Ask ask, final OntologyStatementVersion version) { case EXPAND -> new OntologyExpandStatementRequest() .withVersion(version) .withKey(ask.key()) + .withAfter(ask.after()) .withRelation(relation) .withDirection(ask.direction()); case AGGREGATE -> new OntologyAggregateStatementRequest() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index 5b98933baa22..cf45148a2c34 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -24,6 +24,7 @@ import java.util.Optional; import java.util.UUID; import java.util.function.Supplier; +import java.util.stream.IntStream; import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; import org.openmetadata.schema.api.data.OntologyStatementColumn; import org.openmetadata.schema.api.data.OntologyStatementDirection; @@ -68,6 +69,7 @@ public final class OntologyConceptSqlGenerator { + OntologyConceptQueryService.TABLE_BINDINGS_READ + " table bindings"; private static final String FIRST = alias(0); + private static final String AFTER = "after key"; private static final String COUNT = "COUNT(*) AS records"; private static final String COUNT_LINKS = "COUNT(*) AS links"; private static final String INNER_JOIN = "JOIN"; @@ -151,6 +153,8 @@ public record Generated( * @param rowCap the most rows a reader takes * @param extraRow whether the statement asks for one row more than {@code rowCap} * @param read the tables the statement reads, in join order + * @param orderedBy the indexes of the result columns that hold the key the statement orders by, + * in order, or empty when the statement has no order */ record RecordStatement( TypedStatement text, @@ -158,7 +162,8 @@ record RecordStatement( List columns, int rowCap, boolean extraRow, - List read) {} + List read, + List orderedBy) {} /** One statement about records while it is written. */ private static final class Draft { @@ -175,8 +180,13 @@ private static final class Draft { } RecordStatement finished(final int rowCap, final boolean extraRow) { + return finished(rowCap, extraRow, List.of()); + } + + RecordStatement finished( + final int rowCap, final boolean extraRow, final List orderedBy) { return new RecordStatement( - sql.build(), family, list.columns(), rowCap, extraRow, List.copyOf(read)); + sql.build(), family, list.columns(), rowCap, extraRow, List.copyOf(read), orderedBy); } } @@ -247,11 +257,18 @@ static RecordStatement open( /** * The records that one record relates to: the key of the start record, then the key and the - * display name of each related record. It asks for one row more than a page holds. + * display name of each related record. It asks for one row more than a page holds. The rows are + * ordered by the key of the related record, in key order, and a non-null {@code after} keeps + * only the related records whose key comes after it + * (ADR:2026-11-22-record-statements-start-from-the-identity-table). */ - static RecordStatement expand(final OntologyRelationPath path, final List key) { + static RecordStatement expand( + final OntologyRelationPath path, final List key, final List after) { final MappedTable identity = path.start().identity(); final List values = TypedValues.key(identity.key(), key); + final MappedTable related = path.related().identity(); + final List following = + after == null ? List.of() : TypedValues.key(related.key(), after, AFTER); final String last = alias(path.joins().size()); final Draft draft = new Draft(identity); draft.list.key(path.start(), FIRST).key(path.related(), last).displayName(path.related(), last); @@ -259,8 +276,16 @@ static RecordStatement expand(final OntologyRelationPath path, final List key chain(draft, path); keyEquals(draft.select, identity, values); chainFilters(draft.select, path); + if (after != null) { + keyAfter(draft.select, related, following, last); + } + orderByKey(draft.select, related, last); draft.select.limit(EXPAND_ROWS + 1); - return draft.finished(EXPAND_ROWS, true); + final int relatedKey = identity.keyPaths().size(); + return draft.finished( + EXPAND_ROWS, + true, + IntStream.range(relatedKey, relatedKey + related.keyPaths().size()).boxed().toList()); } /** The number of records of the class in one row: the distinct keys of its identity table. */ @@ -456,6 +481,41 @@ private static void keyEquals( } } + /** + * Keeps the rows whose key comes after {@code values} in key order, written as {@code (k1 > v1) + * OR (k1 = v1 AND k2 > v2) ...} because several engines have no row-value comparison. The engine + * compares, with its own collation. + */ + private static void keyAfter( + final OntologySelectText select, + final MappedTable table, + final List values, + final String alias) { + final List> key = table.keyPaths(); + final TypedStatement.Builder sql = select.where(); + final boolean several = key.size() > 1; + sql.sql(several ? "(" : ""); + for (int part = 0; part < key.size(); part++) { + sql.sql(part == 0 ? "" : " OR ").sql(part == 0 ? "" : "("); + for (int equal = 0; equal < part; equal++) { + sql.column(alias, key.get(equal)).sql(" = ").value(values.get(equal)).sql(" AND "); + } + sql.column(alias, key.get(part)).sql(" > ").value(values.get(part)); + sql.sql(part == 0 ? "" : ")"); + } + sql.sql(several ? ")" : ""); + } + + /** {@code ORDER BY} the key columns of {@code table}, ascending, in key order. */ + private static void orderByKey( + final OntologySelectText select, final MappedTable table, final String alias) { + final TypedStatement.Builder sql = select.clause("ORDER BY"); + final List> key = table.keyPaths(); + for (int part = 0; part < key.size(); part++) { + sql.sql(part == 0 ? "" : ", ").column(alias, key.get(part)); + } + } + private static void rowFilter( final OntologySelectText select, final MappedTable table, final String alias) { final TypedRowFilter filter = table.filter(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java index 243deee42823..d3eba854ae6a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java @@ -213,7 +213,8 @@ public OntologyStatementPlan expand( new Along(request.getRelation(), request.getDirection(), request.getRelatedClass())); return plan( OntologyStatementKind.EXPAND, - OntologyConceptSqlGenerator.expand(route.path(), request.getKey())) + OntologyConceptSqlGenerator.expand( + route.path(), request.getKey(), request.getAfter())) .withRelation(route.relation()) .withVersion(start.version().read()) .withBindingRevisions(route.revisions()); @@ -495,7 +496,8 @@ private static OntologyStatementPlan plan( .withTables(statement.read().stream().map(MappedTable::fullyQualifiedName).toList()) .withColumns(statement.columns()) .withRowCap(statement.rowCap()) - .withExtraRow(statement.extraRow()); + .withExtraRow(statement.extraRow()) + .withOrderedBy(statement.orderedBy()); } private static List revisions( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java index 76d2b59841ec..7f4e7f5fb2da 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java @@ -142,11 +142,17 @@ public static TypedValue value(final Column column, final Object raw) { /** A record key: one value for each key column, in the order of the key. */ public static List key(final List columns, final List values) { + return key(columns, values, "key"); + } + + /** A key that the request calls {@code name}, such as the key of the record to start after. */ + public static List key( + final List columns, final List values, final String name) { if (columns.size() != values.size()) { throw new BadRequestException( String.format( - "The key has %s but the request gives %s", - counted(columns.size(), "column"), counted(values.size(), "value"))); + "The %s has %s but the request gives %s", + name, counted(columns.size(), "column"), counted(values.size(), "value"))); } return IntStream.range(0, columns.size()) .mapToObj(index -> value(columns.get(index), values.get(index))) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java index 2c96b1f6d475..682ba396fb4a 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java @@ -23,6 +23,7 @@ import static org.openmetadata.service.ontology.OntologyMappingShapeModel.sql; import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.PAGED_COMPOSITE_RELATED_KEY; import jakarta.ws.rs.ClientErrorException; import java.util.ArrayList; @@ -63,7 +64,7 @@ void aRelationHeldInAColumnJoinsTheIdentityTableOfTheRelatedClass() { assertEquals( "SELECT t0.id, t1.id, t1.name\nFROM shop.orders t0\n" + "JOIN shop.customers t1 ON t1.id = t0.customer_id\n" - + "WHERE t0.id = 31\n AND t1.id IS NOT NULL\nLIMIT 26", + + "WHERE t0.id = 31\n AND t1.id IS NOT NULL\nORDER BY t1.id\nLIMIT 26", sql(expand)); assertEquals( List.of( @@ -82,7 +83,7 @@ void aRelatedRecordTakesItsKeyFromItsIdentityTableAndNeverFromTheJoinColumn() { assertEquals( "SELECT t0.`id`, t1.`id`\nFROM `shop`.`customers` t0\n" + "JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id`\n" - + "WHERE t0.`id` = 2\n AND t1.`id` IS NOT NULL\nLIMIT 26", + + "WHERE t0.`id` = 2\n AND t1.`id` IS NOT NULL\nORDER BY t1.`id`\nLIMIT 26", sql(expand)); assertEquals(List.of("0 key Customer part 0", "1 key Order part 0"), plan(expand)); } @@ -96,14 +97,14 @@ void aLinkTableJoinsBetweenTheTwoIdentityTablesAndEveryTableKeepsItsRowFilter() + "JOIN shop.order_items t1 ON t1.order_id = t0.id\n" + "JOIN shop.products t2 ON t2.sku = t1.product_sku\n" + "WHERE t0.id = 1\n AND t0.channel = 'web'\n AND t1.quantity > 0\n" - + " AND t2.sku IS NOT NULL\n AND t2.title <> 'Drill'\nLIMIT 26", + + " AND t2.sku IS NOT NULL\n AND t2.title <> 'Drill'\nORDER BY t2.sku\nLIMIT 26", sql(expand(model, "Order", "contains", FORWARD, List.of(1)))); assertEquals( "SELECT t0.sku, t2.id\nFROM shop.products t0\n" + "JOIN shop.order_items t1 ON t1.product_sku = t0.sku\n" + "JOIN shop.orders t2 ON t2.id = t1.order_id\n" + "WHERE t0.sku = 'A-1'\n AND t0.title <> 'Drill'\n AND t1.quantity > 0\n" - + " AND t2.id IS NOT NULL\n AND t2.channel = 'web'\nLIMIT 26", + + " AND t2.id IS NOT NULL\n AND t2.channel = 'web'\nORDER BY t2.id\nLIMIT 26", sql(expand(model, "Product", "contains", INVERSE, List.of("A-1")))); } @@ -112,7 +113,7 @@ void transactSqlAsksForTheExtraRowWithTop() { assertEquals( "SELECT TOP 26 t0.[id], t1.[id], t1.[name]\nFROM [shop].[orders] t0\n" + "JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id]\n" - + "WHERE t0.[id] = 31\n AND t1.[id] IS NOT NULL", + + "WHERE t0.[id] = 31\n AND t1.[id] IS NOT NULL\nORDER BY t1.[id]", sql(expand(model(COLUMN_RELATION, "Mssql"), "Order", "placedBy", FORWARD, List.of(31)))); } @@ -123,12 +124,12 @@ void aRelationFromAClassToItselfJoinsItsIdentityTableToItself() { assertEquals( "SELECT t0.id, t1.id, t1.name\nFROM shop.employees t0\n" + "JOIN shop.employees t1 ON t1.id = t0.manager_id\n" - + "WHERE t0.id = 5\n AND t1.id IS NOT NULL\nLIMIT 26", + + "WHERE t0.id = 5\n AND t1.id IS NOT NULL\nORDER BY t1.id\nLIMIT 26", sql(expand(model, "Employee", "reportsTo", FORWARD, List.of(5)))); assertEquals( "SELECT t0.id, t1.id, t1.name\nFROM shop.employees t0\n" + "JOIN shop.employees t1 ON t1.manager_id = t0.id\n" - + "WHERE t0.id = 1\n AND t1.id IS NOT NULL\nLIMIT 26", + + "WHERE t0.id = 1\n AND t1.id IS NOT NULL\nORDER BY t1.id\nLIMIT 26", sql(expand(model, "Employee", "reportsTo", INVERSE, List.of(1)))); } @@ -138,7 +139,7 @@ void aJoinOverSeveralColumnsEquatesEachPair() { "SELECT t0.id, t1.tenant_id, t1.account_id\nFROM shop.invoices t0\n" + "JOIN shop.accounts t1 ON t1.tenant_id = t0.tenant AND t1.account_id = t0.account\n" + "WHERE t0.id = 9\n AND t1.tenant_id IS NOT NULL\n AND t1.account_id IS NOT NULL\n" - + "LIMIT 26", + + "ORDER BY t1.tenant_id, t1.account_id\nLIMIT 26", sql(expand(model(billing(), POSTGRES), "Invoice", "billedTo", FORWARD, List.of(9)))); } @@ -359,6 +360,128 @@ void theKeyOfTheStartRecordIsParsedAsTheKeyOfItsIdentityTable() { .getMessage()); } + @Test + void aKeyOfOneColumnPagesByTheRelatedKeyAndStartsAfterTheGivenOne() { + final OntologyMappingShapeModel model = model(COLUMN_RELATION, POSTGRES); + + assertEquals( + "SELECT t0.id, t1.id\nFROM shop.customers t0\n" + + "JOIN shop.orders t1 ON t1.customer_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.id IS NOT NULL\n AND t1.id > 25\n" + + "ORDER BY t1.id\nLIMIT 26", + sql(expand(model, "Customer", "placedBy", INVERSE, List.of(1), List.of(25)))); + } + + @Test + void aKeyOfTwoColumnsComparesTheFirstPartThenTheSecondWithoutARowValue() { + final OntologyMappingShapeModel model = model(PAGED_COMPOSITE_RELATED_KEY, POSTGRES); + + assertEquals( + "SELECT t0.id, t1.ledger, t1.seq\nFROM shop.accounts t0\n" + + "JOIN shop.entries t1 ON t1.account_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.ledger IS NOT NULL\n AND t1.seq IS NOT NULL\n" + + " AND (t1.ledger > 'a' OR (t1.ledger = 'a' AND t1.seq > 25))\n" + + "ORDER BY t1.ledger, t1.seq\nLIMIT 26", + sql(expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of("a", 25)))); + assertEquals( + "SELECT TOP 26 t0.[id], t1.[ledger], t1.[seq]\nFROM [shop].[accounts] t0\n" + + "JOIN [shop].[entries] t1 ON t1.[account_id] = t0.[id]\n" + + "WHERE t0.[id] = 1\n AND t1.[ledger] IS NOT NULL\n AND t1.[seq] IS NOT NULL\n" + + " AND (t1.[ledger] > N'a' OR (t1.[ledger] = N'a' AND t1.[seq] > 25))\n" + + "ORDER BY t1.[ledger], t1.[seq]", + sql( + expand( + model(PAGED_COMPOSITE_RELATED_KEY, "Mssql"), + "Account", + "postedTo", + INVERSE, + List.of(1), + List.of("a", 25)))); + } + + @Test + void aKeyOfTwoColumnsOrdersByBothPartsInKeyOrderWhenNoKeyIsGiven() { + assertEquals( + "SELECT t0.`id`, t1.`ledger`, t1.`seq`\nFROM `shop`.`accounts` t0\n" + + "JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id`\n" + + "WHERE t0.`id` = 1\n AND t1.`ledger` IS NOT NULL\n AND t1.`seq` IS NOT NULL\n" + + "ORDER BY t1.`ledger`, t1.`seq`\nLIMIT 26", + sql( + expand( + model(PAGED_COMPOSITE_RELATED_KEY, "Mysql"), + "Account", + "postedTo", + INVERSE, + List.of(1)))); + } + + @Test + void theOrderIsTheKeyOfTheRelatedClassAndTheStartKeyNeverOrdersTheRows() { + final OntologyMappingShapeModel model = model(PAGED_COMPOSITE_RELATED_KEY, POSTGRES); + + assertEquals( + List.of(1, 2), expand(model, "Account", "postedTo", INVERSE, List.of(1), null).orderedBy()); + assertEquals( + List.of(2), expand(model, "Entry", "postedTo", FORWARD, List.of("b", 7), null).orderedBy()); + assertEquals( + "SELECT t0.ledger, t0.seq, t1.id, t1.name\nFROM shop.entries t0\n" + + "JOIN shop.accounts t1 ON t1.id = t0.account_id\n" + + "WHERE t0.ledger = 'b'\n AND t0.seq = 7\n AND t1.id IS NOT NULL\n" + + " AND t1.id > 0\nORDER BY t1.id\nLIMIT 26", + sql(expand(model, "Entry", "postedTo", FORWARD, List.of("b", 7), List.of(0)))); + } + + @Test + void aFindStatementStaysWithoutAnOrderAndOnlyAnExpandStatementIsOrdered() { + final OntologyMappingShapeModel model = model(COLUMN_RELATION, POSTGRES); + final RecordStatement find = OntologyConceptSqlGenerator.find(model.mapped("Customer"), null); + + assertEquals( + "SELECT t0.id, t0.name\nFROM shop.customers t0\nWHERE t0.id IS NOT NULL\nLIMIT 25", + sql(find)); + assertEquals(List.of(), find.orderedBy()); + assertEquals( + List.of(1), expand(model, "Customer", "placedBy", INVERSE, List.of(1), null).orderedBy()); + } + + @Test + void anAfterOfTheWrongTypeOrTheWrongLengthIsRefusedAsTheKeyIs() { + final OntologyMappingShapeModel model = model(PAGED_COMPOSITE_RELATED_KEY, POSTGRES); + + assertEquals( + "The value for column seq does not parse as INT: a whole number is written in ASCII" + + " digits, with a leading minus sign when negative and no leading zeros", + assertThrows( + BadRequestException.class, + () -> + expand( + model, + "Account", + "postedTo", + INVERSE, + List.of(1), + List.of("a", "25 OR 1=1"))) + .getMessage()); + assertEquals( + "The after key has 2 columns but the request gives 1 value", + assertThrows( + BadRequestException.class, + () -> expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of("a"))) + .getMessage()); + assertEquals( + "The after key has 2 columns but the request gives 3 values", + assertThrows( + BadRequestException.class, + () -> expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of("a", 1, 2))) + .getMessage()); + assertEquals( + "The after key has 2 columns but the request gives 0 values", + assertThrows( + BadRequestException.class, + () -> expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of())) + .getMessage()); + } + private static OntologyMappingShapeModel model(final Shape shape, final String serviceType) { return new OntologyMappingShapeModel(shape, serviceType); } @@ -369,7 +492,17 @@ private static RecordStatement expand( final String relation, final OntologyStatementDirection direction, final List key) { - return OntologyConceptSqlGenerator.expand(model.path(type, relation, direction), key); + return expand(model, type, relation, direction, key, null); + } + + private static RecordStatement expand( + final OntologyMappingShapeModel model, + final String type, + final String relation, + final OntologyStatementDirection direction, + final List key, + final List after) { + return OntologyConceptSqlGenerator.expand(model.path(type, relation, direction), key, after); } /** The orders table of the column relation shape, with another join for its relation or none. */ diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java index cf6c44a0e91c..c17ee73e5895 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java @@ -131,7 +131,7 @@ RecordStatement statement(final Ask ask) { case OPEN -> OntologyConceptSqlGenerator.open( mapped(ask.type()), contributing(ask.type()), ask.key()); case EXPAND -> OntologyConceptSqlGenerator.expand( - path(ask.type(), ask.relation(), ask.direction()), ask.key()); + path(ask.type(), ask.relation(), ask.direction()), ask.key(), ask.after()); case AGGREGATE -> aggregate(ask); }; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java index f16975bd38cb..be5999b239a8 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java @@ -32,7 +32,7 @@ import org.openmetadata.schema.type.OntologyRowFilterOperator; /** - * Six small mappings, one for each shape that the table bindings of a class take. Each names its + * Seven small mappings, one for each shape that the table bindings of a class take. Each names its * tables with their rows, its classes, its properties, its bindings, and the statements to ask of * it with the rows each one returns when the tables hold exactly those rows. * @@ -114,12 +114,13 @@ public record BindingSpec( * @param type the class the request is made on * @param matchText for find, the text to match, or null * @param key for open and expand, the key of the record + * @param after for expand, the key of the last related record already held, or null * @param relation for expand and a relation aggregate, the relation to follow * @param columns what each result column holds, one line for each as {@link #columnPlan} writes * it * @param rows the rows the statement can return, each value as text. It returns all of them, or - * as many as its row limit when there are more. Only the rows of a relation aggregate come - * in a fixed order + * as many as its row limit when there are more. The rows of a relation aggregate and of an + * expand come in a fixed order, the expand rows in the key order of the related class * @param measure for an aggregate over a relation, what it counts, or null for the default */ public record Ask( @@ -132,8 +133,9 @@ public record Ask( OntologyStatementDirection direction, List columns, List> rows, - OntologyStatementMeasure measure) { - /** An ask that names no measure. */ + OntologyStatementMeasure measure, + List after) { + /** An ask that names no measure and no key to start after. */ public Ask( final String name, final OntologyStatementKind kind, @@ -144,12 +146,34 @@ public Ask( final OntologyStatementDirection direction, final List columns, final List> rows) { - this(name, kind, type, matchText, key, relation, direction, columns, rows, null); + this(name, kind, type, matchText, key, relation, direction, columns, rows, null, null); + } + + /** An ask that names no key to start after. */ + public Ask( + final String name, + final OntologyStatementKind kind, + final String type, + final String matchText, + final List key, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final List> rows, + final OntologyStatementMeasure measure) { + this(name, kind, type, matchText, key, relation, direction, columns, rows, measure, null); } /** The same ask with another measure. */ public Ask withMeasure(final OntologyStatementMeasure counted) { - return new Ask(name, kind, type, matchText, key, relation, direction, columns, rows, counted); + return new Ask( + name, kind, type, matchText, key, relation, direction, columns, rows, counted, after); + } + + /** The same ask that starts after another key. */ + public Ask withAfter(final List last) { + return new Ask( + name, kind, type, matchText, key, relation, direction, columns, rows, measure, last); } } @@ -500,6 +524,20 @@ public String golden(final String family, final Ask ask) { IntStream.rangeClosed(1, ORDERS_OF_FIRST_CUSTOMER) .mapToObj(order -> texts("1", String.valueOf(order))) .toList()), + new Ask( + "expand-inverse-after", + OntologyStatementKind.EXPAND, + "Customer", + null, + List.of(1), + "placedBy", + OntologyStatementDirection.INVERSE, + CUSTOMER_THEN_ORDER, + IntStream.rangeClosed(26, ORDERS_OF_FIRST_CUSTOMER) + .mapToObj(order -> texts("1", String.valueOf(order))) + .toList(), + null, + List.of(25)), top( "aggregate-forward", "Order", @@ -601,6 +639,15 @@ public String golden(final String family, final Ask ask) { columns("key Product part 0", "key Order part 0"), texts("A-1", "1"), texts("A-1", "2")), + expand( + "expand-inverse-after", + "Product", + List.of("A-1"), + "contains", + OntologyStatementDirection.INVERSE, + columns("key Product part 0", "key Order part 0"), + texts("A-1", "2")) + .withAfter(List.of(1)), top( "aggregate-forward", "Order", @@ -619,6 +666,72 @@ public String golden(final String family, final Ask ask) { texts("B-2", "Bolt", "1"), texts("C-3", "Crate", "1"))))); + /** The entries of account 1: sixty, so that three pages of 25 hold them. */ + public static final int ENTRIES_OF_FIRST_ACCOUNT = 60; + + private static final List ACCOUNT_THEN_ENTRY = + columns("key Account part 0", "key Entry part 0", "key Entry part 1"); + + /** + * 7. A relation whose related class has a two-column key, text then number. Account 1 holds 40 + * entries of ledger {@code a} and 20 of ledger {@code b}, so the first part of the key repeats + * across the end of each page of 25. Account 2 holds entries of a ledger written in mixed case. + * Two rows have a null part in their key and are no records. + */ + public static final Shape PAGED_COMPOSITE_RELATED_KEY = + new Shape( + "pagedCompositeRelatedKey", + List.of( + table( + "accounts", + List.of(integer("id"), text("name")), + row(1, "Main Ledger"), + row(2, "Mixed Ledger")), + new TableSpec( + "entries", + List.of(text("ledger"), integer("seq"), integer("account_id")), + entries())), + List.of("Entry", "Account"), + List.of(data("accountName", true, "Account"), relation("postedTo", "Entry", "Account")), + List.of( + identity("Account", "accounts", List.of("id"), null, bound("accountName", "name")), + identity( + "Entry", + "entries", + List.of("ledger", "seq"), + null, + joined("postedTo", "account_id", "accounts", "id"))), + List.of( + expandRows( + "expand-inverse", + "Account", + List.of(1), + "postedTo", + OntologyStatementDirection.INVERSE, + ACCOUNT_THEN_ENTRY, + firstAccountEntries()), + expandRows( + "expand-inverse-after", + "Account", + List.of(1), + "postedTo", + OntologyStatementDirection.INVERSE, + ACCOUNT_THEN_ENTRY, + firstAccountEntries().subList(25, 60)) + .withAfter(List.of("a", 25)), + expand( + "expand-forward", + "Entry", + List.of("b", 7), + "postedTo", + OntologyStatementDirection.FORWARD, + columns( + "key Entry part 0", + "key Entry part 1", + "key Account part 0", + "displayName Account accountName"), + texts("b", "7", "1", "Main Ledger")))); + public static List all() { return List.of( UNFILTERED_IDENTITY, @@ -626,7 +739,39 @@ public static List all() { COMPOSITE_KEY, REPEATED_CONTRIBUTION, COLUMN_RELATION, - LINK_TABLE); + LINK_TABLE, + PAGED_COMPOSITE_RELATED_KEY); + } + + /** The 60 entries of account 1 in key order, each with the key of its account. */ + private static List> firstAccountEntries() { + final List> rows = new ArrayList<>(); + IntStream.rangeClosed(1, 40).forEach(seq -> rows.add(texts("1", "a", String.valueOf(seq)))); + IntStream.rangeClosed(1, 20).forEach(seq -> rows.add(texts("1", "b", String.valueOf(seq)))); + return List.copyOf(rows); + } + + /** + * The rows of the entries table, in an order that is not the key order: the 60 entries of + * account 1, six entries of account 2, and two rows with a null part in their key. + */ + private static List> entries() { + final List> ordered = new ArrayList<>(); + IntStream.rangeClosed(1, 40).forEach(seq -> ordered.add(row("a", seq, 1))); + IntStream.rangeClosed(1, 20).forEach(seq -> ordered.add(row("b", seq, 1))); + final List> rows = new ArrayList<>(); + for (int index = 0; index < ordered.size(); index++) { + rows.add(ordered.get(index * 7 % ordered.size())); + } + rows.add(row("x", 1, 2)); + rows.add(row("Y", 2, 2)); + rows.add(row("z", 1, 2)); + rows.add(row("Y", 1, 2)); + rows.add(row("x", 2, 2)); + rows.add(row("z", 2, 2)); + rows.add(row("c", null, 1)); + rows.add(row(null, 3, 1)); + return List.copyOf(rows); } /** The 33 orders that are records, each with its total: more than one page of find. */ @@ -789,6 +934,18 @@ private static Ask expand( List.of(rows)); } + private static Ask expandRows( + final String name, + final String type, + final List key, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final List> rows) { + return new Ask( + name, OntologyStatementKind.EXPAND, type, null, key, relation, direction, columns, rows); + } + private static Ask top( final String name, final String type, diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java index 14d172d23832..cfb7f4d17eec 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java @@ -31,12 +31,13 @@ /** * Holds every statement about records to the SQL text that a person read and committed: nine - * engine families, twelve mapping shapes (six that hold the other statements and six that hold the link counts of a relation) and each statement that applies to a shape. The test reads + * engine families, fourteen mapping shapes (seven that hold the other statements and seven that + * hold the link counts of a relation) and each statement that applies to a shape. The test reads * the files and never writes one. */ class OntologyStatementGoldenTest { private static final int FAMILIES = 9; - private static final int STATEMENTS_OF_THE_SHAPES = 47; + private static final int STATEMENTS_OF_THE_SHAPES = 52; static List goldens() { return OntologyStatementGoldens.all(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java index 7b4ed8e45ab6..4d812047cbe0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java @@ -75,7 +75,7 @@ static List all() { return goldens; } - /** The six mapping shapes, then the six that hold the link counts of a relation. */ + /** The seven mapping shapes, then the seven that hold the link counts of a relation. */ static List shapes() { return Stream.concat(OntologyMappingShapes.all().stream(), OntologyLinkShapes.all().stream()) .toList(); diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward.sql index 22464286dd75..5e1d8c892191 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward.sql @@ -3,4 +3,5 @@ FROM `shop`.`orders` t0 JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` WHERE t0.`id` = 31 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..0abba77b0eb1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL + AND t1.`id` > 25 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-page.sql index 24b076e92f77..bdabd0ec2133 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-page.sql @@ -3,4 +3,5 @@ FROM `shop`.`customers` t0 JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` WHERE t0.`id` = 1 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse.sql index baeff0e34921..ca50f9cb0c4f 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse.sql @@ -3,4 +3,5 @@ FROM `shop`.`customers` t0 JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` WHERE t0.`id` = 2 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward.sql index b9c1dc5906de..620ea42e8d81 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward.sql @@ -4,4 +4,5 @@ JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` WHERE t0.`id` = 1 AND t2.`sku` IS NOT NULL +ORDER BY t2.`sku` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..ed49360a060c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL + AND t2.`id` > 1 +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse.sql index a78744d0c5d9..0e3d88801bc8 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse.sql @@ -4,4 +4,5 @@ JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` = 'A-1' AND t2.`id` IS NOT NULL +ORDER BY t2.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..ef10a2e91c16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..258579d76366 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL + AND (t1.`ledger` > 'a' OR (t1.`ledger` = 'a' AND t1.`seq` > 25)) +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..df8f3e169168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward.sql index 22464286dd75..5e1d8c892191 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward.sql @@ -3,4 +3,5 @@ FROM `shop`.`orders` t0 JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` WHERE t0.`id` = 31 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..0abba77b0eb1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL + AND t1.`id` > 25 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-page.sql index 24b076e92f77..bdabd0ec2133 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-page.sql @@ -3,4 +3,5 @@ FROM `shop`.`customers` t0 JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` WHERE t0.`id` = 1 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse.sql index baeff0e34921..ca50f9cb0c4f 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse.sql @@ -3,4 +3,5 @@ FROM `shop`.`customers` t0 JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` WHERE t0.`id` = 2 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward.sql index b9c1dc5906de..620ea42e8d81 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward.sql @@ -4,4 +4,5 @@ JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` WHERE t0.`id` = 1 AND t2.`sku` IS NOT NULL +ORDER BY t2.`sku` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..ed49360a060c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL + AND t2.`id` > 1 +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse.sql index a78744d0c5d9..0e3d88801bc8 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse.sql @@ -4,4 +4,5 @@ JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` = 'A-1' AND t2.`id` IS NOT NULL +ORDER BY t2.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..ef10a2e91c16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..258579d76366 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL + AND (t1.`ledger` > 'a' OR (t1.`ledger` = 'a' AND t1.`seq` > 25)) +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..df8f3e169168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward.sql index 22464286dd75..5e1d8c892191 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward.sql @@ -3,4 +3,5 @@ FROM `shop`.`orders` t0 JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` WHERE t0.`id` = 31 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..0abba77b0eb1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL + AND t1.`id` > 25 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-page.sql index 24b076e92f77..bdabd0ec2133 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-page.sql @@ -3,4 +3,5 @@ FROM `shop`.`customers` t0 JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` WHERE t0.`id` = 1 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse.sql index baeff0e34921..ca50f9cb0c4f 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse.sql @@ -3,4 +3,5 @@ FROM `shop`.`customers` t0 JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` WHERE t0.`id` = 2 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward.sql index b9c1dc5906de..620ea42e8d81 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward.sql @@ -4,4 +4,5 @@ JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` WHERE t0.`id` = 1 AND t2.`sku` IS NOT NULL +ORDER BY t2.`sku` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..ed49360a060c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL + AND t2.`id` > 1 +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse.sql index a78744d0c5d9..0e3d88801bc8 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse.sql @@ -4,4 +4,5 @@ JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` = 'A-1' AND t2.`id` IS NOT NULL +ORDER BY t2.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..ef10a2e91c16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..258579d76366 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL + AND (t1.`ledger` > 'a' OR (t1.`ledger` = 'a' AND t1.`seq` > 25)) +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..df8f3e169168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward.sql index 17685cf2f525..61c984e2a008 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward.sql @@ -3,4 +3,5 @@ FROM shop.orders t0 JOIN shop.customers t1 ON t1.id = t0.customer_id WHERE t0.id = 31 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..8c77c2edcb81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL + AND t1.id > 25 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-page.sql index 2ce0938bdcb3..a89cb7cb88b7 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-page.sql @@ -3,4 +3,5 @@ FROM shop.customers t0 JOIN shop.orders t1 ON t1.customer_id = t0.id WHERE t0.id = 1 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse.sql index bad69ff947e0..2c19999be46d 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse.sql @@ -3,4 +3,5 @@ FROM shop.customers t0 JOIN shop.orders t1 ON t1.customer_id = t0.id WHERE t0.id = 2 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward.sql index d82c4050133d..b14c19c82e04 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward.sql @@ -4,4 +4,5 @@ JOIN shop.order_items t1 ON t1.order_id = t0.id JOIN shop.products t2 ON t2.sku = t1.product_sku WHERE t0.id = 1 AND t2.sku IS NOT NULL +ORDER BY t2.sku LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..31db3cf3687b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL + AND t2.id > 1 +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse.sql index ea8b8eb775f4..9e5493c904e4 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse.sql @@ -4,4 +4,5 @@ JOIN shop.order_items t1 ON t1.product_sku = t0.sku JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku = 'A-1' AND t2.id IS NOT NULL +ORDER BY t2.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..53c8af0352a6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..e70d76fc94d0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL + AND (t1.ledger > 'a' OR (t1.ledger = 'a' AND t1.seq > 25)) +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..57fd96c978bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward.sql index 17685cf2f525..61c984e2a008 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward.sql @@ -3,4 +3,5 @@ FROM shop.orders t0 JOIN shop.customers t1 ON t1.id = t0.customer_id WHERE t0.id = 31 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..8c77c2edcb81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL + AND t1.id > 25 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-page.sql index 2ce0938bdcb3..a89cb7cb88b7 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-page.sql @@ -3,4 +3,5 @@ FROM shop.customers t0 JOIN shop.orders t1 ON t1.customer_id = t0.id WHERE t0.id = 1 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse.sql index bad69ff947e0..2c19999be46d 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse.sql @@ -3,4 +3,5 @@ FROM shop.customers t0 JOIN shop.orders t1 ON t1.customer_id = t0.id WHERE t0.id = 2 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward.sql index d82c4050133d..b14c19c82e04 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward.sql @@ -4,4 +4,5 @@ JOIN shop.order_items t1 ON t1.order_id = t0.id JOIN shop.products t2 ON t2.sku = t1.product_sku WHERE t0.id = 1 AND t2.sku IS NOT NULL +ORDER BY t2.sku LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..31db3cf3687b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL + AND t2.id > 1 +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse.sql index ea8b8eb775f4..9e5493c904e4 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse.sql @@ -4,4 +4,5 @@ JOIN shop.order_items t1 ON t1.product_sku = t0.sku JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku = 'A-1' AND t2.id IS NOT NULL +ORDER BY t2.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..53c8af0352a6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..e70d76fc94d0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL + AND (t1.ledger > 'a' OR (t1.ledger = 'a' AND t1.seq > 25)) +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..57fd96c978bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward.sql index 3720129c469c..e4cd7efefbd6 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward.sql @@ -3,4 +3,5 @@ FROM "shop"."orders" t0 JOIN "shop"."customers" t1 ON t1."id" = t0."customer_id" WHERE t0."id" = 31 AND t1."id" IS NOT NULL +ORDER BY t1."id" LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..854872594cc3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0."id", t1."id" +FROM "shop"."customers" t0 +JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" +WHERE t0."id" = 1 + AND t1."id" IS NOT NULL + AND t1."id" > 25 +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-page.sql index 0dc2dd32097e..e1d4c121fff8 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-page.sql @@ -3,4 +3,5 @@ FROM "shop"."customers" t0 JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" WHERE t0."id" = 1 AND t1."id" IS NOT NULL +ORDER BY t1."id" LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse.sql index 31ca1515ca25..1c48dab6b659 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse.sql @@ -3,4 +3,5 @@ FROM "shop"."customers" t0 JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" WHERE t0."id" = 2 AND t1."id" IS NOT NULL +ORDER BY t1."id" LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward.sql index 6e6707708944..15e52ec06a0c 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward.sql @@ -4,4 +4,5 @@ JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" JOIN "shop"."products" t2 ON t2."sku" = t1."product_sku" WHERE t0."id" = 1 AND t2."sku" IS NOT NULL +ORDER BY t2."sku" LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..f142d63f5425 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0."sku", t2."id" +FROM "shop"."products" t0 +JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" +JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" +WHERE t0."sku" = 'A-1' + AND t2."id" IS NOT NULL + AND t2."id" > 1 +ORDER BY t2."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse.sql index b072d236bcd2..3ba39b2ed7b1 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse.sql @@ -4,4 +4,5 @@ JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" WHERE t0."sku" = 'A-1' AND t2."id" IS NOT NULL +ORDER BY t2."id" LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..25d42fa073c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0."ledger", t0."seq", t1."id", t1."name" +FROM "shop"."entries" t0 +JOIN "shop"."accounts" t1 ON t1."id" = t0."account_id" +WHERE t0."ledger" = 'b' + AND t0."seq" = 7 + AND t1."id" IS NOT NULL +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..778b5cc285e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0."id", t1."ledger", t1."seq" +FROM "shop"."accounts" t0 +JOIN "shop"."entries" t1 ON t1."account_id" = t0."id" +WHERE t0."id" = 1 + AND t1."ledger" IS NOT NULL + AND t1."seq" IS NOT NULL + AND (t1."ledger" > 'a' OR (t1."ledger" = 'a' AND t1."seq" > 25)) +ORDER BY t1."ledger", t1."seq" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..5dc8e4357ac9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0."id", t1."ledger", t1."seq" +FROM "shop"."accounts" t0 +JOIN "shop"."entries" t1 ON t1."account_id" = t0."id" +WHERE t0."id" = 1 + AND t1."ledger" IS NOT NULL + AND t1."seq" IS NOT NULL +ORDER BY t1."ledger", t1."seq" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward.sql index 22464286dd75..5e1d8c892191 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward.sql @@ -3,4 +3,5 @@ FROM `shop`.`orders` t0 JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` WHERE t0.`id` = 31 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..0abba77b0eb1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL + AND t1.`id` > 25 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-page.sql index 24b076e92f77..bdabd0ec2133 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-page.sql @@ -3,4 +3,5 @@ FROM `shop`.`customers` t0 JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` WHERE t0.`id` = 1 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse.sql index baeff0e34921..ca50f9cb0c4f 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse.sql @@ -3,4 +3,5 @@ FROM `shop`.`customers` t0 JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` WHERE t0.`id` = 2 AND t1.`id` IS NOT NULL +ORDER BY t1.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward.sql index b9c1dc5906de..620ea42e8d81 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward.sql @@ -4,4 +4,5 @@ JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` WHERE t0.`id` = 1 AND t2.`sku` IS NOT NULL +ORDER BY t2.`sku` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..ed49360a060c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL + AND t2.`id` > 1 +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse.sql index a78744d0c5d9..0e3d88801bc8 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse.sql @@ -4,4 +4,5 @@ JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` WHERE t0.`sku` = 'A-1' AND t2.`id` IS NOT NULL +ORDER BY t2.`id` LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..ef10a2e91c16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..258579d76366 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL + AND (t1.`ledger` > 'a' OR (t1.`ledger` = 'a' AND t1.`seq` > 25)) +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..df8f3e169168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward.sql index 17685cf2f525..61c984e2a008 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward.sql @@ -3,4 +3,5 @@ FROM shop.orders t0 JOIN shop.customers t1 ON t1.id = t0.customer_id WHERE t0.id = 31 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..8c77c2edcb81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL + AND t1.id > 25 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-page.sql index 2ce0938bdcb3..a89cb7cb88b7 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-page.sql @@ -3,4 +3,5 @@ FROM shop.customers t0 JOIN shop.orders t1 ON t1.customer_id = t0.id WHERE t0.id = 1 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse.sql index bad69ff947e0..2c19999be46d 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse.sql @@ -3,4 +3,5 @@ FROM shop.customers t0 JOIN shop.orders t1 ON t1.customer_id = t0.id WHERE t0.id = 2 AND t1.id IS NOT NULL +ORDER BY t1.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward.sql index d82c4050133d..b14c19c82e04 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward.sql @@ -4,4 +4,5 @@ JOIN shop.order_items t1 ON t1.order_id = t0.id JOIN shop.products t2 ON t2.sku = t1.product_sku WHERE t0.id = 1 AND t2.sku IS NOT NULL +ORDER BY t2.sku LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..31db3cf3687b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL + AND t2.id > 1 +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse.sql index ea8b8eb775f4..9e5493c904e4 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse.sql @@ -4,4 +4,5 @@ JOIN shop.order_items t1 ON t1.product_sku = t0.sku JOIN shop.orders t2 ON t2.id = t1.order_id WHERE t0.sku = 'A-1' AND t2.id IS NOT NULL +ORDER BY t2.id LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..53c8af0352a6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..e70d76fc94d0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL + AND (t1.ledger > 'a' OR (t1.ledger = 'a' AND t1.seq > 25)) +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..57fd96c978bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward.sql index 2c2973fd051d..d9bc14b1a7f5 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward.sql @@ -3,3 +3,4 @@ FROM [shop].[orders] t0 JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id] WHERE t0.[id] = 31 AND t1.[id] IS NOT NULL +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..b528c56c000f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-after.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[id], t1.[id] +FROM [shop].[customers] t0 +JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] +WHERE t0.[id] = 1 + AND t1.[id] IS NOT NULL + AND t1.[id] > 25 +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-page.sql index a402032599ab..ddb6695eee5b 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-page.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-page.sql @@ -3,3 +3,4 @@ FROM [shop].[customers] t0 JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] WHERE t0.[id] = 1 AND t1.[id] IS NOT NULL +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse.sql index dc89b1df8d51..8a6cc1d68193 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse.sql @@ -3,3 +3,4 @@ FROM [shop].[customers] t0 JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] WHERE t0.[id] = 2 AND t1.[id] IS NOT NULL +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward.sql index c70a7bfc7a06..d0189a800cb2 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward.sql @@ -4,3 +4,4 @@ JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] JOIN [shop].[products] t2 ON t2.[sku] = t1.[product_sku] WHERE t0.[id] = 1 AND t2.[sku] IS NOT NULL +ORDER BY t2.[sku] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..4385becac17d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT TOP 26 t0.[sku], t2.[id] +FROM [shop].[products] t0 +JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] +JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] +WHERE t0.[sku] = N'A-1' + AND t2.[id] IS NOT NULL + AND t2.[id] > 1 +ORDER BY t2.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse.sql index e4bbcce171bc..6cf735694cfd 100644 --- a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse.sql +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse.sql @@ -4,3 +4,4 @@ JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] WHERE t0.[sku] = N'A-1' AND t2.[id] IS NOT NULL +ORDER BY t2.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..7bb7c7f81a24 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[ledger], t0.[seq], t1.[id], t1.[name] +FROM [shop].[entries] t0 +JOIN [shop].[accounts] t1 ON t1.[id] = t0.[account_id] +WHERE t0.[ledger] = N'b' + AND t0.[seq] = 7 + AND t1.[id] IS NOT NULL +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..acff38d0e351 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT TOP 26 t0.[id], t1.[ledger], t1.[seq] +FROM [shop].[accounts] t0 +JOIN [shop].[entries] t1 ON t1.[account_id] = t0.[id] +WHERE t0.[id] = 1 + AND t1.[ledger] IS NOT NULL + AND t1.[seq] IS NOT NULL + AND (t1.[ledger] > N'a' OR (t1.[ledger] = N'a' AND t1.[seq] > 25)) +ORDER BY t1.[ledger], t1.[seq] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..90a4477754ad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[id], t1.[ledger], t1.[seq] +FROM [shop].[accounts] t0 +JOIN [shop].[entries] t1 ON t1.[account_id] = t0.[id] +WHERE t0.[id] = 1 + AND t1.[ledger] IS NOT NULL + AND t1.[seq] IS NOT NULL +ORDER BY t1.[ledger], t1.[seq] diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json index 43f2a08e16fb..7249fe36c327 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json @@ -2,7 +2,7 @@ "$id": "https://open-metadata.org/schema/api/data/ontologyAggregateStatementRequest.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "OntologyAggregateStatementRequest", - "description": "Asks for a counting statement. Without a relation it counts the records of the class. With a relation and a direction it returns, by default, the 8 records of the class that relate to the most records along that relation, each with its count. With the measure `linkCount` it returns one number, the links of the relation. A link is a pair of a record of the class that binds the relation and an object key with no null part. Forward from the binding class the count is every link. Inverse from the other class it is the links whose object is a record of the class asked, and the row filter of the object class applies only when the count starts from it.", + "description": "Asks for a counting statement. Without a relation it counts the records of the class. With a relation and a direction it returns, by default, the 8 records of the class that relate to the most records along that relation, each with its count. Each record's number counts its joined rows, so a pair that two rows hold counts twice. In either direction the related record must exist, with a whole key, and pass the row filter of its class, which a forward link count does not ask. So the numbers need not add up to `linkCount`. With the measure `linkCount` it returns one number, the links of the relation. A link is a pair of a record of the class that binds the relation and an object key with no null part. The record passes the row filter of its class, and a row of a link table or another contributing table counts only when it passes that table's own row filter. Forward from the binding class the count is every link. The object need not be a record. Inverse from the other class it is the links whose object is a record of the class asked, and the row filter of the object class applies only when the count starts from it.", "type": "object", "javaType": "org.openmetadata.schema.api.data.OntologyAggregateStatementRequest", "properties": { diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json index 557a93dcd064..893c9c65259a 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json @@ -2,7 +2,7 @@ "$id": "https://open-metadata.org/schema/api/data/ontologyExpandStatementRequest.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "OntologyExpandStatementRequest", - "description": "Asks for the statement that lists the records one record relates to along one relation. The statement asks for 26 rows, and the 26th says only that more exist.", + "description": "Asks for the statement that lists the records one record relates to along one relation. The statement asks for 26 rows, and the 26th says only that more exist. It orders the related records by their key, so a client reads the next page by sending the key of the last related record it holds as `after`. The engine compares and orders with its own collation, so a client must not merge pages that came from two connections.", "type": "object", "javaType": "org.openmetadata.schema.api.data.OntologyExpandStatementRequest", "properties": { @@ -19,6 +19,10 @@ "direction": { "$ref": "ontologyStatementPlan.json#/definitions/direction" }, + "after": { + "description": "The key of the last related record the client holds, in the key order of the related class, with the shape and the typing of `key`. The statement then returns the related records whose key comes after it. Leave it out to start at the first related record. A value of the wrong type for its column, or the wrong number of values, is a 400.", + "$ref": "ontologyStatementPlan.json#/definitions/key" + }, "relatedClass": { "description": "Id of the class at the far end of the relation. Leave it out when the relation names one class on that side, its range for `forward` and its domain for `inverse`.", "$ref": "../../type/basic.json#/definitions/uuid" diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json index b85202801416..43604799ceb4 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json @@ -25,7 +25,7 @@ "items": { "description": "A string, a number or a boolean." } }, "measure": { - "description": "What an aggregate over a relation counts. `topRecords` returns the 8 records of the class that relate to the most records along the relation, each with its count. `linkCount` returns one number, the links of the relation. A link is a pair of a record of the class that binds the relation and an object key with no null part. Forward from the binding class the count is every link. Inverse from the other class it is the links whose object is a record of the start class, and the object need not be a record when the count starts from the binding class. A request that names none asks for `topRecords`.", + "description": "What an aggregate over a relation counts. `topRecords` returns the 8 records of the class that relate to the most records along the relation, each with its count. Each record's number counts its joined rows, so a pair that two rows hold counts twice. In either direction the related record must exist, with a whole key, and pass the row filter of its class, which a forward link count does not ask. So the numbers need not add up to `linkCount`. `linkCount` returns one number, the links of the relation. A link is a pair of a record of the class that binds the relation and an object key with no null part. The record passes the row filter of its class, and a row of a link table or another contributing table counts only when it passes that table's own row filter. Forward from the binding class the count is every link. Inverse from the other class it is the links whose object is a record of the start class, and the object need not be a record when the count starts from the binding class. A request that names none asks for `topRecords`.", "type": "string", "javaType": "org.openmetadata.schema.api.data.OntologyStatementMeasure", "enum": ["topRecords", "linkCount"] @@ -205,6 +205,12 @@ "type": "boolean", "default": false }, + "orderedBy": { + "description": "The indexes of the result columns that hold the key the statement orders by, in key order, when the statement is ordered. An `expand` statement orders by the key of the related record, and a client sends the values of these columns in the last row as `after` to read the next page. Empty on a statement that has no order.", + "type": "array", + "items": { "type": "integer", "minimum": 0 }, + "default": [] + }, "version": { "$ref": "#/definitions/versionRead" }, "bindingRevisions": { "description": "The binding revision of every class whose bindings the statement read. A statement that follows a relation names both classes.", From 9cbcc0fabd8459da542db399c13aad0f47e6a411 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 13:32:56 -0800 Subject: [PATCH 102/203] Test the pages of the expand statement on MySQL and Postgres Three pages over sixty related records with a two-column key, an integer key ordered as a number, a text key of mixed case, a key past the last record and a key of the wrong type or length. An empty key to start after reads as none. --- .../it/tests/OntologyExpandPagingIT.java | 232 ++++++++++++++++++ .../it/tests/OntologyRecordStatementIT.java | 22 ++ .../ontology/OntologyConceptSqlGenerator.java | 11 +- .../ontology/OntologyExpandStatementTest.java | 7 +- .../ontology/OntologyMappingShapes.java | 6 + .../data/ontologyExpandStatementRequest.json | 2 +- 6 files changed, 270 insertions(+), 10 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java new file mode 100644 index 000000000000..9e6534b24734 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java @@ -0,0 +1,232 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.ENTRIES_OF_FIRST_ACCOUNT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.PAGED_COMPOSITE_RELATED_KEY; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; + +/** + * Pages through the records one record relates to, as a client does: it reads the first rows, takes + * the key of the last row it keeps from the columns that the plan names, and sends it as {@code + * after}. The pages must follow each other with no gap and no repeat, and the engine must be the + * one to compare and to order. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyExpandPagingIT extends BaseOntologyApprovalIT { + private static final int PAGE = 25; + private static final String NOT_A_WHOLE_NUMBER = + " does not parse as INT: a whole number is written in ASCII digits, with a leading minus" + + " sign when negative and no leading zeros"; + + @Test + void threePagesOverSixtyRelatedRecordsOfATwoColumnKeyHoldEveryRecordOnce(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "threePages"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PAGED_COMPOSITE_RELATED_KEY).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask first = PAGED_COMPOSITE_RELATED_KEY.ask("expand-inverse"); + + final OntologyStatementPlan firstPlan = fixture.ask(admin(), first, null); + final List> firstRows = OntologyShapeFixture.run(firstPlan.getSql()); + final List afterFirst = lastKey(firstPlan, firstRows.subList(0, PAGE)); + final OntologyStatementPlan secondPlan = + fixture.ask(admin(), first.withAfter(afterFirst), null); + final List> secondRows = OntologyShapeFixture.run(secondPlan.getSql()); + final List afterSecond = lastKey(secondPlan, secondRows.subList(0, PAGE)); + final OntologyStatementPlan thirdPlan = + fixture.ask(admin(), first.withAfter(afterSecond), null); + final List> thirdRows = OntologyShapeFixture.run(thirdPlan.getSql()); + + assertEquals(List.of(1, 2), firstPlan.getOrderedBy()); + assertEquals(List.of("a", "25"), afterFirst); + assertEquals(List.of("b", "10"), afterSecond); + assertEquals(entries(1, 27), firstRows); + assertEquals(entries(26, 52), secondRows); + assertEquals(entries(51, 61), thirdRows); + final List> together = new ArrayList<>(firstRows.subList(0, PAGE)); + together.addAll(secondRows.subList(0, PAGE)); + together.addAll(thirdRows); + assertEquals(entries(1, 61), together); + assertEquals(ENTRIES_OF_FIRST_ACCOUNT, together.size()); + } + } + + @Test + void aKeyThatIsAWholeNumberOrdersAsANumberAndNotAsText(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "numberKey"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, COLUMN_RELATION).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask orders = COLUMN_RELATION.ask("expand-inverse-page"); + + final List> first = + OntologyShapeFixture.run(fixture.ask(admin(), orders, null).getSql()); + final List> afterNine = + OntologyShapeFixture.run( + fixture.ask(admin(), orders.withAfter(List.of(9)), null).getSql()); + + assertEquals(orderRows(1, 27), first); + assertEquals(orderRows(10, 31), afterNine); + } + } + + @Test + void aTextKeyOfMixedCaseFollowsTheOrderOfTheEngineItsPagesAreReadFrom(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "mixedCase"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PAGED_COMPOSITE_RELATED_KEY).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask mixed = PAGED_COMPOSITE_RELATED_KEY.ask("expand-inverse").withKey(List.of(2)); + final List> engine = + OntologyShapeFixture.run( + "SELECT " + + fixture.name("account_id") + + ", " + + fixture.name("ledger") + + ", " + + fixture.name("seq") + + " FROM " + + fixture.from("entries") + + " WHERE " + + fixture.name("account_id") + + " = 2 ORDER BY " + + fixture.name("ledger") + + ", " + + fixture.name("seq")); + + final List> all = + OntologyShapeFixture.run(fixture.ask(admin(), mixed, null).getSql()); + final List> afterX = + OntologyShapeFixture.run( + fixture.ask(admin(), mixed.withAfter(List.of("x", 2)), null).getSql()); + + assertEquals(engine, all); + assertEquals(engine.subList(2, 6), afterX); + if (fixture.family().equals("mysql")) { + assertEquals( + List.of( + List.of("2", "x", "1"), + List.of("2", "x", "2"), + List.of("2", "Y", "1"), + List.of("2", "Y", "2"), + List.of("2", "z", "1"), + List.of("2", "z", "2")), + all); + } + } + } + + @Test + void anAfterPastTheLastRelatedRecordGivesNoRow(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "pastTheEnd"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PAGED_COMPOSITE_RELATED_KEY).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask first = PAGED_COMPOSITE_RELATED_KEY.ask("expand-inverse"); + + assertEquals( + List.of(), + OntologyShapeFixture.run( + fixture.ask(admin(), first.withAfter(List.of("b", 20)), null).getSql())); + assertEquals( + entries(60, 61), + OntologyShapeFixture.run( + fixture.ask(admin(), first.withAfter(List.of("b", 19)), null).getSql())); + } + } + + @Test + void anAfterOfTheWrongTypeOrTheWrongNumberOfPartsIsRefusedWithTheMessageOfAKey( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "badAfter"); + final Ask first = PAGED_COMPOSITE_RELATED_KEY.ask("expand-inverse"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PAGED_COMPOSITE_RELATED_KEY)) { + fixture.bindAll(); + + assertRefused( + 400, + "The value for column seq" + NOT_A_WHOLE_NUMBER, + () -> fixture.ask(admin(), first.withAfter(List.of("a", "twenty")), DRAFT)); + assertRefused( + 400, + "The after key has 2 columns but the request gives 1 value", + () -> fixture.ask(admin(), first.withAfter(List.of("a")), DRAFT)); + assertRefused( + 400, + "The after key has 2 columns but the request gives 3 values", + () -> fixture.ask(admin(), first.withAfter(List.of("a", 1, 2)), DRAFT)); + assertRefused( + 400, + "The after key has 1 column but the request gives 2 values", + () -> + fixture.ask( + admin(), + PAGED_COMPOSITE_RELATED_KEY.ask("expand-forward").withAfter(List.of(1, 2)), + DRAFT)); + assertTrue( + fixture + .ask(admin(), first.withAfter(List.of("a", 1)), DRAFT) + .getSql() + .contains("ORDER BY")); + } + } + + /** The values of the columns that the plan names as the key, in the last row a client keeps. */ + private static List lastKey( + final OntologyStatementPlan plan, final List> kept) { + final List last = kept.getLast(); + return new ArrayList<>(plan.getOrderedBy().stream().map(last::get).toList()); + } + + /** The entries of account 1 from {@code from} to {@code to}, exclusive, by position in key order. */ + private static List> entries(final int from, final int to) { + final List> rows = new ArrayList<>(); + for (int position = from; position < to; position++) { + rows.add( + position <= 40 + ? List.of("1", "a", String.valueOf(position)) + : List.of("1", "b", String.valueOf(position - 40))); + } + return rows; + } + + private static List> orderRows(final int from, final int to) { + final List> rows = new ArrayList<>(); + for (int order = from; order < to; order++) { + rows.add(List.of("1", String.valueOf(order))); + } + return rows; + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java index e6aa691427fe..258ade92642b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java @@ -32,6 +32,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.function.Executable; @@ -325,6 +326,7 @@ private static List> answered( assertEquals(relationOf(shape, ask), plan.getRelation(), name + " relation"); assertEquals(limit.rowCap(), plan.getRowCap(), name + " rowCap"); assertEquals(limit.extraRow(), plan.getExtraRow(), name + " extraRow"); + assertEquals(orderedBy(shape, ask), plan.getOrderedBy(), name + " orderedBy"); assertEquals(releaseRead(release), plan.getVersion(), name + " version"); assertEquals(revisionsOf(fixture, shape, ask), plan.getBindingRevisions(), name + " revisions"); final List> rows = OntologyShapeFixture.run(plan.getSql()); @@ -350,6 +352,11 @@ private static void assertRows(final Ask ask, final Limit limit, final List> listed = new ArrayList<>(ask.rows()); for (final List row : rows) { assertTrue(listed.remove(row), () -> ask.name() + " returned " + row); @@ -357,6 +364,21 @@ private static void assertRows(final Ask ask, final Limit limit, final List orderedBy(final Shape shape, final Ask ask) { + if (ask.kind() != OntologyStatementKind.EXPAND) { + return List.of(); + } + final String related = "key " + relatedTo(shape, ask) + " part"; + return IntStream.range(0, ask.columns().size()) + .filter(index -> ask.columns().get(index).contains(related)) + .boxed() + .toList(); + } + /** What a plan says about the relation that the ask follows, and null when it follows none. */ private static OntologyStatementRelation relationOf(final Shape shape, final Ask ask) { return ask.relation() == null diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index cf45148a2c34..51fa401c9d41 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -258,8 +258,10 @@ static RecordStatement open( /** * The records that one record relates to: the key of the start record, then the key and the * display name of each related record. It asks for one row more than a page holds. The rows are - * ordered by the key of the related record, in key order, and a non-null {@code after} keeps - * only the related records whose key comes after it + * ordered by the key of the related record, in key order, and an {@code after} that holds values + * keeps only the related records whose key comes after it. A null or an empty {@code after} + * starts at the first related record, because a request that leaves the field out reads as an + * empty list * (ADR:2026-11-22-record-statements-start-from-the-identity-table). */ static RecordStatement expand( @@ -267,8 +269,9 @@ static RecordStatement expand( final MappedTable identity = path.start().identity(); final List values = TypedValues.key(identity.key(), key); final MappedTable related = path.related().identity(); + final boolean continued = after != null && !after.isEmpty(); final List following = - after == null ? List.of() : TypedValues.key(related.key(), after, AFTER); + continued ? TypedValues.key(related.key(), after, AFTER) : List.of(); final String last = alias(path.joins().size()); final Draft draft = new Draft(identity); draft.list.key(path.start(), FIRST).key(path.related(), last).displayName(path.related(), last); @@ -276,7 +279,7 @@ static RecordStatement expand( chain(draft, path); keyEquals(draft.select, identity, values); chainFilters(draft.select, path); - if (after != null) { + if (continued) { keyAfter(draft.select, related, following, last); } orderByKey(draft.select, related, last); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java index 682ba396fb4a..c08c1d427a6a 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java @@ -475,11 +475,8 @@ void anAfterOfTheWrongTypeOrTheWrongLengthIsRefusedAsTheKeyIs() { () -> expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of("a", 1, 2))) .getMessage()); assertEquals( - "The after key has 2 columns but the request gives 0 values", - assertThrows( - BadRequestException.class, - () -> expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of())) - .getMessage()); + sql(expand(model, "Account", "postedTo", INVERSE, List.of(1))), + sql(expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of()))); } private static OntologyMappingShapeModel model(final Shape shape, final String serviceType) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java index be5999b239a8..28617e140cea 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java @@ -170,6 +170,12 @@ public Ask withMeasure(final OntologyStatementMeasure counted) { name, kind, type, matchText, key, relation, direction, columns, rows, counted, after); } + /** The same ask about another record. */ + public Ask withKey(final List record) { + return new Ask( + name, kind, type, matchText, record, relation, direction, columns, rows, measure, after); + } + /** The same ask that starts after another key. */ public Ask withAfter(final List last) { return new Ask( diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json index 893c9c65259a..76abea7e58aa 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json @@ -20,7 +20,7 @@ "$ref": "ontologyStatementPlan.json#/definitions/direction" }, "after": { - "description": "The key of the last related record the client holds, in the key order of the related class, with the shape and the typing of `key`. The statement then returns the related records whose key comes after it. Leave it out to start at the first related record. A value of the wrong type for its column, or the wrong number of values, is a 400.", + "description": "The key of the last related record the client holds, in the key order of the related class, with the shape and the typing of `key`. The statement then returns the related records whose key comes after it. Leave it out, or send an empty list, to start at the first related record. A value of the wrong type for its column, or a number of values other than the key has, is a 400.", "$ref": "ontologyStatementPlan.json#/definitions/key" }, "relatedClass": { From 774008b90a57c1ad506bc69913955778fec8dc1a Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 13:51:34 -0800 Subject: [PATCH 103/203] Record how the expand statement pages by the related key --- ...tatements-start-from-the-identity-table.md | 53 +++++++++++++++++-- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md index 0e1af4a8379a..03dabc85a896 100644 --- a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -1,9 +1,9 @@ # A statement about the records of a class starts from its identity table - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (the aggregate statement gains the link count of a relation) +- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (the aggregate statement gains the link count of a relation) · v3 2026-11-26 (the expand statement orders by the related key and starts after a given key) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyLinkCountIT`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyRecordStatementIT`, `OntologyStatementRefusalIT`, `OntologyStatementReleaseDeleteIT`, `OntologyStatementValueIT`, `OntologyConceptQueryIT` +- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyLinkCountIT`, `OntologyExpandPagingIT`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyRecordStatementIT`, `OntologyStatementRefusalIT`, `OntologyStatementReleaseDeleteIT`, `OntologyStatementValueIT`, `OntologyConceptQueryIT` - **Related:** ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles and the subject key that a statement reads), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (amended by this record), ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension (three of its rules are replaced here), ADR:2026-11-21-a-class-has-at-most-one-display-name-property ## Context @@ -141,8 +141,8 @@ A concept that binds several tables and has no identity table got a search-aroun before, and now gets a 409. That request works again once someone picks its identity table. A hop still reaches such a concept, because the rules for a hop are unchanged. -Only the relation count orders its rows. A page of `find` or `expand` is any 25 records, and no -statement reads a second page. Paging needs an order over the key and is a later decision. +Only the relation count and the `expand` statement order their rows (amendment v3). A page of +`find` is any 25 records, and `find` reads no second page. A statement counts and lists joined rows. A link table that repeats one pair shows it twice in `expand` and counts it twice. Two contributing tables that each hold several rows for one key @@ -213,3 +213,48 @@ forward count, so the agreement with the stored-profile count holds for the forw client that wants the links of the relation as a whole asks forward from the class that binds it. Guard: `OntologyAggregateStatementTest`, `OntologyStatementGoldenTest` and `OntologyLinkCountIT`. + +## Amendment v3: the expand statement pages by the key of the related record + +**The statement orders and can start after a key.** `expand` ends with `ORDER BY` the key columns +of the identity table of the related class, ascending, in key order. The request gains `after`, the +key of the last related record the client holds, in the key order of the related class, with the +shape and the typing of `key`. Without `after`, or with an empty one, the statement starts at the +first related record. With it, the statement keeps the related records whose key comes after it: + + (k1 > v1) OR (k1 = v1 AND k2 > v2) OR ... + +The comparison is written out and not as a row-value comparison, because several engines have no +row-value comparison. Each value goes through the escapers of ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text, +typed by its key column. The statement still asks for 26 rows, so the 26th row says that a next page +exists, and a client reads the next page with the key of the 25th row. + +**The plan says which columns hold the key.** `orderedBy` lists the indexes of the result columns +that hold the related key, in key order, and is empty on a statement with no order. A client sends +the values of those columns in the last row it keeps as `after`. + +**A bad `after` is a 400, as a bad `key` is.** A value of the wrong type for its column names the +column, the data type and the problem. A number of values other than the key has says how many the +key has. A request that leaves `after` out reads as an empty list, so an empty `after` cannot be a +400 and means no `after`. + +**The engine compares and orders.** The statement carries no collation, so a page boundary agrees +with the order the engine gives for its own columns. Two engines can order the same text +differently, and so can two collations of one engine: MySQL's default collation puts `x`, `Y` and +`z` in that order, and a binary one puts `Y` first. A client must not merge pages that came from two +connections, and must not pass an `after` from one engine to another. + +**Two related rows with one key are a data fault.** A related key that more than one row holds, or +a link table that repeats a pair, gives the same key on two rows. A page that ends between them +starts the next page after that key, and the second row is skipped. A client folds rows by key. + +**A related record whose key has a null part stays out**, as before, so no page holds it and no +`after` can name it. + +**`find` has no order.** A `find` over a whole table with `ORDER BY` makes each request scan and +sort that table on a warehouse, and a first page of any 25 records is enough +to see what a class holds. `expand` is different: the rows of one record are few, they are found +through the join, and a client needs the second page of them. + +Guard: `OntologyExpandStatementTest`, `OntologyStatementGoldenTest`, `OntologyExpandPagingIT` and +`OntologyRecordStatementIT`. From f9f07a0386878dab8441f7d1b30f709d6d85e7c0 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 21:14:00 -0800 Subject: [PATCH 104/203] Order the expand statement only by a related key whose columns take values --- .../ontology/OntologyConceptSqlGenerator.java | 12 +- .../service/ontology/sql/TypedValues.java | 20 ++- .../ontology/OntologyExpandStatementTest.java | 126 ++++++++++++++++++ 3 files changed, 154 insertions(+), 4 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index 51fa401c9d41..ee0359c13647 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -261,7 +261,8 @@ static RecordStatement open( * ordered by the key of the related record, in key order, and an {@code after} that holds values * keeps only the related records whose key comes after it. A null or an empty {@code after} * starts at the first related record, because a request that leaves the field out reads as an - * empty list + * empty list. A related key with a column of a type that takes no value, such as JSON, gives a + * statement with no order and an empty {@code orderedBy}, and {@code after} on it is refused * (ADR:2026-11-22-record-statements-start-from-the-identity-table). */ static RecordStatement expand( @@ -282,13 +283,18 @@ static RecordStatement expand( if (continued) { keyAfter(draft.select, related, following, last); } - orderByKey(draft.select, related, last); + final boolean ordered = TypedValues.takeValues(related.key()); + if (ordered) { + orderByKey(draft.select, related, last); + } draft.select.limit(EXPAND_ROWS + 1); final int relatedKey = identity.keyPaths().size(); return draft.finished( EXPAND_ROWS, true, - IntStream.range(relatedKey, relatedKey + related.keyPaths().size()).boxed().toList()); + ordered + ? IntStream.range(relatedKey, relatedKey + related.keyPaths().size()).boxed().toList() + : List.of()); } /** The number of records of the class in one row: the distinct keys of its identity table. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java index 7f4e7f5fb2da..82cfc1239b5b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java @@ -218,7 +218,25 @@ private static List members(final Column column, final Object raw) { return list.stream().map(member -> value(column, member)).toList(); } + /** + * Whether every column of {@code columns} has a data type whose values the generator writes. + * {@link #value} refuses a column for which this is false, so a statement can ask it before it + * orders by a key whose values it could never write. + */ + public static boolean takeValues(final List columns) { + return columns.stream().allMatch(column -> kind(column) != null); + } + private static Kind kindOf(final Column column) { + final Kind kind = kind(column); + if (kind == null) { + throw unsupported(column); + } + return kind; + } + + /** The kind of the data type of {@code column}, or null for a type that takes no value. */ + private static Kind kind(final Column column) { return switch (column.getDataType()) { case TINYINT, BYTEINT, SMALLINT, INT, BIGINT, LARGEINT -> Kind.WHOLE; case DECIMAL, NUMERIC, NUMBER, FLOAT, DOUBLE -> Kind.DECIMAL; @@ -228,7 +246,7 @@ private static Kind kindOf(final Column column) { case TIME -> Kind.TIME; case TIMESTAMP, TIMESTAMPZ, DATETIME -> Kind.TIMESTAMP; case UUID -> Kind.UUID; - default -> throw unsupported(column); + default -> null; }; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java index c08c1d427a6a..97cdb7cdd900 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java @@ -479,6 +479,85 @@ void anAfterOfTheWrongTypeOrTheWrongLengthIsRefusedAsTheKeyIs() { sql(expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of()))); } + @Test + void aKeyOfThreeColumnsKeepsEveryEqualityOfTheLeadingPartsInEachLaterDisjunct() { + final OntologyMappingShapeModel model = model(heldItems(tripleKey()), POSTGRES); + + final RecordStatement page = + expand(model, "Owner", "heldBy", INVERSE, List.of(1), List.of("m", 5, 5)); + + assertEquals( + "SELECT t0.id, t1.k1, t1.k2, t1.k3\nFROM shop.owners t0\n" + + "JOIN shop.items t1 ON t1.owner_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.k1 IS NOT NULL\n AND t1.k2 IS NOT NULL\n" + + " AND t1.k3 IS NOT NULL\n" + + " AND (t1.k1 > 'm' OR (t1.k1 = 'm' AND t1.k2 > 5)" + + " OR (t1.k1 = 'm' AND t1.k2 = 5 AND t1.k3 > 5))\n" + + "ORDER BY t1.k1, t1.k2, t1.k3\nLIMIT 26", + sql(page)); + assertEquals(List.of(1, 2, 3), page.orderedBy()); + } + + @Test + void aRelatedKeyWithAJsonColumnWritesNoOrderAndNoOrderedByAndTakesNoAfter() { + final OntologyMappingShapeModel model = + model(heldItems(List.of(new ColumnSpec("id", ColumnDataType.JSON))), POSTGRES); + + final RecordStatement first = expand(model, "Owner", "heldBy", INVERSE, List.of(1)); + + assertEquals( + "SELECT t0.id, t1.id\nFROM shop.owners t0\n" + + "JOIN shop.items t1 ON t1.owner_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.id IS NOT NULL\nLIMIT 26", + sql(first)); + assertEquals(List.of(), first.orderedBy()); + assertEquals( + "SQL generation does not support column type JSON of column id", + assertThrows( + BadRequestException.class, + () -> expand(model, "Owner", "heldBy", INVERSE, List.of(1), List.of(1))) + .getMessage()); + } + + @Test + void aRelatedKeyWithABlobOrAnArrayColumnAmongOthersWritesNoOrder() { + for (final ColumnDataType type : List.of(ColumnDataType.BLOB, ColumnDataType.ARRAY)) { + final OntologyMappingShapeModel model = + model( + heldItems( + List.of(new ColumnSpec("k1", ColumnDataType.INT), new ColumnSpec("k2", type))), + POSTGRES); + + final RecordStatement first = expand(model, "Owner", "heldBy", INVERSE, List.of(1)); + + assertEquals( + "SELECT t0.id, t1.k1, t1.k2\nFROM shop.owners t0\n" + + "JOIN shop.items t1 ON t1.owner_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.k1 IS NOT NULL\n AND t1.k2 IS NOT NULL\nLIMIT 26", + sql(first)); + assertEquals(List.of(), first.orderedBy()); + assertEquals( + "SQL generation does not support column type " + type.value() + " of column k2", + assertThrows( + BadRequestException.class, + () -> expand(model, "Owner", "heldBy", INVERSE, List.of(1), List.of(1, 1))) + .getMessage()); + } + } + + @Test + void aStartKeyWithAJsonColumnIsRefusedAsBefore() { + final OntologyMappingShapeModel model = + model(heldItems(List.of(new ColumnSpec("id", ColumnDataType.JSON))), POSTGRES); + + assertEquals( + "SQL generation does not support column type JSON of column id", + assertThrows( + BadRequestException.class, + () -> expand(model, "Item", "heldBy", FORWARD, List.of(1))) + .getMessage()); + } + private static OntologyMappingShapeModel model(final Shape shape, final String serviceType) { return new OntologyMappingShapeModel(shape, serviceType); } @@ -621,6 +700,53 @@ private static Shape staff() { List.of()); } + private static List tripleKey() { + return List.of( + new ColumnSpec("k1", ColumnDataType.VARCHAR), + new ColumnSpec("k2", ColumnDataType.INT), + new ColumnSpec("k3", ColumnDataType.DECIMAL)); + } + + /** + * An item names its owner. The items table holds the given key columns and the owner column, and + * the identity of the item is the key. Not part of {@code OntologyMappingShapes.all()}. + */ + static Shape heldItems(final List key) { + final List columns = new ArrayList<>(key); + columns.add(new ColumnSpec("owner_id", ColumnDataType.INT)); + return new Shape( + "heldItems", + List.of( + new TableSpec( + "owners", + List.of( + new ColumnSpec("id", ColumnDataType.INT), + new ColumnSpec("name", ColumnDataType.VARCHAR)), + List.of()), + new TableSpec("items", columns, List.of())), + List.of("Owner", "Item"), + List.of(new PropertySpec("heldBy", false, "Item", "Owner")), + List.of( + new BindingSpec( + "Owner", "owners", OntologyBindingRole.IDENTITY, List.of("id"), null, List.of()), + new BindingSpec( + "Item", + "items", + OntologyBindingRole.IDENTITY, + key.stream().map(ColumnSpec::name).toList(), + null, + List.of( + new ColumnBindingSpec( + "heldBy", + "owner_id", + new JoinSpec( + "owners", + OntologyJoinStatus.CONFIRMED, + List.of("owner_id"), + List.of("id")))))), + List.of()); + } + /** An invoice names its account with two columns, the two-column key of the accounts table. */ private static Shape billing() { return new Shape( From a7c2f2c49d1702c84f143c212bac536c87f91f55 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 21:15:35 -0800 Subject: [PATCH 105/203] Add goldens for the forward expand statement with after --- .../ontology/OntologyMappingShapes.java | 40 ++++++++++++++++++- .../ontology/OntologyStatementGoldenTest.java | 2 +- .../columnRelation-expand-forward-after.sql | 8 ++++ .../linkTable-expand-forward-after.sql | 9 +++++ ...mpositeRelatedKey-expand-forward-after.sql | 9 +++++ .../columnRelation-expand-forward-after.sql | 8 ++++ .../linkTable-expand-forward-after.sql | 9 +++++ ...mpositeRelatedKey-expand-forward-after.sql | 9 +++++ .../columnRelation-expand-forward-after.sql | 8 ++++ .../mysql/linkTable-expand-forward-after.sql | 9 +++++ ...mpositeRelatedKey-expand-forward-after.sql | 9 +++++ .../columnRelation-expand-forward-after.sql | 8 ++++ .../linkTable-expand-forward-after.sql | 9 +++++ ...mpositeRelatedKey-expand-forward-after.sql | 9 +++++ .../columnRelation-expand-forward-after.sql | 8 ++++ .../linkTable-expand-forward-after.sql | 9 +++++ ...mpositeRelatedKey-expand-forward-after.sql | 9 +++++ .../columnRelation-expand-forward-after.sql | 8 ++++ .../linkTable-expand-forward-after.sql | 9 +++++ ...mpositeRelatedKey-expand-forward-after.sql | 9 +++++ .../columnRelation-expand-forward-after.sql | 8 ++++ .../spark/linkTable-expand-forward-after.sql | 9 +++++ ...mpositeRelatedKey-expand-forward-after.sql | 9 +++++ .../columnRelation-expand-forward-after.sql | 8 ++++ .../trino/linkTable-expand-forward-after.sql | 9 +++++ ...mpositeRelatedKey-expand-forward-after.sql | 9 +++++ .../columnRelation-expand-forward-after.sql | 7 ++++ .../tsql/linkTable-expand-forward-after.sql | 8 ++++ ...mpositeRelatedKey-expand-forward-after.sql | 8 ++++ 29 files changed, 271 insertions(+), 2 deletions(-) create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward-after.sql create mode 100644 openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward-after.sql diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java index 28617e140cea..2e6d51171c98 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java @@ -509,6 +509,18 @@ public String golden(final String family, final Ask ask) { "key Customer part 0", "displayName Customer customerName"), texts("31", "2", "Grace Hopper")), + expand( + "expand-forward-after", + "Order", + List.of(31), + "placedBy", + OntologyStatementDirection.FORWARD, + columns( + "key Order part 0", + "key Customer part 0", + "displayName Customer customerName"), + texts("31", "2", "Grace Hopper")) + .withAfter(List.of(1)), expand( "expand-inverse", "Customer", @@ -636,6 +648,19 @@ public String golden(final String family, final Ask ask) { texts("1", "A-1", "Anvil"), texts("1", "B-2", "Bolt"), texts("1", "C-3", "Crate")), + expand( + "expand-forward-after", + "Order", + List.of(1), + "contains", + OntologyStatementDirection.FORWARD, + columns( + "key Order part 0", + "key Product part 0", + "displayName Product productTitle"), + texts("1", "B-2", "Bolt"), + texts("1", "C-3", "Crate")) + .withAfter(List.of("A-1")), expand( "expand-inverse", "Product", @@ -736,7 +761,20 @@ public String golden(final String family, final Ask ask) { "key Entry part 1", "key Account part 0", "displayName Account accountName"), - texts("b", "7", "1", "Main Ledger")))); + texts("b", "7", "1", "Main Ledger")), + expand( + "expand-forward-after", + "Entry", + List.of("b", 7), + "postedTo", + OntologyStatementDirection.FORWARD, + columns( + "key Entry part 0", + "key Entry part 1", + "key Account part 0", + "displayName Account accountName"), + texts("b", "7", "1", "Main Ledger")) + .withAfter(List.of(0)))); public static List all() { return List.of( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java index cfb7f4d17eec..dac39c361095 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java @@ -37,7 +37,7 @@ */ class OntologyStatementGoldenTest { private static final int FAMILIES = 9; - private static final int STATEMENTS_OF_THE_SHAPES = 52; + private static final int STATEMENTS_OF_THE_SHAPES = 55; static List goldens() { return OntologyStatementGoldens.all(); diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..c54b5c312081 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL + AND t1.`id` > 1 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..3a8fd8d10aab --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL + AND t2.`sku` > 'A-1' +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..caa609645aaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL + AND t1.`id` > 0 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..c54b5c312081 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL + AND t1.`id` > 1 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..3a8fd8d10aab --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL + AND t2.`sku` > 'A-1' +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..caa609645aaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL + AND t1.`id` > 0 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..c54b5c312081 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL + AND t1.`id` > 1 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..3a8fd8d10aab --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL + AND t2.`sku` > 'A-1' +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..caa609645aaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL + AND t1.`id` > 0 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..2b445527e07d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL + AND t1.id > 1 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..f7d5dd202dad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL + AND t2.sku > 'A-1' +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..477618a62c9c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL + AND t1.id > 0 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..2b445527e07d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL + AND t1.id > 1 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..f7d5dd202dad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL + AND t2.sku > 'A-1' +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..477618a62c9c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL + AND t1.id > 0 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..44ebc1759a54 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0."id", t1."id", t1."name" +FROM "shop"."orders" t0 +JOIN "shop"."customers" t1 ON t1."id" = t0."customer_id" +WHERE t0."id" = 31 + AND t1."id" IS NOT NULL + AND t1."id" > 1 +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..541e45516669 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0."id", t2."sku", t2."title" +FROM "shop"."orders" t0 +JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" +JOIN "shop"."products" t2 ON t2."sku" = t1."product_sku" +WHERE t0."id" = 1 + AND t2."sku" IS NOT NULL + AND t2."sku" > 'A-1' +ORDER BY t2."sku" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..b41322735235 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0."ledger", t0."seq", t1."id", t1."name" +FROM "shop"."entries" t0 +JOIN "shop"."accounts" t1 ON t1."id" = t0."account_id" +WHERE t0."ledger" = 'b' + AND t0."seq" = 7 + AND t1."id" IS NOT NULL + AND t1."id" > 0 +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..c54b5c312081 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL + AND t1.`id` > 1 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..3a8fd8d10aab --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL + AND t2.`sku` > 'A-1' +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..caa609645aaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL + AND t1.`id` > 0 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..2b445527e07d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL + AND t1.id > 1 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..f7d5dd202dad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL + AND t2.sku > 'A-1' +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..477618a62c9c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL + AND t1.id > 0 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..b78a4fdcad32 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward-after.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[id], t1.[id], t1.[name] +FROM [shop].[orders] t0 +JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id] +WHERE t0.[id] = 31 + AND t1.[id] IS NOT NULL + AND t1.[id] > 1 +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..d846705f4dee --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT TOP 26 t0.[id], t2.[sku], t2.[title] +FROM [shop].[orders] t0 +JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] +JOIN [shop].[products] t2 ON t2.[sku] = t1.[product_sku] +WHERE t0.[id] = 1 + AND t2.[sku] IS NOT NULL + AND t2.[sku] > N'A-1' +ORDER BY t2.[sku] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..3b364a041ade --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT TOP 26 t0.[ledger], t0.[seq], t1.[id], t1.[name] +FROM [shop].[entries] t0 +JOIN [shop].[accounts] t1 ON t1.[id] = t0.[account_id] +WHERE t0.[ledger] = N'b' + AND t0.[seq] = 7 + AND t1.[id] IS NOT NULL + AND t1.[id] > 0 +ORDER BY t1.[id] From 32ae5b6e2414af37f808787f169a417d1da52fa1 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 21:21:55 -0800 Subject: [PATCH 106/203] Test a related key of three columns and a related key that takes no value --- .../it/tests/OntologyExpandPagingIT.java | 58 ++++++++++ .../it/tests/OntologyRecordStatementIT.java | 13 +++ .../it/tests/OntologyShapeFixture.java | 9 +- .../ontology/OntologyExpandStatementTest.java | 40 +------ .../ontology/OntologyMappingShapes.java | 102 ++++++++++++++++++ 5 files changed, 181 insertions(+), 41 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java index 9e6534b24734..b6d49f1f3423 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java @@ -20,7 +20,9 @@ import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; import static org.openmetadata.service.ontology.OntologyMappingShapes.ENTRIES_OF_FIRST_ACCOUNT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.JSON_KEY_ITEMS; import static org.openmetadata.service.ontology.OntologyMappingShapes.PAGED_COMPOSITE_RELATED_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.TRIPLE_KEY_ITEMS; import java.util.ArrayList; import java.util.List; @@ -203,6 +205,62 @@ void anAfterOfTheWrongTypeOrTheWrongNumberOfPartsIsRefusedWithTheMessageOfAKey( } } + @Test + void aKeyOfThreeColumnsPagesWithinOneOwnerAndNeverReadsAnotherOwnersRows(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "threeColumns"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, TRIPLE_KEY_ITEMS).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask first = TRIPLE_KEY_ITEMS.ask("expand-inverse"); + final List after = List.of("m", 5, 5); + + final OntologyStatementPlan plan = fixture.ask(admin(), first, null); + final List> all = OntologyShapeFixture.run(plan.getSql()); + final List> ownerOne = + OntologyShapeFixture.run(fixture.ask(admin(), first.withAfter(after), null).getSql()); + final List> ownerTwo = + OntologyShapeFixture.run( + fixture.ask(admin(), first.withKey(List.of(2)).withAfter(after), null).getSql()); + + assertEquals(List.of(1, 2, 3), plan.getOrderedBy()); + assertEquals(first.rows(), all); + assertEquals( + List.of( + List.of("1", "m", "5", "6.00"), + List.of("1", "m", "6", "0.00"), + List.of("1", "n", "0", "0.00")), + ownerOne); + assertEquals( + List.of( + List.of("2", "m", "5", "7.00"), + List.of("2", "m", "7", "0.00"), + List.of("2", "o", "0", "0.00")), + ownerTwo); + } + } + + @Test + void aRelatedKeyOfAColumnTypeThatTakesNoValueIsAnsweredWithoutAnOrder(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "jsonKey"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, JSON_KEY_ITEMS).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask first = JSON_KEY_ITEMS.ask("expand-inverse"); + + final OntologyStatementPlan plan = fixture.ask(admin(), first, null); + + assertEquals(List.of(), plan.getOrderedBy()); + assertTrue(!plan.getSql().contains("ORDER BY"), plan.getSql()); + assertEquals(2, OntologyShapeFixture.run(plan.getSql()).size()); + assertRefused( + 400, + "SQL generation does not support column type JSON of column id", + () -> fixture.ask(admin(), first.withAfter(List.of("1")), DRAFT)); + } + } + /** The values of the columns that the plan names as the key, in the last row a client keeps. */ private static List lastKey( final OntologyStatementPlan plan, final List> kept) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java index 258ade92642b..2b5877b82a34 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java @@ -24,6 +24,7 @@ import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.PAGED_COMPOSITE_RELATED_KEY; import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; import static org.openmetadata.service.ontology.OntologyMappingShapes.columnPlan; @@ -113,6 +114,7 @@ void aRelationHeldInAColumnIsFollowedBothWaysAndPagedByOneExtraRow(final TestNam assertEquals(26, rows.get("expand-inverse-page").size()); assertEquals(25, rows.get("find").size()); assertEquals(List.of(List.of("31", "2", "Grace Hopper")), rows.get("expand-forward")); + assertEquals(List.of(List.of("31", "2", "Grace Hopper")), rows.get("expand-forward-after")); } @Test @@ -125,6 +127,17 @@ void aRelationHeldInALinkTableIsFollowedBothWays(final TestNamespace ns) { List.of("B-2", "Bolt", "1"), List.of("C-3", "Crate", "1")), rows.get("aggregate-inverse")); + assertEquals( + List.of(List.of("1", "B-2", "Bolt"), List.of("1", "C-3", "Crate")), + rows.get("expand-forward-after")); + } + + @Test + void aRelatedKeyOfTwoColumnsIsFollowedBothWaysAndStartsAfterAGivenKey(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, PAGED_COMPOSITE_RELATED_KEY); + + assertEquals(List.of(List.of("b", "7", "1", "Main Ledger")), rows.get("expand-forward")); + assertEquals(List.of(List.of("b", "7", "1", "Main Ledger")), rows.get("expand-forward-after")); } @Test diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java index 8bd5c9f6977d..d91733ee141e 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java @@ -29,7 +29,6 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -98,7 +97,8 @@ final class OntologyShapeFixture implements AutoCloseable { Map.of( ColumnDataType.INT, "INT", ColumnDataType.VARCHAR, "VARCHAR(64)", - ColumnDataType.DECIMAL, "DECIMAL(10,2)"); + ColumnDataType.DECIMAL, "DECIMAL(10,2)", + ColumnDataType.JSON, "JSON"); private final Shape shape; private final Ontology ontology; @@ -166,7 +166,10 @@ private void create(final Handle handle, final TableSpec spec) { .collect(Collectors.joining(", ")) + ")"); created.add(name); - final String marks = String.join(", ", Collections.nCopies(spec.columns().size(), "?")); + final String marks = + spec.columns().stream() + .map(column -> column.type() == ColumnDataType.JSON ? "CAST(? AS JSON)" : "?") + .collect(Collectors.joining(", ")); final String insert = "INSERT INTO " + name + " VALUES (" + marks + ")"; try (PreparedStatement row = handle.getConnection().prepareStatement(insert)) { for (final List values : spec.rows()) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java index 97cdb7cdd900..fc25fc3dfcae 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java @@ -707,44 +707,8 @@ private static List tripleKey() { new ColumnSpec("k3", ColumnDataType.DECIMAL)); } - /** - * An item names its owner. The items table holds the given key columns and the owner column, and - * the identity of the item is the key. Not part of {@code OntologyMappingShapes.all()}. - */ - static Shape heldItems(final List key) { - final List columns = new ArrayList<>(key); - columns.add(new ColumnSpec("owner_id", ColumnDataType.INT)); - return new Shape( - "heldItems", - List.of( - new TableSpec( - "owners", - List.of( - new ColumnSpec("id", ColumnDataType.INT), - new ColumnSpec("name", ColumnDataType.VARCHAR)), - List.of()), - new TableSpec("items", columns, List.of())), - List.of("Owner", "Item"), - List.of(new PropertySpec("heldBy", false, "Item", "Owner")), - List.of( - new BindingSpec( - "Owner", "owners", OntologyBindingRole.IDENTITY, List.of("id"), null, List.of()), - new BindingSpec( - "Item", - "items", - OntologyBindingRole.IDENTITY, - key.stream().map(ColumnSpec::name).toList(), - null, - List.of( - new ColumnBindingSpec( - "heldBy", - "owner_id", - new JoinSpec( - "owners", - OntologyJoinStatus.CONFIRMED, - List.of("owner_id"), - List.of("id")))))), - List.of()); + private static Shape heldItems(final List key) { + return OntologyMappingShapes.heldItems("heldItems", key, List.of(), List.of()); } /** An invoice names its account with two columns, the two-column key of the accounts table. */ diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java index 2e6d51171c98..479c3515dbb0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java @@ -776,6 +776,108 @@ public String golden(final String family, final Ask ask) { texts("b", "7", "1", "Main Ledger")) .withAfter(List.of(0)))); + /** + * The items of two owners, over a related key of three columns. Not in {@link #all()}, so it has + * no goldens. Owner 1 holds eight records and three rows with a null part of the key, and owner 2 + * holds three records whose keys satisfy the later disjuncts of an {@code after} that owner 1 + * starts from. + */ + public static final Shape TRIPLE_KEY_ITEMS = + heldItems( + "tripleKeyItems", + List.of(text("k1"), integer("k2"), decimal("k3")), + tripleKeyRows(), + List.of( + expandRows( + "expand-inverse", + "Owner", + List.of(1), + "heldBy", + OntologyStatementDirection.INVERSE, + columns( + "key Owner part 0", "key Item part 0", "key Item part 1", "key Item part 2"), + List.of( + texts("1", "l", "5", "6.00"), + texts("1", "l", "9", "9.00"), + texts("1", "m", "4", "9.00"), + texts("1", "m", "5", "4.00"), + texts("1", "m", "5", "5.00"), + texts("1", "m", "5", "6.00"), + texts("1", "m", "6", "0.00"), + texts("1", "n", "0", "0.00"))))); + + /** + * The items of one owner whose key is a JSON column, a type that takes no value. Not in {@link + * #all()}. The one record the table holds is no record on an engine that cannot compare JSON. + */ + public static final Shape JSON_KEY_ITEMS = + heldItems( + "jsonKeyItems", + List.of(new ColumnSpec("id", ColumnDataType.JSON)), + List.of(row("{\"a\": 1}", 1), row("{\"a\": 2}", 1)), + List.of( + expandRows( + "expand-inverse", + "Owner", + List.of(1), + "heldBy", + OntologyStatementDirection.INVERSE, + columns("key Owner part 0", "key Item part 0"), + List.of()))); + + /** + * An item names its owner. The items table holds the key columns, in order, and then the owner + * column, and the identity of an item is its key. + * + * @param rows the rows of the items table, each in column order + */ + public static Shape heldItems( + final String name, + final List key, + final List> rows, + final List asks) { + final List columns = new ArrayList<>(key); + columns.add(integer("owner_id")); + return new Shape( + name, + List.of( + new TableSpec( + "owners", + List.of(integer("id"), text("name")), + List.of(row(1, "One"), row(2, "Two"))), + new TableSpec("items", columns, rows)), + List.of("Owner", "Item"), + List.of(relation("heldBy", "Item", "Owner")), + List.of( + identity("Owner", "owners", List.of("id"), null), + identity( + "Item", + "items", + key.stream().map(ColumnSpec::name).toList(), + null, + joined("heldBy", "owner_id", "owners", "id"))), + asks); + } + + /** The rows of the items table of {@link #TRIPLE_KEY_ITEMS}, in an order that is not key order. */ + private static List> tripleKeyRows() { + return List.of( + row("m", 5, new BigDecimal("5"), 1), + row("m", 5, new BigDecimal("7"), 2), + row("n", 0, new BigDecimal("0"), 1), + row("l", 5, new BigDecimal("6"), 1), + row("m", null, new BigDecimal("1"), 1), + row("m", 5, new BigDecimal("6"), 1), + row("o", 0, new BigDecimal("0"), 2), + row("m", 4, new BigDecimal("9"), 1), + row(null, 1, new BigDecimal("1"), 1), + row("m", 6, new BigDecimal("0"), 1), + row("m", 5, new BigDecimal("4"), 1), + row("l", 9, new BigDecimal("9"), 1), + row("m", 7, new BigDecimal("0"), 2), + row("m", 1, null, 1)); + } + public static List all() { return List.of( UNFILTERED_IDENTITY, From 865f3c5986c897a678ed456a3f2d9e2819e84d28 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 21:23:15 -0800 Subject: [PATCH 107/203] Say how a page boundary meets equal keys, and when the plan names an order --- ...tatements-start-from-the-identity-table.md | 27 ++++++++++++++----- .../data/ontologyExpandStatementRequest.json | 5 ++-- .../api/data/ontologyStatementPlan.json | 2 +- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md index 03dabc85a896..08623366d911 100644 --- a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -28,7 +28,7 @@ request and returns an `OntologyStatementPlan`: one `SELECT` and a column plan. |---|---|---|---| | `/find` | optional `matchText` | the key, the display name, then the other bound columns of the identity table | 25 | | `/open` | `key` | the same, then the bound columns of each contributing table | 100, and one more | -| `/expand` | `key`, `relation`, `direction` | the key of the start record, then the key and the display name of each related record | 25, and one more | +| `/expand` | `key`, `relation`, `direction`, optional `after` | the key of the start record, then the key and the display name of each related record | 25, and one more | | `/aggregate` | nothing | the number of records | 1 | | `/aggregate` | `relation`, `direction` | the key and the display name of the records that relate to the most records, each with its count | 8 | @@ -141,7 +141,7 @@ A concept that binds several tables and has no identity table got a search-aroun before, and now gets a 409. That request works again once someone picks its identity table. A hop still reaches such a concept, because the rules for a hop are unchanged. -Only the relation count and the `expand` statement order their rows (amendment v3). A page of +Only `topRecords` and the `expand` statement order their rows (amendment v3). A page of `find` is any 25 records, and `find` reads no second page. A statement counts and lists joined rows. A link table that repeats one pair shows it twice in @@ -230,8 +230,18 @@ typed by its key column. The statement still asks for 26 rows, so the 26th row s exists, and a client reads the next page with the key of the 25th row. **The plan says which columns hold the key.** `orderedBy` lists the indexes of the result columns -that hold the related key, in key order, and is empty on a statement with no order. A client sends -the values of those columns in the last row it keeps as `after`. +that hold the related key, in key order. Only an `expand` statement sets it, and only when its +related key takes values, as the next paragraph says. Every other statement leaves it empty, +`topRecords` too, though it orders by its count. An empty list means the statement takes no +`after`. A client sends the values of those columns in the last row it keeps as `after`. + +**A related key that takes no value is not ordered.** An `expand` statement whose related key has a +column of a type the generator writes no value for, such as JSON, has no order, an empty `orderedBy` +and no `after`, as before this revision. No `after` could follow its first page, and several engines +cannot order such a type. One predicate decides both, so the order and the 400 on `after` cannot +disagree: the statement orders by the related key only when every column of that key has a type +that takes a value. A start key keeps its rule, and a column without such a type is a 400 there, as +for `open`. **A bad `after` is a 400, as a bad `key` is.** A value of the wrong type for its column names the column, the data type and the problem. A number of values other than the key has says how many the @@ -241,7 +251,10 @@ key has. A request that leaves `after` out reads as an empty list, so an empty ` **The engine compares and orders.** The statement carries no collation, so a page boundary agrees with the order the engine gives for its own columns. Two engines can order the same text differently, and so can two collations of one engine: MySQL's default collation puts `x`, `Y` and -`z` in that order, and a binary one puts `Y` first. A client must not merge pages that came from two +`z` in that order, and a binary one puts `Y` first. Two keys that the engine's collation holds equal +compare as one key, such as `x` and `X`, or `e` and `é`, under MySQL's default collation, which +ignores case and accents. A page that ends on one of them starts after both, so the other is +skipped, as for two rows with one key. A client must not merge pages that came from two connections, and must not pass an `after` from one engine to another. **Two related rows with one key are a data fault.** A related key that more than one row holds, or @@ -256,5 +269,7 @@ sort that table on a warehouse, and a first page of any 25 records is enough to see what a class holds. `expand` is different: the rows of one record are few, they are found through the join, and a client needs the second page of them. -Guard: `OntologyExpandStatementTest`, `OntologyStatementGoldenTest`, `OntologyExpandPagingIT` and +Guard: `OntologyExpandStatementTest` (including a related key of three columns, and a related key +with a JSON, BLOB or ARRAY column), `OntologyStatementGoldenTest` (the forward statements with +`after` too), `OntologyExpandPagingIT` (including the three-column pages and the JSON key) and `OntologyRecordStatementIT`. diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json index 76abea7e58aa..118e68d81e77 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json @@ -20,8 +20,9 @@ "$ref": "ontologyStatementPlan.json#/definitions/direction" }, "after": { - "description": "The key of the last related record the client holds, in the key order of the related class, with the shape and the typing of `key`. The statement then returns the related records whose key comes after it. Leave it out, or send an empty list, to start at the first related record. A value of the wrong type for its column, or a number of values other than the key has, is a 400.", - "$ref": "ontologyStatementPlan.json#/definitions/key" + "description": "The key of the last related record the client holds, in the key order of the related class, typed as `key` is: one value for each column of the related key, each parsed as the data type of its column. The statement then returns the related records whose key comes after it. Leave it out, or send an empty list, to start at the first related record. A value of the wrong type for its column, or a number of values other than the key has, is a 400. Two keys that the engine's collation holds equal compare as one key, such as `x` and `X` under MySQL's default collation, so a page that ends on one of them starts after both and the other is skipped.", + "type": "array", + "items": { "description": "A string, a number or a boolean." } }, "relatedClass": { "description": "Id of the class at the far end of the relation. Leave it out when the relation names one class on that side, its range for `forward` and its domain for `inverse`.", diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json index 43604799ceb4..3f14abf995e8 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json @@ -206,7 +206,7 @@ "default": false }, "orderedBy": { - "description": "The indexes of the result columns that hold the key the statement orders by, in key order, when the statement is ordered. An `expand` statement orders by the key of the related record, and a client sends the values of these columns in the last row as `after` to read the next page. Empty on a statement that has no order.", + "description": "The indexes of the result columns that hold the key of the related record, in key order, for a client to send the values of these columns in the last row it keeps as `after` and read the next page. Only an `expand` statement sets it, and only when every column of its related key has a type the generator writes values for, such as a number or a string and not JSON. Every other statement leaves it empty, `topRecords` too, though it orders by its count. An empty list means the statement takes no `after`.", "type": "array", "items": { "type": "integer", "minimum": 0 }, "default": [] From 99a19efeff1e37fabd3b81b500ce686eebde2e14 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 22:35:45 -0800 Subject: [PATCH 108/203] Run the statement of a related key with no value before checking its plan --- .../java/org/openmetadata/it/tests/OntologyExpandPagingIT.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java index b6d49f1f3423..65366c6636aa 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java @@ -250,10 +250,11 @@ void aRelatedKeyOfAColumnTypeThatTakesNoValueIsAnsweredWithoutAnOrder(final Test final Ask first = JSON_KEY_ITEMS.ask("expand-inverse"); final OntologyStatementPlan plan = fixture.ask(admin(), first, null); + final List> rows = OntologyShapeFixture.run(plan.getSql()); + assertEquals(2, rows.size()); assertEquals(List.of(), plan.getOrderedBy()); assertTrue(!plan.getSql().contains("ORDER BY"), plan.getSql()); - assertEquals(2, OntologyShapeFixture.run(plan.getSql()).size()); assertRefused( 400, "SQL generation does not support column type JSON of column id", From 8bcdbcc6a30ad94a75a3f7d7d2ea827acc429f7e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 23:40:01 -0800 Subject: [PATCH 109/203] Let a suggestion task propose a table constraint, applied with the approver's rights --- ...stion-task-can-carry-a-table-constraint.md | 50 +++ .../jdbi3/TaskFormSchemaRepository.java | 1 + .../service/jdbi3/TaskRepository.java | 4 + .../tasks/TableConstraintSuggestion.java | 235 +++++++++++++ .../service/tasks/TaskWorkflowHandler.java | 42 +++ .../TableConstraintSuggestion.json | 31 ++ .../tasks/SuggestionTypeRoutingTest.java | 98 ++++++ .../tasks/TableConstraintSuggestionTest.java | 328 ++++++++++++++++++ .../json/schema/type/suggestionPayload.json | 6 +- 9 files changed, 792 insertions(+), 3 deletions(-) create mode 100644 docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java create mode 100644 openmetadata-service/src/main/resources/json/data/taskFormSchemas/TableConstraintSuggestion.json create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/tasks/SuggestionTypeRoutingTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md new file mode 100644 index 000000000000..c21a2ea5670e --- /dev/null +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -0,0 +1,50 @@ +# A suggestion task can carry a table constraint, and approving it adds the constraint as the approver + +- **Status:** Accepted +- **Revisions:** v1 2026-11-26 (initial) +- **Deciders:** OpenMetadata maintainers +- **Guard:** `TableConstraintSuggestionTest`, `SuggestionTypeRoutingTest`, `TaskTableConstraintSuggestionIT` +- **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type + +## Context + +A suggestion task proposed a description, tags, an owner, a tier, a domain or a custom property. A +table's primary, unique and foreign keys were editable only by a person with write access, with no +way for a connector, an agent or a colleague to propose one and have it reviewed. A proposal needs +the reviewer's rights and a record, so a client does not propose the same key again after it was +declined. + +## Decision + +- `SuggestionPayload.suggestionType` has the value `TableConstraint`. Its `fieldPath` is + `tableConstraints`, and its `suggestedValue` is one `tableConstraint` of `table.json` written as + JSON: `constraintType`, `columns`, and for a foreign key `referredColumns` (full column names) + and `relationshipType`. A seeded task form `TableConstraintSuggestion` (task type `Suggestion`, + category `MetadataUpdate`) carries it, and `TaskFormSchemaRepository` maps the type to that form. +- Filing the task is refused with a 400 unless the task is about a table, the value parses as one + `tableConstraint`, its type is `PRIMARY_KEY`, `UNIQUE` or `FOREIGN_KEY` (`SORT_KEY`, `DIST_KEY` + and `CLUSTER_KEY` are refused), its columns are columns of the table, and each referred column + is a column of an existing table. A foreign key has one referred column for each column, and + another type has none. Approving repeats these checks on the payload the approver resolved with. +- Approving needs `EditAll` on the table. A PATCH of `tableConstraints` maps to no narrower + operation in `ResourceRegistry`, so `TaskRepository#getOperationForSuggestion` returns `EDIT_ALL` + and the task's own authorization check runs before anything is written. +- Applying patches the table as the approver through the table repository, so its own validation + runs. A constraint equal to one already on the table (same type, columns and referred columns) + writes nothing and the task still resolves. A second primary key is refused with a 400 naming + the existing one, before anything is written, and the task stays open. A failure while applying + a constraint is raised to the caller, unlike the other suggestion types, so a task is never + `Approved` for a constraint that was not added. +- Rejecting leaves the table unchanged and the task `Rejected`. +- A client finds the suggestions already made for a table, and the ones declined, by listing the + tasks about that table with type `Suggestion` and a status, and reading `payload.suggestionType` + and `payload.suggestedValue`. No list filter was added for it. +- The change summary covers `description`, `owners` and `columns.description` only, so an agent's + constraint suggestion is not recorded in it. + +## Consequences + +- A client that sees a `suggestionType` it does not know must skip it or show the raw value. A + server that predates this value rejects the payload as an unknown enum value. +- Replacing a primary key takes two steps: remove the old one, then approve the new suggestion. +- Revisit the `EditAll` requirement if a narrower operation for table structure is added. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java index e07ff688aeab..303d9abb4907 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java @@ -394,6 +394,7 @@ private Optional mapSuggestionTypeToSchema(String suggestionType) { return switch (suggestionType.trim().toLowerCase(Locale.ROOT)) { case "description" -> Optional.of("DescriptionSuggestion"); case "tag" -> Optional.of("TagSuggestion"); + case "tableconstraint" -> Optional.of("TableConstraintSuggestion"); default -> Optional.empty(); }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index a0fa8525e3a5..b429bcf18bde 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -90,6 +90,7 @@ import org.openmetadata.service.security.policyevaluator.TaskResourceContext; import org.openmetadata.service.security.policyevaluator.TestCaseResourceContext; import org.openmetadata.service.tasks.IncidentWorkflowStages; +import org.openmetadata.service.tasks.TableConstraintSuggestion; import org.openmetadata.service.tasks.TaskFieldTarget; import org.openmetadata.service.tasks.TaskFieldValidator; import org.openmetadata.service.tasks.TaskFormExecutionResolver; @@ -417,6 +418,7 @@ public void prepare(Task task, boolean update) { TaskFieldValidator.validateDataAccessRequestExpiry(task); TaskFieldTarget.fillDefault(task); TaskFieldTarget.require(task); + TableConstraintSuggestion.require(task); } validateNoDuplicateActiveDataAccessRequest(task); @@ -1506,6 +1508,8 @@ private MetadataOperation getOperationForSuggestion(Task task) { case TIER -> MetadataOperation.EDIT_TIER; case DOMAIN -> MetadataOperation.EDIT_ALL; case CUSTOM_PROPERTY -> MetadataOperation.EDIT_CUSTOM_FIELDS; + // No narrower operation covers tableConstraints: a PATCH of that field needs EditAll. + case TABLE_CONSTRAINT -> MetadataOperation.EDIT_ALL; }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java new file mode 100644 index 000000000000..1c690605d7e2 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java @@ -0,0 +1,235 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.tasks; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * A suggestion task of type {@code TableConstraint} proposes one primary key, unique or foreign key + * constraint for the table it is about. Its {@code suggestedValue} is that {@link TableConstraint} + * written as JSON, and its field path is {@code tableConstraints}. + * + *

      A task is refused when it is filed, and again when it is approved with the resolver's payload + * laid over it, unless it names a table, a supported constraint type, columns of that table and, for + * a foreign key, referred columns of existing tables. Approving also refuses a second primary key + * (ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint). + */ +public final class TableConstraintSuggestion { + public static final String TYPE = "TableConstraint"; + public static final String FIELD_PATH = "tableConstraints"; + private static final String TABLE_FIELDS = "columns,tableConstraints"; + private static final Set SUPPORTED = + EnumSet.of(ConstraintType.PRIMARY_KEY, ConstraintType.UNIQUE, ConstraintType.FOREIGN_KEY); + + private TableConstraintSuggestion() {} + + public static boolean isTableConstraint(Task task) { + return task != null + && task.getPayload() != null + && TYPE.equals(JsonUtils.valueToTree(task.getPayload()).path("suggestionType").asText("")); + } + + /** Refuses filing a table constraint suggestion that names no valid constraint of its table. */ + public static void require(Task task) { + if (isTableConstraint(task)) { + validate(task, JsonUtils.valueToTree(task.getPayload())); + } + } + + /** + * Refuses approving a table constraint suggestion, with the resolver's payload laid over the + * task's, when it is no longer valid or when the table already has another primary key. + */ + public static void requireToApply(Task task, Object requestPayload, String newValue) { + if (isTableConstraint(task)) { + JsonNode merged = + JsonUtils.valueToTree( + TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + Table table = loadTable(task); + TableConstraint constraint = validate(task, merged, table); + toAdd(table, constraint); + } + } + + /** + * The constraint to add to the table: empty when an equal constraint, of the same type, columns + * and referred columns, is already there. + * + * @throws BadRequestException for a primary key when the table has a different one + */ + public static Optional toAdd(Table table, TableConstraint constraint) { + List existing = listOrEmpty(table.getTableConstraints()); + if (existing.stream().anyMatch(present -> sameConstraint(present, constraint))) { + return Optional.empty(); + } + if (constraint.getConstraintType() == ConstraintType.PRIMARY_KEY) { + existing.stream() + .filter(present -> present.getConstraintType() == ConstraintType.PRIMARY_KEY) + .findFirst() + .ifPresent( + present -> { + throw BadRequestException.of( + "Table '%s' already has a primary key on columns %s; a table has one primary key" + .formatted(table.getFullyQualifiedName(), present.getColumns())); + }); + } + return Optional.of(constraint); + } + + /** The table's constraints with {@code constraint} added. */ + public static List withConstraint(Table table, TableConstraint constraint) { + List constraints = new ArrayList<>(listOrEmpty(table.getTableConstraints())); + constraints.add(constraint); + return constraints; + } + + /** The constraint a task's {@code suggestedValue} carries. */ + public static TableConstraint constraintOf(JsonNode payload) { + String suggestedValue = payload.path("suggestedValue").asText(""); + try { + TableConstraint constraint = JsonUtils.readValue(suggestedValue, TableConstraint.class); + if (constraint == null || constraint.getConstraintType() == null) { + throw BadRequestException.of( + "Suggested value is not a table constraint: it has no constraintType"); + } + return constraint; + } catch (BadRequestException e) { + throw e; + } catch (RuntimeException e) { + throw BadRequestException.of( + "Suggested value is not a table constraint: %s".formatted(suggestedValue)); + } + } + + private static void validate(Task task, JsonNode payload) { + validate(task, payload, loadTable(task)); + } + + private static TableConstraint validate(Task task, JsonNode payload, Table table) { + String fieldPath = payload.path(TaskFieldTarget.FIELD_PATH).asText(null); + if (!FIELD_PATH.equals(fieldPath)) { + throw BadRequestException.of( + "Field path of a table constraint suggestion must be '%s', not '%s'" + .formatted(FIELD_PATH, fieldPath)); + } + TableConstraint constraint = constraintOf(payload); + if (!SUPPORTED.contains(constraint.getConstraintType())) { + throw BadRequestException.of( + "Table constraint type %s cannot be suggested; use PRIMARY_KEY, UNIQUE or FOREIGN_KEY" + .formatted(constraint.getConstraintType())); + } + requireColumns(table, constraint); + requireReferredColumns(constraint); + return constraint; + } + + private static Table loadTable(Task task) { + if (task.getAbout() == null || !Entity.TABLE.equals(task.getAbout().getType())) { + throw BadRequestException.of( + "A table constraint suggestion must be about a table, not %s" + .formatted(task.getAbout() == null ? "nothing" : task.getAbout().getType())); + } + return Entity.getEntity(task.getAbout(), TABLE_FIELDS, Include.NON_DELETED); + } + + private static void requireColumns(Table table, TableConstraint constraint) { + if (nullOrEmpty(constraint.getColumns())) { + throw BadRequestException.of("A table constraint needs at least one column"); + } + for (String name : constraint.getColumns()) { + if (!hasColumn(table, name)) { + throw BadRequestException.of( + "Column '%s' is not a column of table '%s'" + .formatted(name, table.getFullyQualifiedName())); + } + } + } + + private static void requireReferredColumns(TableConstraint constraint) { + List referred = listOrEmpty(constraint.getReferredColumns()); + if (constraint.getConstraintType() != ConstraintType.FOREIGN_KEY) { + if (!referred.isEmpty()) { + throw BadRequestException.of( + "Only a foreign key has referredColumns, not %s" + .formatted(constraint.getConstraintType())); + } + return; + } + if (referred.size() != constraint.getColumns().size()) { + throw BadRequestException.of( + "A foreign key needs one referred column for each of its %d columns, not %d" + .formatted(constraint.getColumns().size(), referred.size())); + } + referred.forEach(TableConstraintSuggestion::requireReferredColumn); + } + + private static void requireReferredColumn(String columnFqn) { + Table referredTable; + String columnName; + try { + referredTable = + Entity.getEntityByName( + Entity.TABLE, + FullyQualifiedName.getTableFQN(columnFqn), + "columns", + Include.NON_DELETED); + columnName = FullyQualifiedName.getColumnName(columnFqn); + } catch (EntityNotFoundException | IllegalArgumentException e) { + throw unresolved(columnFqn); + } + if (!hasColumn(referredTable, columnName)) { + throw unresolved(columnFqn); + } + } + + private static BadRequestException unresolved(String columnFqn) { + return BadRequestException.of( + "Referred column '%s' does not resolve to a column of an existing table" + .formatted(columnFqn)); + } + + private static boolean hasColumn(Table table, String name) { + return listOrEmpty(table.getColumns()).stream() + .filter(Objects::nonNull) + .map(Column::getName) + .anyMatch(name::equals); + } + + private static boolean sameConstraint(TableConstraint present, TableConstraint suggested) { + return present.getConstraintType() == suggested.getConstraintType() + && listOrEmpty(present.getColumns()).equals(listOrEmpty(suggested.getColumns())) + && listOrEmpty(present.getReferredColumns()) + .equals(listOrEmpty(suggested.getReferredColumns())); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 5052089f21d6..6d6c4cf8d687 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -41,6 +41,7 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.entity.tasks.Task; import org.openmetadata.schema.governance.workflows.WorkflowDefinition; import org.openmetadata.schema.governance.workflows.elements.EdgeDefinition; @@ -48,6 +49,7 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EventType; import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.type.TaskAvailableTransition; import org.openmetadata.schema.type.TaskComment; @@ -198,6 +200,9 @@ public Task resolveTask( effectiveResolutionType, user); TaskFieldTarget.requireToApply(task, effectiveResolutionType, resolvedPayload); + if (isPositiveResolution(effectiveResolutionType)) { + TableConstraintSuggestion.requireToApply(task, resolvedPayload, newValue); + } ReviewOutcome outcome = ApprovalDecisionService.recordForTask(task, effectiveResolutionType, review, comment, user); @@ -840,6 +845,10 @@ private void applyEntityChanges( } catch (Exception e) { LOG.error( "[TaskWorkflowHandler] Failed to apply entity changes for task '{}'", task.getId(), e); + if (TableConstraintSuggestion.isTableConstraint(task)) { + // The task stays open: approving it must not report a constraint that was not added. + throw e; + } } } @@ -1378,14 +1387,47 @@ private void applySuggestion( tags.size(), entity.getName()); } + } else if (TableConstraintSuggestion.TYPE.equals(suggestionType)) { + applyTableConstraint(payloadNode, entity, repository, user); } else { LOG.debug("[TaskWorkflowHandler] Unknown suggestion type: {}", suggestionType); } } catch (Exception e) { LOG.error("[TaskWorkflowHandler] Failed to apply Suggestion", e); + if (TableConstraintSuggestion.isTableConstraint(task)) { + throw e; + } } } + /** + * Adds the suggested constraint to the table as the approver, through the table repository's own + * validation. An equal constraint already on the table is left as it is. + */ + private void applyTableConstraint( + JsonNode payloadNode, + EntityInterface entity, + EntityRepository repository, + String user) { + Table table = (Table) entity; + TableConstraint constraint = TableConstraintSuggestion.constraintOf(payloadNode); + Optional toAdd = TableConstraintSuggestion.toAdd(table, constraint); + if (toAdd.isEmpty()) { + LOG.info( + "[TaskWorkflowHandler] Table '{}' already has the suggested {} constraint", + table.getFullyQualifiedName(), + constraint.getConstraintType()); + return; + } + String before = JsonUtils.pojoToJson(table); + table.setTableConstraints(TableConstraintSuggestion.withConstraint(table, toAdd.get())); + saveChange(table, repository, user, before, null); + LOG.info( + "[TaskWorkflowHandler] Applied {} constraint suggestion to table '{}'", + constraint.getConstraintType(), + table.getFullyQualifiedName()); + } + private void applyEntityLevelTags( EntityInterface entity, EntityRepository repository, String user, List tags) { String before = JsonUtils.pojoToJson(entity); diff --git a/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TableConstraintSuggestion.json b/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TableConstraintSuggestion.json new file mode 100644 index 000000000000..de72b285db4b --- /dev/null +++ b/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TableConstraintSuggestion.json @@ -0,0 +1,31 @@ +{ + "name": "TableConstraintSuggestion", + "displayName": "Table Constraint Suggestion", + "taskType": "Suggestion", + "taskCategory": "MetadataUpdate", + "formSchema": { + "type": "object", + "required": [ + "suggestedValue" + ], + "properties": { + "suggestedValue": { + "type": "string", + "title": "Suggested Table Constraint (JSON)" + }, + "reasoning": { + "type": "string", + "title": "Reason for suggestion" + } + } + }, + "uiSchema": { + "suggestedValue": { + "ui:widget": "textarea" + }, + "reasoning": { + "ui:widget": "textarea" + } + }, + "fullyQualifiedName": "TableConstraintSuggestion" +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/SuggestionTypeRoutingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/SuggestionTypeRoutingTest.java new file mode 100644 index 000000000000..4b731abf8f93 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/SuggestionTypeRoutingTest.java @@ -0,0 +1,98 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.tasks; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; + +import java.io.InputStream; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.TaskFormSchemaRepository; +import org.openmetadata.service.jdbi3.TaskRepository; + +class SuggestionTypeRoutingTest { + + @ParameterizedTest + @CsvSource({ + "Description,DescriptionSuggestion", + "Tag,TagSuggestion", + "TableConstraint,TableConstraintSuggestion", + "tableconstraint,TableConstraintSuggestion" + }) + void aSuggestionTypeMapsToItsSeededForm(String suggestionType, String expectedForm) + throws Exception { + TaskFormSchemaRepository repository = mock(TaskFormSchemaRepository.class, CALLS_REAL_METHODS); + Method method = + TaskFormSchemaRepository.class.getDeclaredMethod("getSuggestionSchemaName", Object.class); + method.setAccessible(true); + + Object form = method.invoke(repository, Map.of("suggestionType", suggestionType)); + + assertEquals(Optional.of(expectedForm), form); + } + + @Test + void theSeededTableConstraintFormIsASuggestionForm() throws Exception { + try (InputStream stream = + getClass() + .getClassLoader() + .getResourceAsStream("json/data/taskFormSchemas/TableConstraintSuggestion.json")) { + Map form = + JsonUtils.readValue(new String(stream.readAllBytes(), StandardCharsets.UTF_8), Map.class); + + assertEquals("TableConstraintSuggestion", form.get("name")); + assertEquals("Suggestion", form.get("taskType")); + assertEquals("MetadataUpdate", form.get("taskCategory")); + assertTrue(form.toString().contains("suggestedValue")); + } + } + + @ParameterizedTest + @CsvSource({ + "Description,EDIT_DESCRIPTION", + "Tag,EDIT_TAGS", + "Owner,EDIT_OWNERS", + "Tier,EDIT_TIER", + "Domain,EDIT_ALL", + "CustomProperty,EDIT_CUSTOM_FIELDS", + "TableConstraint,EDIT_ALL" + }) + void approvingASuggestionNeedsTheOperationForItsType( + String suggestionType, MetadataOperation expected) throws Exception { + TaskRepository repository = mock(TaskRepository.class, CALLS_REAL_METHODS); + Task task = + new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withPayload( + Map.of("suggestionType", suggestionType, "fieldPath", "x", "suggestedValue", "y")); + Method method = TaskRepository.class.getDeclaredMethod("getOperationForSuggestion", Task.class); + method.setAccessible(true); + + assertEquals(expected, method.invoke(repository, task)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java new file mode 100644 index 000000000000..c5706e603882 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -0,0 +1,328 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.tasks; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import jakarta.json.JsonPatch; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.schema.type.TableConstraint.RelationshipType; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.EntityRepository; + +class TableConstraintSuggestionTest { + private static final String ORDERS = "svc.db.schema.orders"; + private static final String CUSTOMERS = "svc.db.schema.customers"; + private MockedStatic entity; + private Table orders; + + @BeforeEach + void setUp() { + orders = table("orders", ORDERS, "order_id", "customer_id", "email"); + Table customers = table("customers", CUSTOMERS, "id"); + entity = mockStatic(Entity.class); + entity + .when(() -> Entity.getEntity(any(EntityReference.class), anyString(), any(Include.class))) + .thenAnswer(invocation -> orders); + entity + .when(() -> Entity.getEntityByName(eq(Entity.TABLE), anyString(), anyString(), any())) + .thenAnswer( + invocation -> { + String fqn = invocation.getArgument(1); + if (CUSTOMERS.equals(fqn)) { + return customers; + } + throw EntityNotFoundException.byName(fqn); + }); + } + + @AfterEach + void tearDown() { + entity.close(); + } + + @Test + void aPrimaryKeyOnExistingColumns_isAccepted() { + Task task = task(Entity.TABLE, constraint(ConstraintType.PRIMARY_KEY, List.of("order_id"))); + + assertDoesNotThrow(() -> TableConstraintSuggestion.require(task)); + } + + @Test + void aForeignKeyToAnotherTablesColumn_isAccepted() { + TableConstraint foreignKey = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id")) + .withRelationshipType(RelationshipType.MANY_TO_ONE); + + assertDoesNotThrow(() -> TableConstraintSuggestion.require(task(Entity.TABLE, foreignKey))); + } + + @Test + void aTaskAboutAnotherEntityType_isRefused() { + Task task = task(Entity.DASHBOARD, constraint(ConstraintType.UNIQUE, List.of("email"))); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals( + "A table constraint suggestion must be about a table, not dashboard", e.getMessage()); + } + + @Test + void aSuggestedValueThatIsNotAConstraint_isRefused() { + Task task = taskWithValue("not json at all"); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals("Suggested value is not a table constraint: not json at all", e.getMessage()); + } + + @Test + void aConstraintWithoutAType_isRefused() { + Task task = taskWithValue("{\"columns\":[\"email\"]}"); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals( + "Suggested value is not a table constraint: it has no constraintType", e.getMessage()); + } + + @Test + void aColumnTheTableDoesNotHave_isRefused() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("missing"))); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals("Column 'missing' is not a column of table '" + ORDERS + "'", e.getMessage()); + } + + @Test + void aReferredColumnThatResolvesToNothing_isRefused() { + TableConstraint missingTable = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of("svc.db.schema.ghosts.id")); + TableConstraint missingColumn = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".nope")); + + assertEquals( + "Referred column 'svc.db.schema.ghosts.id' does not resolve to a column of an existing table", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, missingTable))) + .getMessage()); + assertEquals( + "Referred column '" + + CUSTOMERS + + ".nope' does not resolve to a column of an existing table", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, missingColumn))) + .getMessage()); + } + + @Test + void aSortKey_isRefused() { + Task task = task(Entity.TABLE, constraint(ConstraintType.SORT_KEY, List.of("order_id"))); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals( + "Table constraint type SORT_KEY cannot be suggested; use PRIMARY_KEY, UNIQUE or FOREIGN_KEY", + e.getMessage()); + } + + @Test + void aFieldPathOtherThanTableConstraints_isRefused() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + @SuppressWarnings("unchecked") + Map payload = (Map) task.getPayload(); + payload.put("fieldPath", "description"); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals( + "Field path of a table constraint suggestion must be 'tableConstraints', not 'description'", + e.getMessage()); + } + + @Test + void aSecondPrimaryKey_isRefusedAtApprovalNamingTheExistingOne() { + orders.setTableConstraints( + List.of(constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")))); + Task task = task(Entity.TABLE, constraint(ConstraintType.PRIMARY_KEY, List.of("email"))); + + BadRequestException e = + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.requireToApply(task, null, null)); + + assertEquals( + "Table '" + + ORDERS + + "' already has a primary key on columns [order_id]; " + + "a table has one primary key", + e.getMessage()); + } + + @Test + void anEqualConstraintAlreadyOnTheTable_addsNothing() { + TableConstraint present = constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")); + orders.setTableConstraints(List.of(present)); + + assertEquals( + Optional.empty(), + TableConstraintSuggestion.toAdd( + orders, constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")))); + } + + @Test + void aUniqueConstraintBesidesAPrimaryKey_isAdded() { + orders.setTableConstraints( + List.of(constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")))); + TableConstraint unique = constraint(ConstraintType.UNIQUE, List.of("email")); + + assertEquals(Optional.of(unique), TableConstraintSuggestion.toAdd(orders, unique)); + } + + @Test + void applyingASuggestion_addsTheConstraintToTheTableAsTheApprover() throws Exception { + EntityRepository repository = mock(EntityRepository.class); + TableConstraint foreignKey = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id")) + .withRelationshipType(RelationshipType.MANY_TO_ONE); + + invokeApplySuggestion(task(Entity.TABLE, foreignKey), orders, repository, "approver"); + + ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); + verify(repository) + .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any(), (String) any()); + String operations = patch.getValue().toJsonArray().toString(); + assertTrue(operations.contains("\"op\":\"add\""), operations); + assertTrue(operations.contains("\"path\":\"/tableConstraints\""), operations); + assertTrue(operations.contains("\"relationshipType\":\"MANY_TO_ONE\""), operations); + assertTrue(operations.contains("\"referredColumns\":[\"" + CUSTOMERS + ".id\"]"), operations); + } + + @Test + void applyingASuggestionTheTableAlreadyHas_writesNothing() throws Exception { + EntityRepository repository = mock(EntityRepository.class); + orders.setTableConstraints( + new ArrayList<>(List.of(constraint(ConstraintType.UNIQUE, List.of("email"))))); + + invokeApplySuggestion( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), + orders, + repository, + "approver"); + + verify(repository, never()) + .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + assertEquals(1, orders.getTableConstraints().size()); + } + + private static void invokeApplySuggestion( + Task task, Table table, EntityRepository repository, String user) throws Exception { + Method applySuggestion = + TaskWorkflowHandler.class.getDeclaredMethod( + "applySuggestion", + Task.class, + Object.class, + EntityInterface.class, + EntityRepository.class, + String.class); + applySuggestion.setAccessible(true); + applySuggestion.invoke( + TaskWorkflowHandler.getInstance(), task, task.getPayload(), table, repository, user); + } + + private static Table table(String name, String fqn, String... columns) { + List columnList = new ArrayList<>(); + for (String column : columns) { + columnList.add(new Column().withName(column)); + } + return new Table() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName(fqn) + .withColumns(columnList); + } + + private static TableConstraint constraint(ConstraintType type, List columns) { + return new TableConstraint().withConstraintType(type).withColumns(columns); + } + + private Task task(String aboutType, TableConstraint constraint) { + return taskWithValue(aboutType, JsonUtils.pojoToJson(constraint)); + } + + private Task taskWithValue(String value) { + return taskWithValue(Entity.TABLE, value); + } + + private Task taskWithValue(String aboutType, String value) { + Map payload = new java.util.LinkedHashMap<>(); + payload.put("suggestionType", "TableConstraint"); + payload.put("fieldPath", "tableConstraints"); + payload.put("suggestedValue", value); + return new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withAbout( + new EntityReference() + .withId(orders.getId()) + .withType(aboutType) + .withFullyQualifiedName(ORDERS)) + .withPayload(payload); + } +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json b/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json index b2c1dfc3832b..60cec9b9ee71 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json @@ -9,10 +9,10 @@ "suggestionType": { "description": "Type of suggestion.", "type": "string", - "enum": ["Description", "Tag", "Owner", "Tier", "Domain", "CustomProperty"] + "enum": ["Description", "Tag", "Owner", "Tier", "Domain", "CustomProperty", "TableConstraint"] }, "fieldPath": { - "description": "Path to the property being updated. For a Description or Tag suggestion it is written as .[....]., for example 'columns.customer_id.description', or 'description' / 'tags' alone for the entity itself.", + "description": "Path to the property being updated. For a Description or Tag suggestion it is written as .[....]., for example 'columns.customer_id.description', or 'description' / 'tags' alone for the entity itself. A TableConstraint suggestion's path is 'tableConstraints'.", "type": "string" }, "currentValue": { @@ -20,7 +20,7 @@ "type": "string" }, "suggestedValue": { - "description": "Suggested new value for the field.", + "description": "Suggested new value for the field. For a TableConstraint suggestion it is one tableConstraint object written as JSON: its constraintType (PRIMARY_KEY, UNIQUE or FOREIGN_KEY), its columns, and for a foreign key its referredColumns as full column names and its relationshipType.", "type": "string" }, "confidence": { From 954c8eeb1aaf54ec202e5d574b465b22f3571853 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 26 Nov 2026 23:47:45 -0800 Subject: [PATCH 110/203] Test that a suggested table constraint is applied as the approver on MySQL and Postgres --- .../TaskTableConstraintSuggestionIT.java | 366 ++++++++++++++++++ 1 file changed, 366 insertions(+) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java new file mode 100644 index 000000000000..3f758d375eb2 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -0,0 +1,366 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.bootstrap.SharedEntities; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.factories.DatabaseServiceTestFactory; +import org.openmetadata.it.factories.TableTestFactory; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.tasks.CreateTask; +import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.services.DatabaseService; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.schema.type.TableConstraint.RelationshipType; +import org.openmetadata.schema.type.TaskCategory; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.ForbiddenException; +import org.openmetadata.sdk.exceptions.InvalidRequestException; +import org.openmetadata.sdk.models.ListParams; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.governance.workflows.WorkflowHandler; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * A suggestion task can propose a table constraint. Approving it needs EditAll on the table and adds + * the constraint as the approver; rejecting it leaves the table as it was. + */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +public class TaskTableConstraintSuggestionIT { + private static final String TABLE_FIELDS = "tableConstraints,tags,description"; + + @Test + void approvingAsAnOwnerAddsThePrimaryKeyToTheTable(TestNamespace ns) { + Table table = ownedTable(ns, "pk"); + Task task = suggest(ns, table, "pk", constraint(ConstraintType.PRIMARY_KEY, "id"), null); + + Task approved = apply(SdkClients.user3Client(), task); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.PRIMARY_KEY, constraints.get(0).getConstraintType()); + assertEquals(List.of("id"), constraints.get(0).getColumns()); + } + + @Test + void approvingAForeignKeyToAnotherTablesColumnAddsItWithItsRelationshipType(TestNamespace ns) { + Table orders = adminTable(ns, "orders"); + Table customers = adminTable(ns, "customers"); + String customerId = FullyQualifiedName.add(customers.getFullyQualifiedName(), "id"); + TableConstraint foreignKey = + constraint(ConstraintType.FOREIGN_KEY, "id") + .withReferredColumns(List.of(customerId)) + .withRelationshipType(RelationshipType.MANY_TO_ONE); + Task task = suggest(ns, orders, "fk", foreignKey, null); + + Task approved = apply(SdkClients.adminClient(), task); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(orders); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.FOREIGN_KEY, constraints.get(0).getConstraintType()); + assertEquals(List.of("id"), constraints.get(0).getColumns()); + assertEquals(List.of(customerId), constraints.get(0).getReferredColumns()); + assertEquals(RelationshipType.MANY_TO_ONE, constraints.get(0).getRelationshipType()); + } + + @Test + void approvingWithoutEditAllIsForbiddenAndLeavesTheTableAndTaskAsTheyWere(TestNamespace ns) { + Table table = ownedTable(ns, "denied"); + Task task = + suggest( + ns, + table, + "denied", + constraint(ConstraintType.UNIQUE, "name"), + List.of(SharedEntities.get().USER2.getFullyQualifiedName())); + + ForbiddenException denied = + assertThrows(ForbiddenException.class, () -> apply(SdkClients.user2Client(), task)); + + assertTrue(denied.getMessage().contains("EditAll"), denied.getMessage()); + assertEquals(List.of(), constraintsOf(table)); + assertEquals( + TaskEntityStatus.Open, + SdkClients.adminClient().tasks().get(task.getId().toString()).getStatus()); + } + + @Test + void approvingWhenAnEqualConstraintIsPresentLeavesOneConstraint(TestNamespace ns) { + Table table = adminTable(ns, "equal"); + addConstraint(table, constraint(ConstraintType.UNIQUE, "name")); + Task task = suggest(ns, table, "equal", constraint(ConstraintType.UNIQUE, "name"), null); + + Task approved = apply(SdkClients.adminClient(), task); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + assertEquals(1, constraintsOf(table).size()); + assertEquals(ConstraintType.UNIQUE, constraintsOf(table).get(0).getConstraintType()); + } + + @Test + void rejectingLeavesTheTableAsItWasAndTheRejectionIsListedByTableAndStatus(TestNamespace ns) { + Table table = adminTable(ns, "reject"); + TableConstraint proposed = constraint(ConstraintType.PRIMARY_KEY, "id"); + Task task = suggest(ns, table, "reject", proposed, null); + awaitWorkflowTask(task); + + Task rejected = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Rejected) + .withComment("id is not unique")); + + assertEquals(TaskEntityStatus.Rejected, rejected.getStatus()); + assertEquals(List.of(), constraintsOf(table)); + ListParams params = new ListParams(); + params.addFilter("aboutEntity", table.getFullyQualifiedName()); + params.addFilter("type", "Suggestion"); + params.addFilter("status", "Rejected"); + List listed = SdkClients.adminClient().tasks().list(params).getData(); + assertEquals(1, listed.size()); + assertEquals(task.getId(), listed.get(0).getId()); + Map payload = JsonUtils.convertValue(listed.get(0).getPayload(), Map.class); + assertEquals("TableConstraint", payload.get("suggestionType")); + assertEquals(JsonUtils.pojoToJson(proposed), payload.get("suggestedValue")); + } + + @Test + void aSecondPrimaryKeyIsRefusedNamingTheExistingOneAndTheTaskStaysOpen(TestNamespace ns) { + Table table = adminTable(ns, "second"); + addConstraint(table, constraint(ConstraintType.PRIMARY_KEY, "id")); + Task task = suggest(ns, table, "second", constraint(ConstraintType.PRIMARY_KEY, "name"), null); + + InvalidRequestException refused = + assertThrows(InvalidRequestException.class, () -> apply(SdkClients.adminClient(), task)); + + assertTrue( + refused + .getMessage() + .contains( + "Table '" + + table.getFullyQualifiedName() + + "' already has a primary key on columns [id]; a table has one primary key"), + refused.getMessage()); + assertEquals( + TaskEntityStatus.Open, + SdkClients.adminClient().tasks().get(task.getId().toString()).getStatus()); + assertEquals(1, constraintsOf(table).size()); + assertEquals(List.of("id"), constraintsOf(table).get(0).getColumns()); + } + + @Test + void aSuggestionThatNamesNoValidConstraintIsRefusedWhenFiled(TestNamespace ns) { + Table table = adminTable(ns, "invalid"); + String tableFqn = table.getFullyQualifiedName(); + + assertEquals( + "Table constraint type SORT_KEY cannot be suggested; use PRIMARY_KEY, UNIQUE or FOREIGN_KEY", + fileRefused( + ns, table, "sort", JsonUtils.pojoToJson(constraint(ConstraintType.SORT_KEY, "id")))); + assertEquals( + "Column 'missing' is not a column of table '" + tableFqn + "'", + fileRefused( + ns, + table, + "column", + JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "missing")))); + assertEquals( + "Referred column '" + + tableFqn + + ".ghost' does not resolve to a column of an existing table", + fileRefused( + ns, + table, + "referred", + JsonUtils.pojoToJson( + constraint(ConstraintType.FOREIGN_KEY, "id") + .withReferredColumns(List.of(tableFqn + ".ghost"))))); + assertEquals( + "Suggested value is not a table constraint: not a constraint", + fileRefused(ns, table, "malformed", "not a constraint")); + } + + @Test + void aDescriptionAndATagSuggestionStillApply(TestNamespace ns) { + Table table = adminTable(ns, "others"); + Task description = + file( + ns, + table, + "description", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "Orders placed by customers"), + null); + Task tag = + file( + ns, + table, + "tag", + Map.of( + "suggestionType", "Tag", + "fieldPath", "tags", + "suggestedValue", + "[{\"tagFQN\":\"PII.Sensitive\",\"source\":\"Classification\"," + + "\"labelType\":\"Manual\",\"state\":\"Confirmed\"}]"), + null); + + assertEquals( + TaskEntityStatus.Approved, apply(SdkClients.adminClient(), description).getStatus()); + assertEquals(TaskEntityStatus.Approved, apply(SdkClients.adminClient(), tag).getStatus()); + + Table updated = + SdkClients.adminClient().tables().getByName(table.getFullyQualifiedName(), TABLE_FIELDS); + assertEquals("Orders placed by customers", updated.getDescription()); + assertEquals( + List.of("PII.Sensitive"), updated.getTags().stream().map(t -> t.getTagFQN()).toList()); + } + + private static String fileRefused( + TestNamespace ns, Table table, String label, String suggestedValue) { + return assertThrows( + InvalidRequestException.class, + () -> file(ns, table, label, payload(suggestedValue), null)) + .getMessage(); + } + + private static Table adminTable(TestNamespace ns, String label) { + DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); + DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns, service); + return TableTestFactory.createWithName(ns, schema.getFullyQualifiedName(), label); + } + + /** A table the shared third user owns, which gives that user EditAll on it. */ + private static Table ownedTable(TestNamespace ns, String label) { + Table table = adminTable(ns, label); + table.setOwners(List.of(SharedEntities.get().USER3_REF)); + return SdkClients.adminClient().tables().update(table.getId().toString(), table); + } + + private static void addConstraint(Table table, TableConstraint constraint) { + SdkClients.adminClient() + .tables() + .patch( + table.getId().toString(), + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/tableConstraints\",\"value\":[" + + JsonUtils.pojoToJson(constraint) + + "]}]")); + } + + private static List constraintsOf(Table table) { + Table stored = + SdkClients.adminClient().tables().getByName(table.getFullyQualifiedName(), TABLE_FIELDS); + return stored.getTableConstraints() == null ? List.of() : stored.getTableConstraints(); + } + + private static TableConstraint constraint(ConstraintType type, String... columns) { + return new TableConstraint().withConstraintType(type).withColumns(List.of(columns)); + } + + private static Task suggest( + TestNamespace ns, + Table table, + String label, + TableConstraint constraint, + List assignees) { + return file(ns, table, label, payload(JsonUtils.pojoToJson(constraint)), assignees); + } + + private static Map payload(String suggestedValue) { + Map payload = new LinkedHashMap<>(); + payload.put("suggestionType", "TableConstraint"); + payload.put("fieldPath", "tableConstraints"); + payload.put("suggestedValue", suggestedValue); + payload.put("source", "Agent"); + payload.put("confidence", 80.0); + payload.put("reasoning", "The column is unique in the sampled rows"); + return payload; + } + + private static Task file( + TestNamespace ns, + Table table, + String label, + Map payload, + List assignees) { + CreateTask request = + new CreateTask() + .withName(ns.prefix("constraint-" + label)) + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.Suggestion) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload(payload); + if (assignees != null) { + request.setAssignees(assignees); + } + return SdkClients.adminClient().tasks().create(request); + } + + private static Task apply(OpenMetadataClient client, Task task) { + awaitWorkflowTask(task); + return client + .getHttpClient() + .execute( + HttpMethod.PUT, "/v1/tasks/" + task.getId() + "/suggestion/apply", null, Task.class); + } + + private static void awaitWorkflowTask(Task task) { + UUID taskId = task.getId(); + Awaitility.await("workflow task for " + taskId) + .atMost(Duration.ofSeconds(20)) + .pollInterval(Duration.ofMillis(250)) + .untilAsserted( + () -> { + Task stored = + SdkClients.adminClient() + .tasks() + .get(taskId.toString(), "status,workflowDefinitionId,workflowStageId"); + assertNotNull(stored.getWorkflowStageId()); + assertTrue(WorkflowHandler.getInstance().hasActiveRuntimeTask(taskId)); + }); + } +} From faa4e438d1ae1265b92fce17bb315c4c3b284694 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 09:13:01 -0800 Subject: [PATCH 111/203] Make the definition digest the same for null and absent fields, set order, empty lists and derived fields --- .../ontology/OntologyDefinitionDigest.java | 152 +++++++- .../OntologyDefinitionDigestTest.java | 333 +++++++++++++++++- 2 files changed, 462 insertions(+), 23 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java index ca1781e28753..544cff70d03c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java @@ -14,23 +14,74 @@ package org.openmetadata.service.ontology; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.Comparator; +import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.StreamSupport; import org.apache.commons.codec.digest.DigestUtils; import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyAxiom; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.utils.JsonUtils; /** * The content digest of a definition, as a declined-definition record keys it. * - *

      The digest is the SHA-256 of the definition's canonical JSON: keys sorted, null fields left - * out, the {@code ontology} reference reduced to its id and type, and the fields the server or a - * generator sets afresh on every run left out ({@link #VOLATILE_FIELDS}). Two runs that propose the - * same definition therefore agree, and a changed label, domain or range does not. + *

      The digest is the SHA-256 of the definition's canonical JSON, which {@link #canonicalJson} + * builds in these steps: + * + *

        + *
      1. The definition is written to JSON and read back into its own class, the round trip a stored + * draft takes. A field sent as {@code null} and a field left out both end as the schema's + * default. + *
      2. The fields in {@link #DROPPED_FIELDS} are removed: the ones a tool or the server sets afresh + * on every run, and the ones the schema marks read only. + *
      3. The {@code ontology} reference and each owner are reduced to their id and type. + *
      4. Null fields and empty arrays are removed at every depth. + *
      5. Object keys are sorted, numbers lose their trailing zeros, and each array the schema marks + * as a set ({@code uniqueItems}) is sorted by the text of its elements and stripped of + * duplicates. + *
      6. The result is written as compact JSON in UTF-8 and hashed. + *
      */ public final class OntologyDefinitionDigest { - static final Set VOLATILE_FIELDS = - Set.of("id", "version", "updatedAt", "updatedBy", "href", "changeDescription"); + /** + * The fields that leave the canonical form. The first seven are set by the tool that proposes the + * definition or by the server on every write. The last three the schema marks {@code readOnly} + * and derives from other rows ({@code superClasses} and {@code subClasses} from the subclass + * axioms, {@code lifecycleStatus} from the ontology's releases). + */ + static final Set DROPPED_FIELDS = + Set.of( + "id", + "version", + "updatedAt", + "updatedBy", + "href", + "changeDescription", + "incrementalChangeDescription", + "impersonatedBy", + "lifecycleStatus", + "superClasses", + "subClasses"); + + private static final String SCHEMA_FOLDER = "/json/schema/entity/data/"; + private static final Map, String> SCHEMAS = + Map.of( + OntologyConcept.class, "ontologyConcept.json", + OntologyProperty.class, "ontologyProperty.json", + OntologyAxiom.class, "ontologyAxiom.json"); + private static final Map, Set> SET_FIELDS = new ConcurrentHashMap<>(); private OntologyDefinitionDigest() {} @@ -39,36 +90,99 @@ public static String of(final OntologyDefinition definition) { } static String canonicalJson(final OntologyDefinition definition) { - final JsonNode tree = JsonUtils.valueToTree(definition); + final JsonNode tree = + JsonUtils.valueToTree( + JsonUtils.readValue(JsonUtils.pojoToJson(definition), definition.getClass())); final ObjectNode content = tree.deepCopy(); - VOLATILE_FIELDS.forEach(content::remove); - if (content.has("ontology") && content.get("ontology").isObject()) { - final ObjectNode reference = JsonUtils.getObjectNode(); - reference.set("id", content.get("ontology").get("id")); - reference.set("type", content.get("ontology").get("type")); - content.set("ontology", reference); + DROPPED_FIELDS.forEach(content::remove); + reduceReferences(content); + final JsonNode canonical = OntologyJson.canonical(withoutEmpty(content)); + setFieldsOf(definition.getClass()).forEach(field -> sortAsSet(canonical, field)); + return canonical.toString(); + } + + /** The names of the arrays that the definition's schema marks {@code uniqueItems}. */ + static Set setFieldsOf(final Class definitionClass) { + return SET_FIELDS.computeIfAbsent(definitionClass, OntologyDefinitionDigest::readSetFields); + } + + private static Set readSetFields(final Class definitionClass) { + final String schema = SCHEMAS.get(definitionClass); + final Set fields = new TreeSet<>(); + if (schema == null) { + return fields; + } + try (InputStream stream = + OntologyDefinitionDigest.class.getResourceAsStream(SCHEMA_FOLDER + schema)) { + if (stream == null) { + throw new IllegalStateException("Schema " + SCHEMA_FOLDER + schema + " is not packaged"); + } + final JsonNode properties = + JsonUtils.readTree(new String(stream.readAllBytes(), StandardCharsets.UTF_8)) + .get("properties"); + properties + .properties() + .forEach( + property -> { + if (property.getValue().path("uniqueItems").asBoolean(false)) { + fields.add(property.getKey()); + } + }); + return fields; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void reduceReferences(final ObjectNode content) { + if (content.path("ontology").isObject()) { + content.set("ontology", idAndType(content.get("ontology"))); + } + if (content.path("owners").isArray()) { + final ArrayNode owners = JsonUtils.getObjectMapper().createArrayNode(); + content.get("owners").forEach(owner -> owners.add(idAndType(owner))); + content.set("owners", owners); } - return OntologyJson.canonical(withoutNulls(content)).toString(); } - private static JsonNode withoutNulls(final JsonNode value) { + private static ObjectNode idAndType(final JsonNode reference) { + final ObjectNode reduced = JsonUtils.getObjectNode(); + reduced.set("id", reference.get("id")); + reduced.set("type", reference.get("type")); + return reduced; + } + + private static JsonNode withoutEmpty(final JsonNode value) { if (value instanceof ObjectNode object) { final ObjectNode kept = JsonUtils.getObjectNode(); object .properties() .forEach( entry -> { - if (!entry.getValue().isNull()) { - kept.set(entry.getKey(), withoutNulls(entry.getValue())); + final JsonNode child = withoutEmpty(entry.getValue()); + if (!child.isNull() && !(child.isArray() && child.isEmpty())) { + kept.set(entry.getKey(), child); } }); return kept; } if (value.isArray()) { - final var items = JsonUtils.getObjectMapper().createArrayNode(); - value.forEach(item -> items.add(withoutNulls(item))); + final ArrayNode items = JsonUtils.getObjectMapper().createArrayNode(); + value.forEach(item -> items.add(withoutEmpty(item))); return items; } return value; } + + private static void sortAsSet(final JsonNode canonical, final String field) { + if (canonical.get(field) instanceof ArrayNode array) { + final List ordered = + StreamSupport.stream(array.spliterator(), false) + .sorted(Comparator.comparing(JsonNode::toString)) + .distinct() + .toList(); + ((ObjectNode) canonical) + .set(field, JsonUtils.getObjectMapper().createArrayNode().addAll(ordered)); + } + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDefinitionDigestTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDefinitionDigestTest.java index e3213826bd10..47a9de2744b8 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDefinitionDigestTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDefinitionDigestTest.java @@ -14,12 +14,27 @@ package org.openmetadata.service.ontology; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import com.fasterxml.jackson.databind.JsonNode; +import java.io.IOException; +import java.io.InputStream; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Set; +import java.util.TreeSet; import java.util.UUID; +import java.util.stream.Stream; +import org.apache.commons.codec.digest.DigestUtils; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.EntityReference; @@ -29,14 +44,68 @@ class OntologyDefinitionDigestTest { private static final UUID ONTOLOGY = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); + private static final String ONTOLOGY_JSON = + "{\"id\":\"00000000-0000-0000-0000-0000000000a1\",\"type\":\"ontology\"}"; private static final String ORDER_CANONICAL = - "{\"abstract\":false,\"conceptMappings\":[],\"conceptType\":\"OWL_CLASS\",\"deleted\":false,\"deprecated\":false,\"description\":\"A purchase a customer placed\",\"displayName\":\"Order\",\"fullyQualifiedName\":\"sales.Order\",\"iri\":\"https://example.org/sales/Order\",\"name\":\"Order\",\"ontology\":{\"id\":\"00000000-0000-0000-0000-0000000000a1\",\"type\":\"ontology\"},\"provider\":\"user\",\"subClasses\":[],\"superClasses\":[],\"synonyms\":[]}"; + "{\"abstract\":false,\"conceptType\":\"OWL_CLASS\",\"deleted\":false,\"deprecated\":false,\"description\":\"A purchase a customer placed\",\"displayName\":\"Order\",\"fullyQualifiedName\":\"sales.Order\",\"iri\":\"https://example.org/sales/Order\",\"name\":\"Order\",\"ontology\":{\"id\":\"00000000-0000-0000-0000-0000000000a1\",\"type\":\"ontology\"},\"provider\":\"user\"}"; private static final String ORDER_DIGEST = - "2bddd94468d56041502ca0270cce671e8eaf4dfdfdcd25234c158ca44e163ca5"; + "d1bef0ebba86898d77e8b761c7d6c1c67a6de316a2d48a8e1595a714077b991b"; private static final String TOTAL_CANONICAL = - "{\"characteristics\":[],\"deleted\":false,\"deprecated\":false,\"disjointWith\":[],\"domain\":[\"https://example.org/sales/Order\"],\"enumValues\":[],\"fullyQualifiedName\":\"sales.total\",\"iri\":\"https://example.org/sales/total\",\"isIdentifier\":false,\"kind\":\"DATA\",\"name\":\"total\",\"ontology\":{\"id\":\"00000000-0000-0000-0000-0000000000a1\",\"type\":\"ontology\"},\"propertyChain\":[],\"provider\":\"user\",\"range\":[\"http://www.w3.org/2001/XMLSchema#decimal\"],\"superProperties\":[]}"; + "{\"deleted\":false,\"deprecated\":false,\"domain\":[\"https://example.org/sales/Order\"],\"fullyQualifiedName\":\"sales.total\",\"iri\":\"https://example.org/sales/total\",\"isIdentifier\":false,\"kind\":\"DATA\",\"name\":\"total\",\"ontology\":{\"id\":\"00000000-0000-0000-0000-0000000000a1\",\"type\":\"ontology\"},\"provider\":\"user\",\"range\":[\"http://www.w3.org/2001/XMLSchema#decimal\"]}"; private static final String TOTAL_DIGEST = - "6db5fca8db27d39290783c57df6eb0b991c5b1b8826728e221581455bfba6470"; + "dede90b4844e19579b0fc16accf3937493626d37d4cc668960eb95bdece30d10"; + + /** The 21 fields that carry a schema default in a concept, a property or an axiom. */ + private static Stream fieldsWithADefault() { + return Stream.concat( + Stream.of( + "synonyms", + "conceptMappings", + "deleted", + "provider", + "abstract", + "deprecated", + "superClasses", + "subClasses") + .map(field -> Arguments.of(OntologyConcept.class, ORDER_JSON, field)), + Stream.concat( + Stream.of( + "deleted", + "provider", + "domain", + "range", + "enumValues", + "isIdentifier", + "characteristics", + "propertyChain", + "disjointWith", + "superProperties", + "deprecated") + .map(field -> Arguments.of(OntologyProperty.class, TOTAL_JSON, field)), + Stream.of("deleted", "provider") + .map(field -> Arguments.of(OntologyAxiom.class, AXIOM_JSON, field)))); + } + + private static final String ORDER_JSON = + "{\"name\":\"Order\",\"fullyQualifiedName\":\"sales.Order\",\"displayName\":\"Order\"," + + "\"description\":\"A purchase a customer placed\"," + + "\"iri\":\"https://example.org/sales/Order\",\"conceptType\":\"OWL_CLASS\"," + + "\"ontology\":" + + ONTOLOGY_JSON + + "}"; + private static final String TOTAL_JSON = + "{\"name\":\"total\",\"fullyQualifiedName\":\"sales.total\"," + + "\"iri\":\"https://example.org/sales/total\",\"kind\":\"DATA\"," + + "\"domain\":[\"https://example.org/sales/Order\"]," + + "\"range\":[\"http://www.w3.org/2001/XMLSchema#decimal\"],\"ontology\":" + + ONTOLOGY_JSON + + "}"; + private static final String AXIOM_JSON = + "{\"name\":\"orderIsAThing\",\"axiomType\":\"SUBCLASS_OF\"," + + "\"subjectIri\":\"https://example.org/sales/Order\"," + + "\"targetIri\":\"https://example.org/sales/Thing\",\"ontology\":" + + ONTOLOGY_JSON + + "}"; @Test void aClassHasTheDigestOfItsCanonicalContent() { @@ -50,6 +119,34 @@ void aPropertyHasTheDigestOfItsCanonicalContent() { assertEquals(TOTAL_DIGEST, OntologyDefinitionDigest.of(total())); } + @Test + void theDigestIsTheSha256OfTheCompactUtf8Text() { + final OntologyConcept accented = order().withDisplayName("Commande été"); + final String canonical = OntologyDefinitionDigest.canonicalJson(accented); + + assertTrue(canonical.contains("\"displayName\":\"Commande été\""), canonical); + assertFalse(canonical.contains("\\u00e9"), canonical); + assertFalse(canonical.contains(": ") || canonical.contains(", "), canonical); + assertEquals( + DigestUtils.sha256Hex(canonical.getBytes(StandardCharsets.UTF_8)), + OntologyDefinitionDigest.of(accented)); + } + + @Test + void aNumberKeepsNoTrailingZerosSoTenIsWrittenAsOneETen() { + final OntologyAxiom restricted = + JsonUtils.readValue( + "{\"name\":\"r\",\"axiomType\":\"SUBCLASS_OF\"," + + "\"subjectIri\":\"https://example.org/sales/Order\",\"expressions\":[" + + "{\"kind\":\"RESTRICTION\",\"propertyIri\":\"https://example.org/sales/line\"," + + "\"restrictionKind\":\"MIN\",\"cardinality\":10}]}", + OntologyAxiom.class); + + assertTrue( + OntologyDefinitionDigest.canonicalJson(restricted).contains("\"cardinality\":1E+1"), + OntologyDefinitionDigest.canonicalJson(restricted)); + } + @Test void aFreshIdVersionAndAuthorshipDoNotChangeTheDigest() { final OntologyConcept again = @@ -90,6 +187,25 @@ void aChangedLabelOrDomainGivesANewDigest() { assertNotEquals(relabeled, redomained); } + @Test + void aChangedRangeParentClassOrOwnerGivesANewDigest() { + final String range = + OntologyDefinitionDigest.of( + total().withRange(List.of(URI.create("http://www.w3.org/2001/XMLSchema#string")))); + final String parent = + OntologyDefinitionDigest.of( + JsonUtils.readValue(AXIOM_JSON, OntologyAxiom.class) + .withTargetIri(URI.create("https://example.org/sales/Other"))); + final String owned = + OntologyDefinitionDigest.of( + order().withOwners(List.of(reference(UUID.randomUUID(), "user")))); + + assertNotEquals(TOTAL_DIGEST, range); + assertNotEquals( + OntologyDefinitionDigest.of(JsonUtils.readValue(AXIOM_JSON, OntologyAxiom.class)), parent); + assertNotEquals(ORDER_DIGEST, owned); + } + @Test void theOrderOfKeysInTheJsonDoesNotMatter() { final String forward = @@ -104,6 +220,215 @@ void theOrderOfKeysInTheJsonDoesNotMatter() { OntologyDefinitionDigest.of(JsonUtils.readValue(backward, OntologyConcept.class))); } + @ParameterizedTest(name = "{1} of {0}") + @MethodSource("fieldsWithADefault") + void aFieldSentAsNullAndTheSameFieldLeftOutGiveOneDigest( + final Class type, final String json, final String field) { + final JsonNode withoutIt = JsonUtils.readTree(json); + ((com.fasterxml.jackson.databind.node.ObjectNode) withoutIt).remove(field); + final JsonNode withNull = withoutIt.deepCopy(); + ((com.fasterxml.jackson.databind.node.ObjectNode) withNull).putNull(field); + + assertEquals( + OntologyDefinitionDigest.of(JsonUtils.readValue(withoutIt.toString(), type)), + OntologyDefinitionDigest.of(JsonUtils.readValue(withNull.toString(), type)), + field); + } + + @Test + void aNullThatTurnsOffADefaultedFieldStillMatchesTheDefaultedDefinition() { + final OntologyConcept sentAsNulls = + JsonUtils.readValue( + ORDER_JSON.substring(0, ORDER_JSON.length() - 1) + + ",\"synonyms\":null,\"deleted\":null,\"provider\":null,\"abstract\":null}", + OntologyConcept.class); + + assertEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(sentAsNulls)); + } + + @Test + void aConceptWithoutATypeTakesTheSchemaDefaultAndAnAxiomItsProvenance() { + final String concept = + OntologyDefinitionDigest.canonicalJson( + JsonUtils.readValue( + "{\"name\":\"Order\",\"iri\":\"https://example.org/sales/Order\"}", + OntologyConcept.class)); + final String axiom = + OntologyDefinitionDigest.canonicalJson( + JsonUtils.readValue(AXIOM_JSON, OntologyAxiom.class)); + + assertEquals( + "{\"abstract\":false,\"conceptType\":\"BOTH\",\"deleted\":false,\"deprecated\":false," + + "\"iri\":\"https://example.org/sales/Order\",\"name\":\"Order\",\"provider\":\"user\"}", + concept); + assertEquals( + "{\"axiomType\":\"SUBCLASS_OF\",\"deleted\":false,\"name\":\"orderIsAThing\"," + + "\"ontology\":" + + ONTOLOGY_JSON + + ",\"provenance\":\"Manual\",\"provider\":\"user\"," + + "\"subjectIri\":\"https://example.org/sales/Order\"," + + "\"targetIri\":\"https://example.org/sales/Thing\"}", + axiom); + } + + @Test + void theOrderOfAnArrayTheSchemaTreatsAsASetDoesNotMatter() { + final OntologyProperty forward = + total() + .withDomain( + List.of( + URI.create("https://example.org/sales/Order"), + URI.create("https://example.org/sales/Invoice"))) + .withRange( + List.of( + URI.create("http://www.w3.org/2001/XMLSchema#string"), + URI.create("http://www.w3.org/2001/XMLSchema#decimal"))); + final OntologyProperty backward = + total() + .withDomain( + List.of( + URI.create("https://example.org/sales/Invoice"), + URI.create("https://example.org/sales/Order"))) + .withRange( + List.of( + URI.create("http://www.w3.org/2001/XMLSchema#decimal"), + URI.create("http://www.w3.org/2001/XMLSchema#string"))); + final OntologyConcept synonymsForward = + order().withSynonyms(new java.util.LinkedHashSet<>(List.of("Purchase", "Sale"))); + final OntologyConcept synonymsBackward = + order().withSynonyms(new java.util.LinkedHashSet<>(List.of("Sale", "Purchase"))); + + assertEquals(OntologyDefinitionDigest.of(forward), OntologyDefinitionDigest.of(backward)); + assertEquals( + OntologyDefinitionDigest.of(synonymsForward), + OntologyDefinitionDigest.of(synonymsBackward)); + } + + @Test + void theOrderOfAnOrderedArrayDoesMatter() { + final OntologyProperty chain = + total() + .withPropertyChain( + List.of( + URI.create("https://example.org/sales/a"), + URI.create("https://example.org/sales/b"))); + final OntologyProperty reversed = + total() + .withPropertyChain( + List.of( + URI.create("https://example.org/sales/b"), + URI.create("https://example.org/sales/a"))); + + assertNotEquals(OntologyDefinitionDigest.of(chain), OntologyDefinitionDigest.of(reversed)); + } + + @Test + void everyArrayTheSchemasMarkUniqueIsASetField() throws IOException { + assertEquals(Set.of("synonyms"), OntologyDefinitionDigest.setFieldsOf(OntologyConcept.class)); + assertEquals( + Set.of( + "domain", "range", "enumValues", "characteristics", "disjointWith", "superProperties"), + OntologyDefinitionDigest.setFieldsOf(OntologyProperty.class)); + assertEquals(Set.of(), OntologyDefinitionDigest.setFieldsOf(OntologyAxiom.class)); + for (final String schema : List.of("ontologyConcept", "ontologyProperty", "ontologyAxiom")) { + final Set unique = new TreeSet<>(); + schemaProperties(schema) + .properties() + .forEach( + property -> { + if (property.getValue().path("uniqueItems").asBoolean(false)) { + unique.add(property.getKey()); + } + }); + final Class type = + switch (schema) { + case "ontologyConcept" -> OntologyConcept.class; + case "ontologyProperty" -> OntologyProperty.class; + default -> OntologyAxiom.class; + }; + assertEquals(unique, OntologyDefinitionDigest.setFieldsOf(type), schema); + } + } + + @Test + void anEmptyArrayAndAnAbsentFieldGiveOneDigest() { + final OntologyConcept withEmpty = order().withOwners(List.of()); + final OntologyConcept without = order().withOwners(null); + + assertEquals(OntologyDefinitionDigest.of(without), OntologyDefinitionDigest.of(withEmpty)); + assertEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(withEmpty)); + } + + @Test + void aServerDerivedFieldDoesNotChangeTheDigest() { + final OntologyConcept read = + JsonUtils.readValue( + ORDER_JSON.substring(0, ORDER_JSON.length() - 1) + + ",\"impersonatedBy\":\"ingestion-bot\"," + + "\"incrementalChangeDescription\":{\"fieldsAdded\":[{\"name\":\"description\"}]}," + + "\"lifecycleStatus\":\"InReview\"," + + "\"superClasses\":[\"https://example.org/sales/Thing\"]," + + "\"subClasses\":[\"https://example.org/sales/Rush\"]," + + "\"owners\":[{\"id\":\"%s\",\"type\":\"team\",\"name\":\"sales\"," + .formatted(OWNER) + + "\"displayName\":\"Sales\",\"href\":\"https://example.org/api/v1/teams/x\"}]}", + OntologyConcept.class); + final OntologyConcept owned = order().withOwners(List.of(reference(OWNER, "team"))); + + assertEquals(OntologyDefinitionDigest.of(owned), OntologyDefinitionDigest.of(read)); + assertNotEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(read)); + } + + @Test + void everyFieldTheSchemasMarkReadOnlyLeavesTheCanonicalForm() throws IOException { + for (final String schema : List.of("ontologyConcept", "ontologyProperty", "ontologyAxiom")) { + schemaProperties(schema) + .properties() + .forEach( + property -> { + if (property.getValue().path("readOnly").asBoolean(false)) { + assertTrue( + OntologyDefinitionDigest.DROPPED_FIELDS.contains(property.getKey()), + schema + "." + property.getKey()); + } + }); + } + } + + @Test + void theDroppedFieldsAreExactlyTheServerDerivedOnes() { + assertEquals( + new TreeSet<>( + Set.of( + "id", + "version", + "updatedAt", + "updatedBy", + "href", + "changeDescription", + "incrementalChangeDescription", + "impersonatedBy", + "lifecycleStatus", + "superClasses", + "subClasses")), + new TreeSet<>(OntologyDefinitionDigest.DROPPED_FIELDS)); + } + + private static final UUID OWNER = UUID.fromString("00000000-0000-0000-0000-0000000000b2"); + + private static EntityReference reference(final UUID id, final String type) { + return new EntityReference().withId(id).withType(type); + } + + private static JsonNode schemaProperties(final String schema) throws IOException { + try (InputStream stream = + OntologyDefinitionDigestTest.class.getResourceAsStream( + "/json/schema/entity/data/" + schema + ".json")) { + return JsonUtils.readTree(new String(stream.readAllBytes(), StandardCharsets.UTF_8)) + .get("properties"); + } + } + private static OntologyConcept order() { return new OntologyConcept() .withId(UUID.randomUUID()) From 29b11f848f387605d86517d447e7c7fbce0bc3b5 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 09:13:06 -0800 Subject: [PATCH 112/203] Check every kept operation when narrowing a draft, whatever the undo cursor --- .../ontology/OntologyDraftNarrowing.java | 94 +++++++++--- .../ontology/OntologyDraftNarrowingTest.java | 144 ++++++++++++++++++ 2 files changed, 213 insertions(+), 25 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftNarrowing.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftNarrowing.java index 43197eaa5249..68eb3d56764e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftNarrowing.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftNarrowing.java @@ -16,13 +16,17 @@ import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import jakarta.ws.rs.BadRequestException; -import java.util.HashSet; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.TreeSet; -import java.util.stream.Collectors; +import java.util.function.Predicate; import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.service.ontology.OntologyChangePreflight.DeclaredConcepts; /** @@ -31,9 +35,27 @@ * first time it would otherwise say so. */ public final class OntologyDraftNarrowing { + private static final String REMOVED_HEAD = + "Ontology operations need classes that only removed operations create: "; + private static final String REMOVED_TAIL = + ". Keep the operation that creates each class, or remove the operations that need it."; + private static final String UNDONE_HEAD = + "Ontology operations need classes that only kept operations past the undo cursor create: "; + private static final String UNDONE_TAIL = + ". Move the undo cursor past the operation that creates each class, or remove the operations" + + " that need it."; + private OntologyDraftNarrowing() {} /** + * Refuses a replacement in which a kept operation needs a class that a redo or an apply of the + * kept operations would not have created before it. The operation at index {@code i} is active + * together with {@code kept[0 .. max(i + 1, cursor))}, whatever the cursor is now, because a redo + * moves the cursor forward one operation at a time. A class the operations before it do not + * create makes the draft fail at apply when a stored operation created it: when it is created by + * no kept operation, the removed one is to blame, and when a kept operation past the cursor + * creates it, the cursor is. + * * @param replaced the draft with the operations and cursor that replace the stored ones * @param stored the operations the draft held before the replacement */ @@ -45,35 +67,57 @@ public static void requireNoLostClasses( return; } final List kept = listOrEmpty(replaced.getOperations()); - final List active = kept.subList(0, replaced.getUndoCursor()); - final Set lost = lostClasses(active, stored); + final Set storedCreations = OntologyChangePreflight.createdConceptIris(stored); + final Map firstCreation = firstCreations(kept); + final Set removed = new TreeSet<>(); + final Set undone = new TreeSet<>(); + final Map> dataPropertiesBefore = new HashMap<>(); + for (int index = 0; index < kept.size(); index++) { + final int reachable = Math.max(index + 1, replaced.getUndoCursor()); + final var isDataProperty = + dataPropertiesBefore.computeIfAbsent( + reachable, end -> OntologyChangePreflight.dataProperties(kept.subList(0, end))); + for (final String needed : + OntologyChangePreflight.neededClassIris(kept.get(index), isDataProperty)) { + final Integer created = firstCreation.get(needed); + if (storedCreations.contains(needed) && (created == null || created >= reachable)) { + (created == null ? removed : undone).add(needed); + } + } + } + final Set lost = new TreeSet<>(removed); + lost.addAll(undone); if (lost.isEmpty()) { return; } - lost.removeAll(declaredConcepts.declared(replaced.getOntology().getId(), lost)); - if (!lost.isEmpty()) { - throw new BadRequestException( - "Ontology operations need classes that only removed operations create: " - + String.join(", ", lost) - + ". Keep the operation that creates each class, or remove the operations that need" - + " it."); + final Set declared = declaredConcepts.declared(replaced.getOntology().getId(), lost); + removed.removeAll(declared); + undone.removeAll(declared); + if (!removed.isEmpty() || !undone.isEmpty()) { + throw new BadRequestException(refusal(removed, undone)); + } + } + + private static String refusal(final Set removed, final Set undone) { + final List sentences = new ArrayList<>(); + if (!removed.isEmpty()) { + sentences.add(REMOVED_HEAD + String.join(", ", removed) + REMOVED_TAIL); + } + if (!undone.isEmpty()) { + sentences.add(UNDONE_HEAD + String.join(", ", undone) + UNDONE_TAIL); } + return String.join(" ", sentences); } - private static Set lostClasses( - final List active, final List stored) { - final Set removedCreations = - new HashSet<>(OntologyChangePreflight.createdConceptIris(stored)); - removedCreations.removeAll(OntologyChangePreflight.createdConceptIris(active)); - if (removedCreations.isEmpty()) { - return new TreeSet<>(); + private static Map firstCreations(final List kept) { + final Map first = new HashMap<>(); + for (int index = 0; index < kept.size(); index++) { + final OntologyChangeOperation operation = kept.get(index); + if (operation.getOperationType() == OntologyChangeOperationType.UPSERT_CONCEPT + && operation.getConcept() != null) { + first.putIfAbsent(operation.getConcept().getIri().toString(), index); + } } - final var isDataProperty = OntologyChangePreflight.dataProperties(active); - return active.stream() - .flatMap( - operation -> - OntologyChangePreflight.neededClassIris(operation, isDataProperty).stream()) - .filter(removedCreations::contains) - .collect(Collectors.toCollection(TreeSet::new)); + return first; } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftNarrowingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftNarrowingTest.java index 3267607df90d..56cc6a5c0437 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftNarrowingTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftNarrowingTest.java @@ -120,6 +120,150 @@ void refusesAClassKeptPastTheUndoCursor() { () -> narrow(List.of(total, order), 1, List.of(order, total), Set.of())); } + @Test + void namesAClassKeptPastTheUndoCursorAsUndoneAndNotAsRemoved() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation total = dataProperty("total", ORDER); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> narrow(List.of(total, order), 1, List.of(order, total), Set.of())); + + assertEquals( + "Ontology operations need classes that only kept operations past the undo cursor create: " + + "https://example.org/sales/Order. Move the undo cursor past the operation that" + + " creates each class, or remove the operations that need it.", + refusal.getMessage()); + } + + @Test + void namesBothKindsOfLostClassInOneRefusal() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation customer = concept(CUSTOMER); + final OntologyChangeOperation placedBy = objectProperty("placedBy", ORDER, CUSTOMER); + final OntologyChangeOperation lateCustomer = concept(CUSTOMER); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> + narrow( + List.of(placedBy, lateCustomer), + 1, + List.of(order, customer, placedBy, lateCustomer), + Set.of())); + + assertEquals( + REFUSAL_HEAD + + "https://example.org/sales/Order. Keep the operation that creates each class, or" + + " remove the operations that need it." + + " Ontology operations need classes that only kept operations past the undo cursor" + + " create: https://example.org/sales/Customer. Move the undo cursor past the" + + " operation that creates each class, or remove the operations that need it.", + refusal.getMessage()); + } + + @Test + void refusesAClassOnlyARemovedOperationCreatedWhenARedoWouldActivateTheOperationThatNeedsIt() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation total = dataProperty("total", ORDER); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> narrow(List.of(total), 0, List.of(order, total), Set.of())); + + assertEquals( + REFUSAL_HEAD + + "https://example.org/sales/Order. Keep the operation that creates each class, or" + + " remove the operations that need it.", + refusal.getMessage()); + } + + /** + * Over every subset of a six-operation draft, every undo cursor and every redo target, a + * narrowing that is accepted leaves a draft that applies at each of the cursors a redo can + * reach, and one that is refused would fail at one of them. + */ + @Test + void aNarrowingIsAcceptedExactlyWhenEveryRedoTargetApplies() { + final URI existing = URI.create("https://example.org/sales/Existing"); + final OntologyChangeOperation classA = concept(ORDER); + final OntologyChangeOperation classB = concept(CUSTOMER); + final OntologyChangeOperation axiom = subclassOf(CUSTOMER, ORDER); + final OntologyChangeOperation p1 = dataProperty("p1", ORDER); + final OntologyChangeOperation p2 = objectProperty("p2", CUSTOMER, ORDER); + final OntologyChangeOperation p3 = dataProperty("p3", existing); + final List draft = List.of(classA, classB, axiom, p1, p2, p3); + final Set declared = Set.of(existing.toString()); + int accepted = 0; + int refused = 0; + int accepting = 0; + + for (int mask = 0; mask < (1 << draft.size()); mask++) { + final List kept = new java.util.ArrayList<>(); + for (int bit = 0; bit < draft.size(); bit++) { + if ((mask & (1 << bit)) != 0) { + kept.add(draft.get(bit)); + } + } + for (int cursor = 0; cursor <= kept.size(); cursor++) { + boolean narrowed = true; + try { + narrow(kept, cursor, draft, declared); + } catch (BadRequestException refusal) { + narrowed = false; + } + boolean everyTargetApplies = true; + for (int target = cursor; target <= kept.size(); target++) { + everyTargetApplies &= applies(kept.subList(0, target), draft, declared); + } + assertEquals(everyTargetApplies, narrowed, "subset " + mask + " cursor " + cursor); + accepted += narrowed ? 1 : 0; + refused += narrowed ? 0 : 1; + accepting += narrowed && everyTargetApplies ? 1 : 0; + } + } + + assertEquals(100, accepted); + assertEquals(156, refused); + assertEquals(accepted, accepting); + } + + /** What apply decides for the active operations: each class a stored operation made is there. */ + private static boolean applies( + final List active, + final List stored, + final Set declared) { + final Set storedClasses = OntologyChangePreflight.createdConceptIris(stored); + final Set created = OntologyChangePreflight.createdConceptIris(active); + final var dataProperties = OntologyChangePreflight.dataProperties(active); + return active.stream() + .flatMap( + operation -> + OntologyChangePreflight.neededClassIris(operation, dataProperties).stream()) + .filter(storedClasses::contains) + .allMatch(iri -> created.contains(iri) || declared.contains(iri)); + } + + private static OntologyChangeOperation subclassOf(final URI child, final URI parent) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_AXIOM) + .withAxiom( + new org.openmetadata.schema.entity.data.OntologyAxiom() + .withId(UUID.randomUUID()) + .withAxiomType(org.openmetadata.schema.type.OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(child) + .withExpressions( + List.of( + new org.openmetadata.schema.type.OntologyExpression() + .withKind( + org.openmetadata.schema.type.OntologyExpressionKind.NAMED_CLASS) + .withClassIri(parent)))); + } + private static void narrow( final List kept, final List stored, From a0110ee16895f08e15ee24c6e0e4e5752b231fb8 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 09:13:11 -0800 Subject: [PATCH 113/203] Remove declined definitions when an ontology is permanently deleted --- .../service/jdbi3/OntologyDeclinedDefinitionDAO.java | 5 +++++ .../org/openmetadata/service/jdbi3/OntologyRepository.java | 1 + .../service/ontology/OntologyDeclinedDefinitionsTest.java | 5 +++++ 3 files changed, 11 insertions(+) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDAO.java index a83c64d48427..1412b3e09a9e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDAO.java @@ -28,6 +28,7 @@ import org.jdbi.v3.sqlobject.customizer.BindList; import org.jdbi.v3.sqlobject.customizer.BindMethods; import org.jdbi.v3.sqlobject.statement.SqlQuery; +import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.type.OntologyDeclinedDefinition; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlUpdate; @@ -101,6 +102,10 @@ List listAfter( @Bind("afterDigest") String afterDigest, @Bind("limit") int limit); + /** Removes every record of an ontology, as its permanent deletion does. */ + @SqlUpdate("DELETE FROM ontology_declined_definition WHERE ontologyId = :ontologyId") + void deleteByOntology(@Bind("ontologyId") String ontologyId); + class DeclinedDefinitionMapper implements RowMapper { @Override public OntologyDeclinedDefinition map(final ResultSet rows, final StatementContext context) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java index 59122802a71d..1a098c68998c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java @@ -346,6 +346,7 @@ protected List prepareChildrenForHardDeleteCascade( @Override protected void entitySpecificCleanup(final Ontology entity) { requireNoRetainedReleases(entity.getId()); + daoCollection.ontologyDeclinedDefinitionDAO().deleteByOntology(entity.getId().toString()); } /** diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitionsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitionsTest.java index 66f80cbf87d3..e9441d32149b 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitionsTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitionsTest.java @@ -198,6 +198,11 @@ public void insertIfAbsent(final StoredDeclinedDefinition row) { } } + @Override + public void deleteByOntology(final String ontologyId) { + rows.removeIf(row -> row.ontologyId().equals(ontologyId)); + } + @Override public List findByIriHashes( final String ontologyId, final List iriHashes) { From 820fb4ef008d0e4937b0f97ffadccdc682647ef6 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 09:13:15 -0800 Subject: [PATCH 114/203] Ask the draft read right before declining a definition of a change set --- .../OntologyDeclinedDefinitionReadIT.java | 191 +++++++++++ .../OntologyDeclinedDefinitionEndpoint.java | 25 +- .../OntologyDeclinedDefinitionRightsTest.java | 311 ++++++++++++++++++ 3 files changed, 521 insertions(+), 6 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionReadIT.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionRightsTest.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionReadIT.java new file mode 100644 index 000000000000..8317864f1669 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionReadIT.java @@ -0,0 +1,191 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * Declining answers with the IRIs of a draft's operations and stores a record for each, so it asks + * the right that reading the draft asks, and asks it before the change set is matched to the + * ontology in the path. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyDeclinedDefinitionReadIT extends BaseOntologyApprovalIT { + private static final int FORBIDDEN = 403; + private static final String HIDDEN_IRI_PREFIX = "urn:declined:Hidden"; + + private record Scene( + Ontology ontology, + OntologyChangeSet draft, + String operationId, + String iri, + OpenMetadataClient editor) { + String draftPath() { + return CHANGE_SETS + "/" + draft.getId(); + } + + String declinePath(final Ontology target) { + return "/v1/ontologies/" + target.getId() + "/declinedDefinitions"; + } + + Map request() { + return Map.of( + "changeSetId", draft.getId().toString(), + "operationIds", List.of(operationId), + "reason", "out of scope"); + } + } + + @Test + void anEditorWhoMayNotReadTheDraftIsRefusedAsTheReadIsAndStoresNoRecord(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("decRead" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OpenMetadataException read = + assertThrows( + OpenMetadataException.class, + () -> send(scene.editor(), HttpMethod.GET, scene.draftPath(), null)); + assertEquals(FORBIDDEN, read.getStatusCode()); + + final OpenMetadataException declined = + assertThrows( + OpenMetadataException.class, + () -> + send( + scene.editor(), + HttpMethod.POST, + scene.declinePath(scene.ontology()), + scene.request())); + + assertEquals(FORBIDDEN, declined.getStatusCode()); + assertEquals(read.getMessage(), declined.getMessage()); + assertFalse(declined.getMessage().contains(scene.iri()), declined.getMessage()); + assertEquals(0, records(scene.ontology()).size()); + } + } + + @Test + void aCallerWhoMayNotReadTheDraftIsRefusedBeforeBeingToldItBelongsToAnotherOntology( + final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("decOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final Ontology other = createOntology(ns, "elsewhere"); + final OpenMetadataException read = + assertThrows( + OpenMetadataException.class, + () -> send(scene.editor(), HttpMethod.GET, scene.draftPath(), null)); + + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + send(scene.editor(), HttpMethod.POST, scene.declinePath(other), scene.request())); + final OpenMetadataException mismatch = + assertThrows( + OpenMetadataException.class, + () -> send(admin(), HttpMethod.POST, scene.declinePath(other), scene.request())); + + assertEquals(FORBIDDEN, refused.getStatusCode()); + assertEquals(read.getMessage(), refused.getMessage()); + assertEquals(400, mismatch.getStatusCode()); + assertTrue(mismatch.getMessage().contains("does not belong"), mismatch.getMessage()); + assertEquals(0, records(other).size()); + assertEquals(0, records(scene.ontology()).size()); + } + } + + @Test + void anAdminWhoMayReadTheDraftStillDeclinesItsOperation(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("decAdmin" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + + final String declined = + send(admin(), HttpMethod.POST, scene.declinePath(scene.ontology()), scene.request()); + + assertTrue(declined.contains(scene.iri()), declined); + assertEquals(1, records(scene.ontology()).size()); + } + } + + private static JsonNode records(final Ontology ontology) { + return JsonUtils.readTree( + send( + admin(), + HttpMethod.GET, + "/v1/ontologies/" + ontology.getId() + "/declinedDefinitions", + null)) + .path("records"); + } + + /** The editor may edit change sets and holds no right on the ontology, so it may not read. */ + private static Scene scene(final TestNamespace ns, final RdfAccessFixtures fixtures) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final var edit = fixtures.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CHANGE_SET); + final OpenMetadataClient editor = + OntologyBindingFixtures.client(fixtures.userToken("editor", List.of(edit.getId()))); + final URI iri = URI.create(HIDDEN_IRI_PREFIX + ns.shortPrefix()); + final OntologyChangeSet draft = + OntologyDraftFixtures.draft( + admin(), + ns, + ontology, + OntologyDraftFixtures.creates( + OntologyDraftFixtures.proposedClass(ontology, "Hidden", iri))); + final JsonNode stored = + JsonUtils.readTree( + send( + admin(), + HttpMethod.GET, + CHANGE_SETS + "/" + draft.getId() + "?fields=operations", + null)); + return new Scene( + ontology, + draft, + stored.path("operations").get(0).path("id").asText(), + iri.toString(), + editor); + } + + private static String send( + final OpenMetadataClient caller, + final HttpMethod method, + final String path, + final Object body) { + return caller.getHttpClient().executeForString(method, path, body); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionEndpoint.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionEndpoint.java index b467275984ee..205db8566065 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionEndpoint.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionEndpoint.java @@ -26,6 +26,7 @@ import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.OntologyChangeSetRepository; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.ontology.OntologyDeclinedDefinitions; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.policyevaluator.OperationContext; @@ -55,7 +56,9 @@ OntologyDeclinedDefinitionPage decline( securityContext, new OperationContext(Entity.ONTOLOGY_CHANGE_SET, MetadataOperation.EDIT_ALL), new ResourceContext<>(Entity.ONTOLOGY_CHANGE_SET, request.getChangeSetId(), null)); - final OntologyChangeSet changeSet = changeSetOf(ontologyId, request.getChangeSetId()); + final OntologyChangeSet changeSet = changeSetOf(request.getChangeSetId()); + OntologyChangeSetReadAccess.requireRead(authorizer, securityContext, changeSet); + requireBelongs(changeSet, ontologyId); return declined.decline( changeSet, request.getOperationIds(), @@ -85,15 +88,25 @@ private void requireRead(final SecurityContext securityContext, final UUID ontol authorizer, securityContext, new ResourceContext<>(Entity.ONTOLOGY, ontologyId, null)); } - private static OntologyChangeSet changeSetOf(final UUID ontologyId, final UUID changeSetId) { + private static OntologyChangeSet changeSetOf(final UUID changeSetId) { final OntologyChangeSetRepository repository = (OntologyChangeSetRepository) Entity.getEntityRepository(Entity.ONTOLOGY_CHANGE_SET); - final OntologyChangeSet changeSet = - repository.get(null, changeSetId, repository.getFields("operations"), Include.ALL, false); + return repository.get( + null, + changeSetId, + repository.getFields(OntologyChangeSetReadAccess.SCOPE_FIELDS), + Include.ALL, + false); + } + + private static void requireBelongs(final OntologyChangeSet changeSet, final UUID ontologyId) { if (changeSet.getOntology() == null || !ontologyId.equals(changeSet.getOntology().getId())) { throw new BadRequestException( - "Change set '" + changeSetId + "' does not belong to ontology '" + ontologyId + "'"); + "Change set '" + + changeSet.getId() + + "' does not belong to ontology '" + + ontologyId + + "'"); } - return changeSet; } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionRightsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionRightsTest.java new file mode 100644 index 000000000000..63a5ee5325ca --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionRightsTest.java @@ -0,0 +1,311 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.resources.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.core.SecurityContext; +import java.lang.reflect.Method; +import java.net.URI; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.openmetadata.schema.api.data.DeclineOntologyDefinitions; +import org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyChangeSetRepository; +import org.openmetadata.service.jdbi3.OntologyDeclinedDefinitionDAO; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; +import org.openmetadata.service.util.EntityUtil.Fields; + +/** + * The declined-definition endpoints return or store the IRIs of a change set's operations, so each + * asks the right that reading those operations needs before it reads or writes anything. A new + * endpoint on the path fails this test until its row is added below, and the rows are then held to + * their word by calling each endpoint with a caller the authorizer refuses. + */ +class OntologyDeclinedDefinitionRightsTest { + private static final String BASE = "/v1/ontologies/{id}/declinedDefinitions"; + private static final String DRAFT_READ = "EditAll on the ontology"; + + private static final Map RIGHT_OF = + Map.of( + "POST " + BASE, + "EditAll on the change set, then " + + DRAFT_READ + + " that owns it, then the ontology match", + "GET " + BASE, + DRAFT_READ, + "POST " + BASE + "/match", + DRAFT_READ); + + private final UUID ontologyId = UUID.randomUUID(); + private final UUID otherOntologyId = UUID.randomUUID(); + private final UUID changeSetId = UUID.randomUUID(); + private final SecurityContext caller = Mockito.mock(SecurityContext.class); + + /** A decision of the mocked authorizer: the resource type, its id and the operation asked. */ + private record Asked(String resourceType, Object scope, MetadataOperation operation) {} + + @Test + void everyDeclinedDefinitionEndpointStatesItsRight() { + final Map endpoints = new TreeMap<>(); + for (final Method method : OntologyResource.class.getMethods()) { + final String endpoint = endpointOf(method); + if (endpoint != null && endpoint.contains("declinedDefinitions")) { + endpoints.put(endpoint, method); + } + } + + assertEquals(RIGHT_OF.keySet(), endpoints.keySet()); + RIGHT_OF.forEach((endpoint, right) -> assertFalse(right.isBlank(), endpoint)); + } + + @Test + void aCallerRefusedTheDraftReadStoresNothingAndLearnsNothing() { + final Scene scene = new Scene(ontologyId, Set.of(ontologyId)); + + try (Scene.Open ignored = scene.open()) { + assertThrows( + AuthorizationException.class, + () -> scene.endpoint().decline(caller, ontologyId, scene.request())); + } + + assertEquals( + List.of( + new Asked(Entity.ONTOLOGY_CHANGE_SET, changeSetId, MetadataOperation.EDIT_ALL), + new Asked(Entity.ONTOLOGY, ontologyId, MetadataOperation.EDIT_ALL)), + scene.asked); + Mockito.verifyNoInteractions(scene.dao); + } + + @Test + void aChangeSetOfAnotherOntologyIsRefusedTheReadBeforeItIsRefusedTheMismatch() { + final Scene scene = new Scene(otherOntologyId, Set.of(otherOntologyId)); + + try (Scene.Open ignored = scene.open()) { + assertThrows( + AuthorizationException.class, + () -> scene.endpoint().decline(caller, ontologyId, scene.request())); + } + + assertEquals( + new Asked(Entity.ONTOLOGY, otherOntologyId, MetadataOperation.EDIT_ALL), + scene.asked.getLast()); + Mockito.verifyNoInteractions(scene.dao); + } + + @Test + void aCallerWhoMayReadTheChangeSetOfAnotherOntologyIsToldItDoesNotBelong() { + final Scene scene = new Scene(otherOntologyId, Set.of()); + + try (Scene.Open ignored = scene.open()) { + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> scene.endpoint().decline(caller, ontologyId, scene.request())); + assertEquals( + "Change set '" + changeSetId + "' does not belong to ontology '" + ontologyId + "'", + refusal.getMessage()); + } + + Mockito.verifyNoInteractions(scene.dao); + } + + @Test + void aCallerWhoMayReadTheChangeSetDeclinesItsOperation() { + final Scene scene = new Scene(ontologyId, Set.of()); + + try (Scene.Open ignored = scene.open()) { + assertEquals( + 1, scene.endpoint().decline(caller, ontologyId, scene.request()).getRecords().size()); + } + + Mockito.verify(scene.dao).insertIfAbsent(Mockito.any()); + } + + @Test + void listAndMatchAskTheDraftReadRightOnTheOntologyBeforeTheyReadAnything() { + final Scene scene = new Scene(ontologyId, Set.of(ontologyId)); + + try (Scene.Open ignored = scene.open()) { + assertThrows( + AuthorizationException.class, () -> scene.endpoint().list(caller, ontologyId, 50, null)); + assertThrows( + AuthorizationException.class, + () -> + scene + .endpoint() + .match( + caller, + ontologyId, + new MatchOntologyDeclinedDefinitions().withCandidates(List.of()))); + } + + assertEquals( + List.of( + new Asked(Entity.ONTOLOGY, ontologyId, MetadataOperation.EDIT_ALL), + new Asked(Entity.ONTOLOGY, ontologyId, MetadataOperation.EDIT_ALL)), + scene.asked); + Mockito.verifyNoInteractions(scene.dao); + } + + /** + * One change set holding one concept, owned by {@code changeSetOntology}, and an authorizer that + * refuses the draft read right on the ontologies it is given. + */ + private final class Scene { + final List asked = new ArrayList<>(); + final OntologyDeclinedDefinitionDAO dao = Mockito.mock(OntologyDeclinedDefinitionDAO.class); + private final Authorizer authorizer = Mockito.mock(Authorizer.class); + private final OntologyChangeSet changeSet; + private final UUID operationId = UUID.randomUUID(); + + Scene(final UUID changeSetOntology, final Set refusedOntologies) { + changeSet = + new OntologyChangeSet() + .withId(changeSetId) + .withOntology(new EntityReference().withId(changeSetOntology).withType("ontology")) + .withOperations( + List.of( + new OntologyChangeOperation() + .withId(operationId) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withConcept( + new OntologyConcept() + .withId(UUID.randomUUID()) + .withName("Order") + .withIri(URI.create("https://example.org/sales/Order"))))); + Mockito.doAnswer( + call -> { + final ResourceContextInterface context = call.getArgument(2); + final OperationContext operation = call.getArgument(1); + final Object scope = scopes.get(context); + asked.add( + new Asked( + context.getResource(), scope, operation.getOperations(context).getFirst())); + if (Entity.ONTOLOGY.equals(context.getResource()) + && refusedOntologies.contains(scope)) { + throw new AuthorizationException("denied"); + } + return null; + }) + .when(authorizer) + .authorize( + Mockito.any(SecurityContext.class), + Mockito.any(OperationContext.class), + Mockito.any(ResourceContextInterface.class)); + final Principal principal = Mockito.mock(Principal.class); + Mockito.when(principal.getName()).thenReturn("editor"); + Mockito.when(caller.getUserPrincipal()).thenReturn(principal); + } + + private final Map scopes = new java.util.IdentityHashMap<>(); + + DeclineOntologyDefinitions request() { + return new DeclineOntologyDefinitions() + .withChangeSetId(changeSetId) + .withOperationIds(Set.of(operationId)); + } + + OntologyDeclinedDefinitionEndpoint endpoint() { + return new OntologyDeclinedDefinitionEndpoint(authorizer); + } + + Open open() { + final MockedStatic entity = Mockito.mockStatic(Entity.class); + final CollectionDAO collection = Mockito.mock(CollectionDAO.class); + Mockito.when(collection.ontologyDeclinedDefinitionDAO()).thenReturn(dao); + entity.when(Entity::getCollectionDAO).thenReturn(collection); + final OntologyChangeSetRepository repository = + Mockito.mock(OntologyChangeSetRepository.class); + Mockito.when(repository.getFields("operations")).thenReturn(Mockito.mock(Fields.class)); + Mockito.when( + repository.get( + Mockito.isNull(), + Mockito.eq(changeSetId), + Mockito.any(Fields.class), + Mockito.eq(Include.ALL), + Mockito.eq(false))) + .thenReturn(changeSet); + entity + .when(() -> Entity.getEntityRepository(Entity.ONTOLOGY_CHANGE_SET)) + .thenReturn(repository); + final MockedConstruction contexts = + Mockito.mockConstruction( + ResourceContext.class, + (context, creation) -> { + scopes.put(context, creation.arguments().get(1)); + Mockito.when(context.getResource()) + .thenReturn((String) creation.arguments().get(0)); + }); + return new Open(entity, contexts); + } + + record Open(MockedStatic entity, MockedConstruction contexts) + implements AutoCloseable { + @Override + public void close() { + contexts.close(); + entity.close(); + } + } + } + + private static String endpointOf(final Method method) { + final String verb = verbOf(method); + final Path own = method.getAnnotation(Path.class); + final Path base = OntologyResource.class.getAnnotation(Path.class); + return verb == null ? null : verb + " " + base.value() + (own == null ? "" : own.value()); + } + + private static String verbOf(final Method method) { + String verb = null; + verb = method.isAnnotationPresent(GET.class) ? "GET" : verb; + verb = method.isAnnotationPresent(POST.class) ? "POST" : verb; + verb = method.isAnnotationPresent(PUT.class) ? "PUT" : verb; + verb = method.isAnnotationPresent(DELETE.class) ? "DELETE" : verb; + verb = method.isAnnotationPresent(PATCH.class) ? "PATCH" : verb; + return verb; + } +} From 7082405782199b797a41aa53fd90f1ffac205d03 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 09:13:19 -0800 Subject: [PATCH 115/203] Test null digests, undo and narrow, and permanent delete on both engines, and state the canonical form --- ...ned-definition-is-remembered-by-content.md | 88 ++++-- .../tests/OntologyDeclinedDefinitionIT.java | 252 ++++++++++++++++++ 2 files changed, 319 insertions(+), 21 deletions(-) diff --git a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md index 7c034a5cd4d8..0b05faaf304d 100644 --- a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md +++ b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md @@ -1,11 +1,12 @@ # A declined definition is remembered by its content, and narrowing a draft keeps its classes - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-26 (canonical form stated in full and made stable for set order, empty lists and server-derived fields; narrowing checks every kept operation; a permanent delete removes the rows; declining asks the draft read right) - **Deciders:** Ontology maintainers - **Guard:** `OntologyDefinitionDigestTest`, `OntologyDeclinedDefinitionsTest`, `OntologyDeclinedDefinitionDaoTest`, `OntologyDraftNarrowingTest`, - `OntologyDeclinedDefinitionIT` and `OntologyRolesMigrationIT` + `OntologyDeclinedDefinitionRightsTest`, `OntologyDeclinedDefinitionIT`, + `OntologyDeclinedDefinitionReadIT` and `OntologyRolesMigrationIT` - **Related:** ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights ## Context @@ -24,14 +25,45 @@ declined definition. Its key is the ontology id, the operation type, the SHA-256 definition's IRI and the payload digest. A row also keeps who declined, when, an optional reason, the change set and the operation the definition came from. -**The digest.** The payload digest is the lower-case hexadecimal SHA-256 of the canonical JSON of -the definition, built by `OntologyDefinitionDigest`: +**The digest.** The payload digest is the lower-case hexadecimal SHA-256 of the UTF-8 bytes of the +definition's canonical JSON, built by `OntologyDefinitionDigest` in these steps, in this order: -- object keys sorted, arrays in their order, numbers without trailing zeros, null fields left out; -- `id`, `version`, `updatedAt`, `updatedBy`, `href` and `changeDescription` left out, because a tool - makes a fresh id on every run and the server sets the rest; -- the `ontology` reference reduced to its `id` and `type`, because the ontology is already in the - key and its display name or description can change between runs. +1. **Round trip and defaults.** Write the definition to JSON without its null fields, read that + back into its own type, and write it again. A field that was `null` or left out takes the + schema's default, so the two give one digest. The defaults that carry a value are, for a + concept: `deleted` false, `provider` "user", `abstract` false, `deprecated` false and + `conceptType` "BOTH"; for a property: `deleted` false, `provider` "user", `isIdentifier` false + and `deprecated` false; for an axiom: `deleted` false, `provider` "user" and `provenance` + "Manual". Every list a schema defaults has the default `[]`. +2. **Dropped fields.** Remove these top-level fields: `id`, `version`, `updatedAt`, `updatedBy`, + `href`, `changeDescription`, `incrementalChangeDescription`, `impersonatedBy`, + `lifecycleStatus`, `superClasses` and `subClasses`. A tool makes a fresh id on every run, and + the server sets the next five on every write. The last three are `readOnly` in the schema and + derived from other rows: the superclasses and subclasses from the subclass axioms, the lifecycle + status from the ontology's releases. A parent class a person sets stays in the digest through + the axiom's `targetIri`, and a property's `superProperties` is a field a person sets, so both + stay. +3. **References.** Reduce the `ontology` reference and each entry of `owners` to its `id` and + `type`, because the other fields of a reference (name, display name, description, `href`) change + when something is renamed or served by another route. +4. **Empty values.** Remove every field whose value is `null` and every field whose value is an + empty array, at any depth, so `owners: []` and a missing `owners` agree. +5. **Order.** Sort object keys by their code points at every depth. An array keeps its order, + except the arrays the schema marks `uniqueItems`, which are sets: at the top level of a concept + `synonyms`; of a property `domain`, `range`, `enumValues`, `characteristics`, `disjointWith` and + `superProperties`; of an axiom none. Sort the elements of a set by the compact JSON text of each + element and drop duplicates. `propertyChain` and an axiom's `expressions` are ordered, and keep + their order. +6. **Numbers.** Write a number as its decimal value with trailing zeros removed, in the form of + Java's `BigDecimal.toString`: `1.50` is `1.5`, and `10` is `1E+1`. +7. **Text.** Write compact JSON, with no space after `:` or `,`, strings in UTF-8 with no `\u` + escapes except where JSON requires them, and hash those bytes. + +The canonical text of the class `Order` in the unit test is +`{"abstract":false,"conceptType":"OWL_CLASS","deleted":false,"deprecated":false,"description":"A purchase a customer placed","displayName":"Order","fullyQualifiedName":"sales.Order","iri":"https://example.org/sales/Order","name":"Order","ontology":{"id":"00000000-0000-0000-0000-0000000000a1","type":"ontology"},"provider":"user"}` +and its digest is `d1bef0ebba86898d77e8b761c7d6c1c67a6de316a2d48a8e1595a714077b991b`. The data +property `total` of the same test gives +`dede90b4844e19579b0fc16accf3937493626d37d4cc668960eb95bdece30d10`. Only the server computes digests. A client never canonicalizes JSON. A definition that changes in any other field gets a new digest, so it no longer matches and is proposed again. @@ -44,21 +76,32 @@ carries no definition, such as a delete, cannot be declined. - `POST` declines operations of one change set, named by change set id and operation ids, with an optional reason. The server reads the stored operations and writes one row each. A definition - declined before keeps its first row, so declining twice changes nothing. It needs the right to - edit the change set. + declined before keeps its first row, so declining twice changes nothing. It answers with the IRI + and digest of each operation, so it asks the same right as reading the draft, in this order: + edit on the change set, then edit on the ontology that owns the change set (the draft read + right), and only then does it read the operations or write a row. The check that the change set + belongs to the ontology in the path comes after the read right, so a caller who may not read the + draft is refused as the read is and learns nothing from a mismatch. - `GET` lists rows oldest first, in pages of at most 1000 with an opaque `after` cursor. It needs the right that reads the ontology's working-draft change sets, which is edit on the ontology - (ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights). + (ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights), asked on the ontology in the + path. - `POST .../match` takes up to 1000 candidate operations and returns, for each in order, whether a - row matches its type, IRI and digest, with the digest and the row. It needs the same right as - `GET`. + row matches its type, IRI and digest, with the digest and the row. It asks the same right as + `GET`, edit on the ontology. **Narrowing.** `PUT /v1/ontologyChangeSets/{id}/operations` refuses a native draft with a 400 when an operation it keeps needs a class that only a removed operation of the same draft creates. The message names the class IRIs. The needs are the class positions preflight computes, plus the IRIs -in `requiresConceptIris`. Only the operations before the undo cursor count. A need is met by a -vocabulary class, a datatype, a class a kept operation creates, or a class the ontology already -declares. A class that nothing in the draft creates is left to the check at apply, as before. +in `requiresConceptIris`. Every kept operation is checked, not only the ones before the undo cursor, +because a redo moves the cursor forward and makes a kept operation active. The operation at index +`i` of the kept list is active together with `kept[0 .. max(i + 1, cursor))`, so each class it needs +must be created in that prefix, be a vocabulary class or a datatype, or be one the ontology already +declares. A class that a stored operation created and the prefix does not create is refused. When no +kept operation creates it, the message says that only removed operations create it. When a kept +operation creates it past the prefix, the message says that only kept operations past the undo +cursor create it, and asks to move the cursor past that operation. A class that nothing in the draft +creates is left to the check at apply, as before. ## Consequences A tool matches its next draft against the rows and leaves out what a person declined, and brings a @@ -69,8 +112,11 @@ The digest covers server defaults too: a field that gains a default in a later r digest of every definition declined before it. Revisit the canonical form before adding such a default. -Deleting an ontology leaves its rows, as it leaves its other side tables. +A permanent delete of an ontology removes its rows in the same transaction, after the check for +retained releases. A soft delete keeps them, and a restore serves them again. -Narrowing costs one read of the ontology's declared classes when a removed operation creates a class -a kept operation needs. The undo and redo endpoints move the cursor and are not checked, so a -cursor moved past a class's creation fails at apply, as before. +Narrowing costs one read of the ontology's declared classes when a stored operation created a class +that a kept operation needs and its prefix lacks, and one scan of the kept operations for each +distinct prefix length, which the limit of 1000 operations bounds. The undo and redo endpoints move +the cursor by one operation and are not checked, because a narrowing that passed leaves every +cursor a redo can reach applicable. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionIT.java index 15bf9573830c..ab1e05a603b2 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionIT.java @@ -17,15 +17,20 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.net.URI; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; @@ -51,8 +56,11 @@ import org.openmetadata.schema.type.OntologyEditLeaseToken; import org.openmetadata.schema.type.OntologyEditLock; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; /** * Declining the definitions of a draft, matching a later draft against them, and refusing to narrow @@ -300,6 +308,250 @@ void narrowingToAPropertyWhoseClassAlreadyExistsOrIsKeptIsAcceptedAndApplies( assertEquals(3, applied.getApplicationResult().getOperationsApplied()); } + @Test + void definitionsSentWithExplicitNullsAreMatchedAgainWithFreshIdsAndTheSameNulls( + final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "nulls"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation total = property(ontology, "total", order.getConcept().getIri()); + final OntologyChangeSet draft = draftSentWithNulls(ns, ontology, List.of(order, total)); + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, order.getId(), total.getId())); + + final OntologyChangeOperation freshOrder = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation freshTotal = + property(ontology, "total", order.getConcept().getIri()); + final String withNulls = matchSentWithNulls(ontology, List.of(freshOrder, freshTotal)); + final String withoutThem = + client + .getHttpClient() + .executeForString( + HttpMethod.POST, + DECLINED + ontology.getId() + "/declinedDefinitions/match", + candidates(freshOrder, freshTotal)); + + assertEquals(List.of(true, true), declinedFlags(withNulls)); + assertEquals(List.of(true, true), declinedFlags(withoutThem)); + } + + @Test + void undoNarrowRedoAndApplyIsRefusedAtTheNarrowNamingTheClass(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "undone"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation total = property(ontology, "total", order.getConcept().getIri()); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order, total)); + final OntologyEditLeaseToken lease = lease(draft); + final OntologyChangeSetCommand command = new OntologyChangeSetCommand().withLease(lease); + client.ontologyChangeSets().undo(draft.getId(), command); + + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyChangeSets() + .replaceOperations( + draft.getId(), + new UpdateOntologyChangeSet() + .withLease(lease) + .withOperations(List.of(total)) + .withUndoCursor(0))); + + assertEquals(400, refusal.getStatusCode()); + assertTrue( + refusal + .getMessage() + .contains( + "Ontology operations need classes that only removed operations create: " + + order.getConcept().getIri() + + "."), + refusal.getMessage()); + final OntologyChangeSet unchanged = + client.ontologyChangeSets().get(draft.getId().toString(), "operations"); + assertEquals(2, unchanged.getOperations().size()); + assertEquals(1, unchanged.getUndoCursor()); + } + + @Test + void aClassKeptButUndoneIsRefusedWithTheMessageForAnUndoneClass(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "cursor"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation total = property(ontology, "total", order.getConcept().getIri()); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order, total)); + final OntologyEditLeaseToken lease = lease(draft); + + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyChangeSets() + .replaceOperations( + draft.getId(), + new UpdateOntologyChangeSet() + .withLease(lease) + .withOperations(List.of(total, order)) + .withUndoCursor(1))); + + assertEquals(400, refusal.getStatusCode()); + assertTrue( + refusal + .getMessage() + .contains( + "Ontology operations need classes that only kept operations past the undo cursor" + + " create: " + + order.getConcept().getIri() + + ". Move the undo cursor past the operation that creates each class, or" + + " remove the operations that need it."), + refusal.getMessage()); + } + + @Test + void aPermanentDeleteOfAnOntologyRemovesItsDeclinedDefinitions(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Counts the embedded server's rows"); + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = client.ontologies().create(request(ns).withName(ns.prefix("purged"))); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation customer = concept(ontology, "Customer", "A buyer"); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order, customer)); + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, order.getId(), customer.getId())); + assertEquals(2, declinedRows(ontology)); + + client + .ontologies() + .delete(ontology.getId().toString(), Map.of("recursive", "true", "hardDelete", "true")); + + assertEquals(0, declinedRows(ontology)); + } + + @Test + void aSoftDeleteKeepsTheDeclinedDefinitionsAndARestoreServesThemAgain(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Counts the embedded server's rows"); + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "archived"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order)); + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, order.getId())); + + client.ontologies().delete(ontology.getId().toString(), Map.of("recursive", "true")); + assertEquals(1, declinedRows(ontology)); + client.ontologies().restore(ontology.getId()); + + assertEquals(1, declinedRows(ontology)); + assertEquals( + 1, + client + .ontologyDeclinedDefinitions() + .list(ontology.getId(), null, null) + .getRecords() + .size()); + assertTrue( + client + .ontologyDeclinedDefinitions() + .match(ontology.getId(), candidates(concept(ontology, "Order", "A purchase"))) + .getMatches() + .getFirst() + .getDeclined()); + } + + private static final String DECLINED = "/v1/ontologies/"; + private static final List CONCEPT_NULLS = + List.of( + "synonyms", + "conceptMappings", + "deleted", + "provider", + "abstract", + "deprecated", + "superClasses", + "subClasses", + "owners", + "replacedBy"); + private static final List PROPERTY_NULLS = + List.of( + "deleted", + "provider", + "enumValues", + "isIdentifier", + "characteristics", + "propertyChain", + "disjointWith", + "superProperties", + "deprecated", + "owners", + "unit", + "replacedBy"); + + private static int declinedRows(final Ontology ontology) { + return Entity.getCollectionDAO() + .ontologyDeclinedDefinitionDAO() + .listAfter(ontology.getId().toString(), false, 0L, "", "", "", 100) + .size(); + } + + /** The operations as a generator that writes every optional field as null sends them. */ + private static ArrayNode operationsWithNulls(final List operations) { + final ArrayNode nodes = JsonUtils.getObjectMapper().createArrayNode(); + for (final OntologyChangeOperation operation : operations) { + final ObjectNode node = (ObjectNode) JsonUtils.valueToTree(operation); + if (node.has("concept")) { + CONCEPT_NULLS.forEach(field -> ((ObjectNode) node.get("concept")).putNull(field)); + } + if (node.has("property")) { + PROPERTY_NULLS.forEach(field -> ((ObjectNode) node.get("property")).putNull(field)); + } + nodes.add(node); + } + return nodes; + } + + private static OntologyChangeSet draftSentWithNulls( + final TestNamespace ns, + final Ontology ontology, + final List operations) { + final var client = SdkClients.adminClient(); + final ObjectNode request = + (ObjectNode) + JsonUtils.valueToTree( + new CreateOntologyChangeSet() + .withName(ns.prefix("draft") + UUID.randomUUID()) + .withDisplayName("Proposed definitions") + .withDescription("Definitions proposed for review") + .withOntology(ontology.getFullyQualifiedName()) + .withBaseWorkingRevision( + client.ontologies().state(ontology.getId()).getWorkingRevision())); + request.set("operations", operationsWithNulls(operations)); + final String created = + client.getHttpClient().executeForString(HttpMethod.POST, "/v1/ontologyChangeSets", request); + return ns.trackRoot("ontologyChangeSet", JsonUtils.readValue(created, OntologyChangeSet.class)); + } + + private static String matchSentWithNulls( + final Ontology ontology, final List operations) { + final ObjectNode request = JsonUtils.getObjectNode(); + request.set("candidates", operationsWithNulls(operations)); + return SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.POST, DECLINED + ontology.getId() + "/declinedDefinitions/match", request); + } + + private static List declinedFlags(final String matches) { + final List flags = new java.util.ArrayList<>(); + JsonUtils.readTree(matches) + .path("matches") + .forEach(match -> flags.add(match.path("declined").asBoolean())); + return flags; + } + private static UpdateOntologyChangeSet narrowTo( final OntologyEditLeaseToken lease, final OntologyChangeOperation... kept) { return new UpdateOntologyChangeSet() From e654f33df50354059319d30cf88551933efa219f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 09:53:37 -0800 Subject: [PATCH 116/203] Keep a task's suggestion type through a resolution, validate the whole constraint set before approving, and test the constraint rules --- .../service/jdbi3/TableRepository.java | 2 +- .../tasks/TableConstraintSuggestion.java | 53 ++++- .../service/tasks/TaskWorkflowHandler.java | 1 + .../tasks/TableConstraintSuggestionTest.java | 205 ++++++++++++++++++ 4 files changed, 256 insertions(+), 5 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java index bed86ce35b1f..9b5f6cac4dbe 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java @@ -2307,7 +2307,7 @@ private CustomMetric getCustomMetric(Table table, String extension) { CustomMetric.class); } - private void validateTableConstraints(Table table, Set columnsBeingRemoved) { + public void validateTableConstraints(Table table, Set columnsBeingRemoved) { if (!nullOrEmpty(table.getTableConstraints())) { Set constraintSet = new HashSet<>(); for (TableConstraint constraint : table.getTableConstraints()) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java index 1c690605d7e2..c81c48fbf515 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; +import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Objects; @@ -29,10 +30,12 @@ import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.schema.type.TaskEntityType; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.TableRepository; import org.openmetadata.service.util.FullyQualifiedName; /** @@ -43,11 +46,13 @@ *

      A task is refused when it is filed, and again when it is approved with the resolver's payload * laid over it, unless it names a table, a supported constraint type, columns of that table and, for * a foreign key, referred columns of existing tables. Approving also refuses a second primary key - * (ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint). + * (ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint). A resolution cannot change a + * task's suggestion type to or from {@code TableConstraint}. */ public final class TableConstraintSuggestion { public static final String TYPE = "TableConstraint"; public static final String FIELD_PATH = "tableConstraints"; + private static final String SUGGESTION_TYPE = "suggestionType"; private static final String TABLE_FIELDS = "columns,tableConstraints"; private static final Set SUPPORTED = EnumSet.of(ConstraintType.PRIMARY_KEY, ConstraintType.UNIQUE, ConstraintType.FOREIGN_KEY); @@ -56,8 +61,31 @@ private TableConstraintSuggestion() {} public static boolean isTableConstraint(Task task) { return task != null - && task.getPayload() != null - && TYPE.equals(JsonUtils.valueToTree(task.getPayload()).path("suggestionType").asText("")); + && task.getType() == TaskEntityType.Suggestion + && TYPE.equals(suggestionTypeOf(task.getPayload())); + } + + private static String suggestionTypeOf(Object payload) { + return payload == null ? "" : JsonUtils.valueToTree(payload).path(SUGGESTION_TYPE).asText(""); + } + + /** + * Refuses a resolution whose payload changes the task's suggestion type to or from {@code + * TableConstraint}. Approving is authorized for the type the task was filed with, so a changed + * type would write a table constraint on the right to edit a description. + */ + public static void requireSameSuggestionType(Task task, Object requestPayload) { + if (task == null || task.getType() != TaskEntityType.Suggestion || requestPayload == null) { + return; + } + String stored = suggestionTypeOf(task.getPayload()); + String requested = suggestionTypeOf(requestPayload); + boolean changed = !requested.isEmpty() && !requested.equals(stored); + if (changed && (TYPE.equals(stored) || TYPE.equals(requested))) { + throw BadRequestException.of( + "A resolution cannot change the suggestion type of a task to or from %s: the task is '%s', the resolution says '%s'" + .formatted(TYPE, stored, requested)); + } } /** Refuses filing a table constraint suggestion that names no valid constraint of its table. */ @@ -78,7 +106,11 @@ public static void requireToApply(Task task, Object requestPayload, String newVa TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); Table table = loadTable(task); TableConstraint constraint = validate(task, merged, table); - toAdd(table, constraint); + toAdd(table, constraint) + .ifPresent( + added -> + tableRepository() + .validateTableConstraints(tableWith(table, added), Collections.emptySet())); } } @@ -107,6 +139,19 @@ public static Optional toAdd(Table table, TableConstraint const return Optional.of(constraint); } + private static TableRepository tableRepository() { + return (TableRepository) Entity.getEntityRepository(Entity.TABLE); + } + + /** What the table repository validates on a write: the table's constraints with one added. */ + private static Table tableWith(Table table, TableConstraint added) { + return new Table() + .withName(table.getName()) + .withFullyQualifiedName(table.getFullyQualifiedName()) + .withColumns(table.getColumns()) + .withTableConstraints(withConstraint(table, added)); + } + /** The table's constraints with {@code constraint} added. */ public static List withConstraint(Table table, TableConstraint constraint) { List constraints = new ArrayList<>(listOrEmpty(table.getTableConstraints())); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 6d6c4cf8d687..63d142b38154 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -201,6 +201,7 @@ public Task resolveTask( user); TaskFieldTarget.requireToApply(task, effectiveResolutionType, resolvedPayload); if (isPositiveResolution(effectiveResolutionType)) { + TableConstraintSuggestion.requireSameSuggestionType(task, resolvedPayload); TableConstraintSuggestion.requireToApply(task, resolvedPayload, newValue); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java index c5706e603882..1259e555dfa4 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -20,6 +20,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; @@ -31,6 +32,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -46,24 +48,29 @@ import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.schema.type.TableConstraint.RelationshipType; +import org.openmetadata.schema.type.TaskEntityStatus; import org.openmetadata.schema.type.TaskEntityType; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.TableRepository; class TableConstraintSuggestionTest { private static final String ORDERS = "svc.db.schema.orders"; private static final String CUSTOMERS = "svc.db.schema.customers"; private MockedStatic entity; private Table orders; + private TableRepository tableRepository; @BeforeEach void setUp() { orders = table("orders", ORDERS, "order_id", "customer_id", "email"); Table customers = table("customers", CUSTOMERS, "id"); + tableRepository = mock(TableRepository.class); entity = mockStatic(Entity.class); + entity.when(() -> Entity.getEntityRepository(Entity.TABLE)).thenAnswer(i -> tableRepository); entity .when(() -> Entity.getEntity(any(EntityReference.class), anyString(), any(Include.class))) .thenAnswer(invocation -> orders); @@ -271,6 +278,204 @@ void applyingASuggestionTheTableAlreadyHas_writesNothing() throws Exception { assertEquals(1, orders.getTableConstraints().size()); } + @Test + void aForeignKeyOnTheSameColumnsReferringToAnotherColumn_isNotTheSuggestedOne() { + TableConstraint present = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".other")); + orders.setTableConstraints(List.of(present)); + TableConstraint suggested = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id")); + + assertEquals(Optional.of(suggested), TableConstraintSuggestion.toAdd(orders, suggested)); + } + + @Test + void aForeignKeyOfTwoColumnsWithOneReferredColumn_isRefused() { + TableConstraint foreignKey = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id", "order_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id")); + + assertEquals( + "A foreign key needs one referred column for each of its 2 columns, not 1", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, foreignKey))) + .getMessage()); + } + + @Test + void aForeignKeyWithNoReferredColumns_isRefused() { + TableConstraint foreignKey = constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")); + + assertEquals( + "A foreign key needs one referred column for each of its 1 columns, not 0", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, foreignKey))) + .getMessage()); + } + + @Test + void aUniqueConstraintWithReferredColumns_isRefused() { + TableConstraint unique = + constraint(ConstraintType.UNIQUE, List.of("email")) + .withReferredColumns(List.of(CUSTOMERS + ".id")); + + assertEquals( + "Only a foreign key has referredColumns, not UNIQUE", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, unique))) + .getMessage()); + } + + @Test + void aFailureWhileApplying_escapesAndLeavesTheTaskOpen() throws Exception { + EntityRepository repository = mock(EntityRepository.class); + doThrow(new IllegalStateException("write failed")) + .when(repository) + .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + task.setStatus(TaskEntityStatus.Open); + + java.lang.reflect.InvocationTargetException thrown = + assertThrows( + java.lang.reflect.InvocationTargetException.class, + () -> invokeApplySuggestion(task, orders, repository, "approver")); + + assertEquals("write failed", thrown.getCause().getMessage()); + assertEquals(TaskEntityStatus.Open, task.getStatus()); + } + + @Test + void aTaskOfAnotherTypeCarryingAConstraintPayload_getsNoCheckAndNoRethrow() throws Exception { + Task task = taskWithValue("not json at all").withType(TaskEntityType.DescriptionUpdate); + EntityRepository repository = mock(EntityRepository.class); + doThrow(new IllegalStateException("write failed")) + .when(repository) + .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + Task applied = + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))) + .withType(TaskEntityType.DescriptionUpdate); + + assertEquals(false, TableConstraintSuggestion.isTableConstraint(task)); + assertDoesNotThrow(() -> TableConstraintSuggestion.require(task)); + assertDoesNotThrow(() -> TableConstraintSuggestion.requireToApply(task, null, null)); + assertDoesNotThrow(() -> invokeApplySuggestion(applied, orders, repository, "approver")); + } + + @Test + void aResolutionCannotTurnADescriptionSuggestionIntoAConstraint() { + Task description = descriptionTask(); + Map resolution = + Map.of( + "suggestionType", + "TableConstraint", + "fieldPath", + "tableConstraints", + "suggestedValue", + JsonUtils.pojoToJson(constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")))); + + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is 'Description', the resolution says 'TableConstraint'", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.requireSameSuggestionType(description, resolution)) + .getMessage()); + } + + @Test + void aResolutionCannotTurnAConstraintSuggestionIntoAnotherType() { + Task constraintTask = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is 'TableConstraint', the resolution says 'Owner'", + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + constraintTask, Map.of("suggestionType", "Owner"))) + .getMessage()); + } + + @Test + void aResolutionBetweenOtherTypesOrOfTheSameType_isNotRefusedHere() { + Task constraintTask = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertDoesNotThrow( + () -> + TableConstraintSuggestion.requireSameSuggestionType( + descriptionTask(), Map.of("suggestionType", "Tag"))); + assertDoesNotThrow( + () -> + TableConstraintSuggestion.requireSameSuggestionType( + constraintTask, Map.of("suggestionType", "TableConstraint"))); + assertDoesNotThrow( + () -> TableConstraintSuggestion.requireSameSuggestionType(constraintTask, null)); + assertDoesNotThrow( + () -> + TableConstraintSuggestion.requireSameSuggestionType( + constraintTask, Map.of("reasoning", "no type given"))); + } + + @Test + void approving_runsTheTableRepositoryValidationOnTheConstraintsWithTheNewOneAdded() { + TableConstraint present = constraint(ConstraintType.UNIQUE, List.of("order_id")); + orders.setTableConstraints(List.of(present)); + TableConstraint suggested = constraint(ConstraintType.UNIQUE, List.of("email")); + + TableConstraintSuggestion.requireToApply(task(Entity.TABLE, suggested), null, null); + + ArgumentCaptor

  • validated = ArgumentCaptor.forClass(Table.class); + verify(tableRepository).validateTableConstraints(validated.capture(), eq(Set.of())); + assertEquals(List.of(present, suggested), validated.getValue().getTableConstraints()); + } + + @Test + void aTableRepositoryRefusalOfTheConstraints_refusesApproving() { + doThrow(new IllegalArgumentException("Table not found: " + CUSTOMERS)) + .when(tableRepository) + .validateTableConstraints(any(Table.class), any()); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals( + "Table not found: " + CUSTOMERS, + assertThrows( + IllegalArgumentException.class, + () -> TableConstraintSuggestion.requireToApply(task, null, null)) + .getMessage()); + } + + @Test + void approvingAnEqualConstraint_doesNotValidateTheTable() { + orders.setTableConstraints(List.of(constraint(ConstraintType.UNIQUE, List.of("email")))); + + TableConstraintSuggestion.requireToApply( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), null, null); + + verify(tableRepository, never()).validateTableConstraints(any(Table.class), any()); + } + + private Task descriptionTask() { + Map payload = new java.util.LinkedHashMap<>(); + payload.put("suggestionType", "Description"); + payload.put("fieldPath", "description"); + payload.put("suggestedValue", "a description"); + return new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withAbout( + new EntityReference() + .withId(orders.getId()) + .withType(Entity.TABLE) + .withFullyQualifiedName(ORDERS)) + .withPayload(payload); + } + private static void invokeApplySuggestion( Task task, Table table, EntityRepository repository, String user) throws Exception { Method applySuggestion = From 616b5bb475ba92bca289797cc41cc57e4a880045 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 09:57:44 -0800 Subject: [PATCH 117/203] Test that a resolution keeps a suggestion's type and that approving checks the whole constraint set, and record both --- ...stion-task-can-carry-a-table-constraint.md | 12 +- .../TaskTableConstraintSuggestionIT.java | 160 +++++++++++++++++- 2 files changed, 169 insertions(+), 3 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index c21a2ea5670e..53a622806ed1 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,9 +1,9 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving) - **Deciders:** OpenMetadata maintainers -- **Guard:** `TableConstraintSuggestionTest`, `SuggestionTypeRoutingTest`, `TaskTableConstraintSuggestionIT` +- **Guard:** `TableConstraintSuggestionTest` (the type check on a resolution, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply), `SuggestionTypeRoutingTest`, `TaskTableConstraintSuggestionIT` - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type ## Context @@ -35,6 +35,14 @@ declined. the existing one, before anything is written, and the task stays open. A failure while applying a constraint is raised to the caller, unlike the other suggestion types, so a task is never `Approved` for a constraint that was not added. +- A resolution cannot change a suggestion task's type to or from `TableConstraint`. Approving is + authorized for the type the task was filed with, so a resolution payload that names another type + would add a constraint on the right to edit something narrower. Such a resolution is refused with + a 400 before the workflow moves, and a change between the other types is as it was. +- Before the workflow moves, approving runs the table repository's own validation on the table's + constraints with the new one added, so a constraint set the write would refuse (for example a + foreign key to a table that was deleted) is refused with a 400 while the task is still open and + can still be rejected. - Rejecting leaves the table unchanged and the task `Rejected`. - A client finds the suggestions already made for a table, and the ones declined, by listing the tasks about that table with type `Suggestion` and a status, and reading `payload.suggestionType` diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 3f758d375eb2..1ca13bf1a926 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -142,6 +142,7 @@ void rejectingLeavesTheTableAsItWasAndTheRejectionIsListedByTableAndStatus(TestN TableConstraint proposed = constraint(ConstraintType.PRIMARY_KEY, "id"); Task task = suggest(ns, table, "reject", proposed, null); awaitWorkflowTask(task); + addConstraint(table, constraint(ConstraintType.PRIMARY_KEY, "name")); Task rejected = SdkClients.adminClient() @@ -153,7 +154,10 @@ void rejectingLeavesTheTableAsItWasAndTheRejectionIsListedByTableAndStatus(TestN .withComment("id is not unique")); assertEquals(TaskEntityStatus.Rejected, rejected.getStatus()); - assertEquals(List.of(), constraintsOf(table)); + List kept = constraintsOf(table); + assertEquals(1, kept.size()); + assertEquals(ConstraintType.PRIMARY_KEY, kept.get(0).getConstraintType()); + assertEquals(List.of("name"), kept.get(0).getColumns()); ListParams params = new ListParams(); params.addFilter("aboutEntity", table.getFullyQualifiedName()); params.addFilter("type", "Suggestion"); @@ -259,6 +263,160 @@ void aDescriptionAndATagSuggestionStillApply(TestNamespace ns) { List.of("PII.Sensitive"), updated.getTags().stream().map(t -> t.getTagFQN()).toList()); } + private static final String TYPE_CHANGE_REFUSED = + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is '%s', the resolution says '%s'"; + + @Test + void aDescriptionSuggestionCannotBeResolvedIntoAConstraintByAnAssigneeWhoMayOnlyEditDescriptions( + TestNamespace ns) { + Table table = adminTable(ns, "switch"); + String before = descriptionOf(table); + Task task = + file( + ns, + table, + "switch", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "a description"), + List.of(SharedEntities.get().USER2.getFullyQualifiedName())); + awaitWorkflowTask(task); + + InvalidRequestException refused = + assertThrows( + InvalidRequestException.class, + () -> + resolve( + SdkClients.user2Client(), + task, + payload(JsonUtils.pojoToJson(constraint(ConstraintType.PRIMARY_KEY, "id"))))); + + assertTrue( + refused + .getMessage() + .contains(TYPE_CHANGE_REFUSED.formatted("Description", "TableConstraint")), + refused.getMessage()); + assertEquals(List.of(), constraintsOf(table)); + assertEquals(before, descriptionOf(table)); + assertStillOpen(task); + } + + @Test + void aConstraintSuggestionCannotBeResolvedAsAnotherType(TestNamespace ns) { + Table table = adminTable(ns, "asowner"); + Task task = suggest(ns, table, "asowner", constraint(ConstraintType.PRIMARY_KEY, "id"), null); + awaitWorkflowTask(task); + + InvalidRequestException refused = + assertThrows( + InvalidRequestException.class, + () -> resolve(SdkClients.adminClient(), task, Map.of("suggestionType", "Owner"))); + + assertTrue( + refused.getMessage().contains(TYPE_CHANGE_REFUSED.formatted("TableConstraint", "Owner")), + refused.getMessage()); + assertEquals(List.of(), constraintsOf(table)); + assertStillOpen(task); + } + + @Test + void aDescriptionSuggestionResolvedWithATagPayloadStillAppliesTheTags(TestNamespace ns) { + Table table = ownedTable(ns, "todescription"); + String before = descriptionOf(table); + Task task = + file( + ns, + table, + "totag", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "a description"), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + Map tagPayload = new LinkedHashMap<>(); + tagPayload.put("suggestionType", "Tag"); + tagPayload.put("fieldPath", "tags"); + tagPayload.put( + "suggestedValue", + "[{\"tagFQN\":\"PII.Sensitive\",\"source\":\"Classification\"," + + "\"labelType\":\"Manual\",\"state\":\"Confirmed\"}]"); + + Task resolved = resolve(SdkClients.user3Client(), task, tagPayload); + + assertEquals(TaskEntityStatus.Approved, resolved.getStatus()); + Table updated = + SdkClients.adminClient().tables().getByName(table.getFullyQualifiedName(), TABLE_FIELDS); + assertEquals( + List.of("PII.Sensitive"), updated.getTags().stream().map(t -> t.getTagFQN()).toList()); + assertEquals(before, descriptionOf(table)); + } + + @Test + void approvingIsRefusedWhileAnExistingForeignKeyReferstoADeletedTableAndTheTaskCanBeRejected( + TestNamespace ns) { + Table orders = adminTable(ns, "stuckorders"); + Table customers = adminTable(ns, "stuckcustomers"); + String customerId = FullyQualifiedName.add(customers.getFullyQualifiedName(), "id"); + addConstraint( + orders, + constraint(ConstraintType.FOREIGN_KEY, "id") + .withReferredColumns(List.of(customerId)) + .withRelationshipType(RelationshipType.MANY_TO_ONE)); + SdkClients.adminClient() + .tables() + .delete(customers.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + Task task = suggest(ns, orders, "stuck", constraint(ConstraintType.UNIQUE, "name"), null); + awaitWorkflowTask(task); + + InvalidRequestException refused = + assertThrows(InvalidRequestException.class, () -> apply(SdkClients.adminClient(), task)); + + assertTrue( + refused.getMessage().contains("Table not found: " + customers.getFullyQualifiedName()), + refused.getMessage()); + assertEquals(1, constraintsOf(orders).size()); + assertStillOpen(task); + assertTrue(WorkflowHandler.getInstance().hasActiveRuntimeTask(task.getId())); + + Task rejected = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals(TaskEntityStatus.Rejected, rejected.getStatus()); + } + + private static String descriptionOf(Table table) { + return SdkClients.adminClient() + .tables() + .getByName(table.getFullyQualifiedName(), TABLE_FIELDS) + .getDescription(); + } + + private static void assertStillOpen(Task task) { + assertEquals( + TaskEntityStatus.Open, + SdkClients.adminClient().tasks().get(task.getId().toString()).getStatus()); + assertTrue(WorkflowHandler.getInstance().hasActiveRuntimeTask(task.getId())); + } + + private static Task resolve(OpenMetadataClient client, Task task, Map payload) { + return client + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Approved) + .withPayload( + JsonUtils.convertValue( + payload, org.openmetadata.schema.api.tasks.Payload.class))); + } + private static String fileRefused( TestNamespace ns, Table table, String label, String suggestedValue) { return assertThrows( From 2b8502788ca6c5af051e4e86a3d8c5aad4ff061c Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 11:02:42 -0800 Subject: [PATCH 118/203] Regenerate the UI's TypeScript types for declined ontology definitions --- .../api/data/declineOntologyDefinitions.ts | 21 + .../data/matchOntologyDeclinedDefinitions.ts | 1490 +++++++++++++++++ .../type/ontologyDeclinedDefinition.ts | 61 + .../type/ontologyDeclinedDefinitionMatches.ts | 90 + .../type/ontologyDeclinedDefinitionPage.ts | 72 + 5 files changed, 1734 insertions(+) create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/declineOntologyDefinitions.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/matchOntologyDeclinedDefinitions.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinition.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinitionMatches.ts create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinitionPage.ts diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/declineOntologyDefinitions.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/declineOntologyDefinitions.ts new file mode 100644 index 000000000000..ae748a441900 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/declineOntologyDefinitions.ts @@ -0,0 +1,21 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Record that the definitions carried by some operations of one change set are declined. + * The server reads the stored operations and computes each digest. + */ +export interface DeclineOntologyDefinitions { + changeSetId: string; + operationIds: string[]; + reason?: string; +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/matchOntologyDeclinedDefinitions.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/matchOntologyDeclinedDefinitions.ts new file mode 100644 index 000000000000..fd732a6aada2 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/matchOntologyDeclinedDefinitions.ts @@ -0,0 +1,1490 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Candidate operations, as they would be put in a new change set, to match against an + * ontology's declined definitions. + */ +export interface MatchOntologyDeclinedDefinitions { + candidates: OntologyChangeOperation[]; +} + +/** + * A typed, reversible operation in an ontology authoring session. + */ +export interface OntologyChangeOperation { + axiom?: OntologyAxiom; + /** + * Version used for optimistic concurrency. Omitted for create operations. On a binding + * operation it is the binding revision of the class that the operation was built against, + * required when the table is already bound to the class. + */ + baseVersion?: number; + /** + * Only on an UPSERT_SHAPE operation. + */ + basis?: Basis; + /** + * The payload of an UPSERT_BINDING operation. + */ + binding?: OntologyBindingChange; + concept?: OntologyConcept; + /** + * Model confidence in this AI suggestion, from 0 to 1. + */ + confidence?: number; + /** + * The tables and columns that support the operation. A save stores the entries about tables + * its writer may view and keeps the stored entries its writer was not shown. A read returns + * only the entries whose table the reader may view. A change event has no single reader, so + * no change event and no recorded change carries an entry. + */ + evidence?: OntologyChangeEvidence[]; + glossary?: Glossary; + id: string; + mapping?: ConceptMapping; + /** + * Identifier of the model that produced this AI suggestion. + */ + modelId?: string; + operationType: OperationType; + property?: OntologyProperty; + /** + * Model explanation of the evidence behind this AI suggestion. + */ + rationale?: string; + relationship?: OntologyRelationship; + /** + * IRIs of concepts that the operation needs in the ontology. Applying the operation is + * refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT + * operation of the same change set. A binding or a shape operation always needs its own + * class, listed here or not. + */ + requiresConceptIris?: string[]; + /** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + */ + shape?: OntologyShape; + /** + * Published context memories that support this AI suggestion. + */ + sourceMemoryIds?: string[]; + state: CandidateState; + targetId?: string; + term?: GlossaryTerm; + /** + * How many evidence entries a read left out of this operation because the reader may not + * view the table they name, or because that table no longer exists. The server sets it on + * every operation it returns that stores evidence. It is never stored. It is read-only in + * effect: a client sends it back unchanged on a save, and when it is present and differs + * from the number the server withholds from that writer now for the stored operation, the + * save is refused with a 412 and the writer reads the change set again. A save that sends + * none is not checked. + */ + withheldEvidenceCount?: number; +} + +/** + * A governed OWL axiom whose relational representation remains authoritative when RDF is + * disabled. + */ +export interface OntologyAxiom { + axiomType: AxiomType; + changeDescription?: ChangeDescription; + deleted?: boolean; + description: string; + displayName: string; + /** + * Class expressions participating in the axiom, ordered from left to right. + */ + expressions: OntologyExpression[]; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + literal?: Literal; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + propertyIri?: string; + provenance: Provenance; + provider?: ProviderType; + subjectIri: string; + targetIri?: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +export enum AxiomType { + ClassAssertion = "CLASS_ASSERTION", + DataPropertyAssertion = "DATA_PROPERTY_ASSERTION", + DisjointWith = "DISJOINT_WITH", + EquivalentClass = "EQUIVALENT_CLASS", + ObjectPropertyAssertion = "OBJECT_PROPERTY_ASSERTION", + SubclassOf = "SUBCLASS_OF", +} + +/** + * Description of the change. + * + * Change that lead to this version of the entity. + */ +export interface ChangeDescription { + changeSummary?: { [key: string]: ChangeSummary }; + /** + * Names of fields added during the version changes. + */ + fieldsAdded?: FieldChange[]; + /** + * Fields deleted during the version changes with old value before deleted. + */ + fieldsDeleted?: FieldChange[]; + /** + * Fields modified during the version changes with old and new values. + */ + fieldsUpdated?: FieldChange[]; + /** + * When a change did not result in change, this could be same as the current version. + */ + previousVersion?: number; +} + +export interface ChangeSummary { + changedAt?: number; + /** + * Name of the user or bot who made this change + */ + changedBy?: string; + changeSource?: ChangeSource; + [property: string]: any; +} + +/** + * The source of the change. This will change based on the context of the change (example: + * manual vs programmatic) + */ +export enum ChangeSource { + Automated = "Automated", + Derived = "Derived", + Ingested = "Ingested", + Manual = "Manual", + Propagated = "Propagated", + Suggested = "Suggested", +} + +export interface FieldChange { + /** + * Name of the entity field that changed. + */ + name?: string; + /** + * New value of the field. Note that this is a JSON string and use the corresponding field + * type to deserialize it. + */ + newValue?: any; + /** + * Previous value of the field. Note that this is a JSON string and use the corresponding + * field type to deserialize it. + */ + oldValue?: any; +} + +/** + * A recursive OWL class expression represented without untyped maps. + * + * Class expression qualifying a restriction. + */ +export interface OntologyExpression { + /** + * Non-negative cardinality for MIN, MAX, and EXACT restrictions. + */ + cardinality?: number; + /** + * Class IRI when kind is NAMED_CLASS. + */ + classIri?: string; + /** + * Class expression qualifying a restriction. + */ + filler?: OntologyExpression; + /** + * Individual value for an object has-value restriction. + */ + individualIri?: string; + /** + * Named individuals used by an enumeration expression. Presence is enforced per expression + * kind by the OWL profile guard. + */ + individualIris?: string[]; + kind: ExpressionKind; + /** + * Literal value for a data has-value restriction. + */ + literal?: Literal; + /** + * Nested expressions for intersection and union expressions. Minimum operand counts are + * enforced per expression kind by the OWL profile guard. + */ + operands?: OntologyExpression[]; + /** + * Property constrained by a restriction. + */ + propertyIri?: string; + restrictionKind?: RestrictionKind; +} + +/** + * Kind of recursive class expression. + */ +export enum ExpressionKind { + Intersection = "INTERSECTION", + NamedClass = "NAMED_CLASS", + OneOf = "ONE_OF", + Restriction = "RESTRICTION", + Union = "UNION", +} + +/** + * Literal value for a data has-value restriction. + * + * A typed OWL literal. + */ +export interface Literal { + datatypeIri?: string; + value: string; +} + +/** + * Supported OWL restriction operator. + */ +export enum RestrictionKind { + Exact = "EXACT", + Max = "MAX", + Min = "MIN", + Only = "ONLY", + Some = "SOME", + Value = "VALUE", +} + +/** + * This schema defines the EntityReference type used for referencing an entity. + * EntityReference is used for capturing relationships from one entity to another. For + * example, a table has an attribute called database of type EntityReference that captures + * the relationship of a table `belongs to a` database. + * + * This schema defines the EntityReferenceList type used for referencing an entity. + * EntityReference is used for capturing relationships from one entity to another. For + * example, a table has an attribute called database of type EntityReference that captures + * the relationship of a table `belongs to a` database. + * + * Owning ontology entity. Glossaries do not own ontology definitions. + * + * Reference to the data contract for this entity. + * + * Glossary that this term belongs to. + * + * Parent glossary term that this term is child of. When `null` this term is the root term + * of the glossary. + * + * Resolved first-class relationship type. + * + * Reference to the related glossary term. + */ +export interface EntityReference { + /** + * If true the entity referred to has been soft-deleted. + */ + deleted?: boolean; + /** + * Optional description of entity. + */ + description?: string; + /** + * Display Name that identifies this entity. + */ + displayName?: string; + /** + * Fully qualified name of the entity instance. For entities such as tables, databases + * fullyQualifiedName is returned in this field. For entities that don't have name hierarchy + * such as `user` and `team` this will be same as the `name` field. + */ + fullyQualifiedName?: string; + /** + * Link to the entity resource. + */ + href?: string; + /** + * Unique identifier that identifies an entity instance. + */ + id: string; + /** + * If true the relationship indicated by this entity reference is inherited from the parent + * entity. + */ + inherited?: boolean; + /** + * Name of the entity instance. + */ + name?: string; + /** + * Entity type/class name - Examples: `database`, `table`, `metrics`, `databaseService`, + * `dashboardService`... + */ + type: string; +} + +/** + * How this relation edge originated. + * + * How this relation edge originated. Defaults to 'Manual'. + */ +export enum Provenance { + AISuggested = "AiSuggested", + Imported = "Imported", + Inferred = "Inferred", + Manual = "Manual", +} + +/** + * Type of provider of an entity. Some entities are provided by the `system`. Some are + * entities created and provided by the `user`. Typically `system` provide entities can't be + * deleted and can only be disabled. Some apps such as AutoPilot create entities with + * `automation` provider type. These entities can be deleted by the user. + */ +export enum ProviderType { + Automation = "automation", + System = "system", + User = "user", +} + +/** + * Only on an UPSERT_SHAPE operation. + * + * Where a proposed shape comes from. `declared` restates what the catalog already declares, + * such as a column constraint. `observed` generalizes from what the stored metadata shows, + * such as a profile. + */ +export enum Basis { + Declared = "declared", + Observed = "observed", +} + +/** + * The payload of an UPSERT_BINDING operation. + * + * One table binding of one class, as a change set operation carries it. The class and each + * property are named by IRI, so the operation can refer to definitions that the same change + * set creates. Applying it adds or replaces the binding of this table and keeps the other + * bindings of the class. + */ +export interface OntologyBindingChange { + /** + * Full IRI of the class the table is bound to. + */ + classIri: string; + columns?: ColumnBinding[]; + role?: Role; + /** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + */ + rowFilter?: RowFilter; + /** + * Present exactly when the binding has a role. + */ + subjectKey?: Array; + /** + * The table that holds records of the class. + */ + tableId: string; +} + +/** + * One property bound to one column of the table. + */ +export interface ColumnBinding { + columnPath: string[]; + /** + * Required when the property is an OBJECT property, and not allowed otherwise. + */ + join?: Join; + /** + * Full IRI of a DATA or OBJECT property of the ontology. + */ + propertyIri: string; +} + +/** + * Required when the property is an OBJECT property, and not allowed otherwise. + * + * How a column bound to an OBJECT property reaches the table that holds the related + * records. It carries no status. A join that a change set writes is stored as `inferred`, + * and only a write through the bindings API confirms one. + */ +export interface Join { + on: JoinColumnPair[]; + /** + * The table that holds the related records. It sits in the same database as the bound table. + */ + targetAssetId: string; +} + +/** + * One equality of a join. `child` is a column of the bound table and `parent` is a column + * of the target table. + */ +export interface JoinColumnPair { + child: string[]; + parent: string[]; +} + +/** + * How a bound table takes part in the records of its class. An `identity` table defines the + * records, and a class has at most one. A `contributing` table adds columns or relations to + * records the identity table defines. A binding without a role is unassigned. + */ +export enum Role { + Contributing = "contributing", + Identity = "identity", +} + +/** + * Applying an operation that sets or changes it also requires ViewSampleData on the table. + * + * One comparison on one column of the bound table that says which rows belong to the class. + * A write that sets or changes it parses each value as the data type of the column and + * refuses a value that does not parse. The value is stored as written. + */ +export interface RowFilter { + column: string[]; + operator: RowFilterOperator; + /** + * The value the column is compared with. A string of at most 1024 characters, a number or a + * boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent + * for `isNull` and `isNotNull`. + */ + value?: any; +} + +/** + * The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, + * `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one + * value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value. + */ +export enum RowFilterOperator { + Equals = "equals", + GreaterThan = "greaterThan", + GreaterThanOrEquals = "greaterThanOrEquals", + In = "in", + IsNotNull = "isNotNull", + IsNull = "isNull", + LessThan = "lessThan", + LessThanOrEquals = "lessThanOrEquals", + NotEquals = "notEquals", +} + +/** + * A formal class, SKOS concept, or both, owned by an ontology independently of glossary + * terms. + */ +export interface OntologyConcept { + /** + * An abstract class has no direct instances; data is classified by its subclasses. + */ + abstract?: boolean; + changeDescription?: ChangeDescription; + conceptMappings?: ConceptMapping[]; + conceptType: OntologyConceptType; + /** + * IRI of the document or standard this definition is taken from. + */ + definitionSource?: string; + deleted?: boolean; + /** + * A deprecated definition stays resolvable for existing references but should not be used + * for new ones. + */ + deprecated?: boolean; + description?: string; + displayName?: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + /** + * Persisted semantic IRI. Renaming the catalog entity must preserve this identity. + */ + iri: string; + /** + * Release review state of this concept, derived by the server from ontology releases. Not + * stored or independently editable. + */ + lifecycleStatus?: OntologyDefinitionStatus; + name: string; + /** + * Owning ontology entity. Glossaries do not own ontology definitions. + */ + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + /** + * IRI of the concept in the same ontology that replaces this one. + */ + replacedBy?: string; + /** + * Direct named subclasses, derived from non-deleted ontology-owned SUBCLASS_OF axioms. Not + * stored or independently editable. + */ + subClasses?: string[]; + /** + * Direct named superclasses, derived from non-deleted ontology-owned SUBCLASS_OF axioms. + * Not stored or independently editable. + */ + superClasses?: string[]; + synonyms?: string[]; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * Mapping from an ontology term to an external concept. + */ +export interface ConceptMapping { + /** + * External concept IRI to map this ontology term to. + */ + conceptIri: string; + /** + * Type of mapping used for the external concept alignment. + */ + mappingType: ConceptMappingType; + /** + * Optional external concept scheme IRI for the mapped concept. + */ + schemeIri?: string; + /** + * Optional source label or catalog for the external concept. + */ + source?: string; +} + +/** + * Type of mapping used for the external concept alignment. + * + * Type of mapping used to align this term with an external concept. + */ +export enum ConceptMappingType { + BroadMatch = "BROAD_MATCH", + CloseMatch = "CLOSE_MATCH", + ExactMatch = "EXACT_MATCH", + NarrowMatch = "NARROW_MATCH", + RelatedMatch = "RELATED_MATCH", + SameAs = "SAME_AS", +} + +/** + * Vocabulary a source ontology used to assert a concept. Preserved so imported ontologies + * round-trip with the typing they were authored with. + */ +export enum OntologyConceptType { + Both = "BOTH", + OwlClass = "OWL_CLASS", + SkosConcept = "SKOS_CONCEPT", +} + +/** + * Release review state of this concept, derived by the server from ontology releases. Not + * stored or independently editable. + * + * Release review state of an ontology definition. The server derives it from ontology + * releases, and clients cannot set it. + */ +export enum OntologyDefinitionStatus { + Approved = "Approved", + Draft = "Draft", + InReview = "InReview", +} + +/** + * One piece of catalog metadata that supports a change set operation: a table and, when the + * support is narrower, some of its columns. A caller of the change set API reads and writes + * only the entries whose table that caller may view. + */ +export interface OntologyChangeEvidence { + /** + * The columns of that table the evidence is about. Absent when it is about the table as a + * whole. + */ + columns?: Array; + kind: EvidenceKind; + /** + * The table the evidence is about. + */ + tableId: string; +} + +/** + * The closed set of metadata that can support an operation. `declaredKey` is a key + * constraint declared on the table. `storedJoinCount` is a join count that the catalog + * stores for the columns. `testCase` is a data quality test on the table or its columns. + * `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile + * of the table or its columns. `name` is the name of the table or of its columns. + * `sampleData` is values seen in the sample rows that the catalog stores for the table. + * `measured` is a count or a rate computed by running a query against the source table, + * such as the distinct and null counts of a key column, or the share of the values of a + * join column that find a match in the target column. + */ +export enum EvidenceKind { + DeclaredKey = "declaredKey", + Lineage = "lineage", + Measured = "measured", + Name = "name", + Profile = "profile", + SampleData = "sampleData", + StoredJoinCount = "storedJoinCount", + TestCase = "testCase", +} + +/** + * This schema defines the Glossary entity. A Glossary is collection of hierarchical + * GlossaryTerms. + */ +export interface Glossary { + /** + * Change that lead to this version of the entity. + */ + changeDescription?: ChangeDescription; + /** + * Reference to the data contract for this entity. + */ + dataContract?: EntityReference; + /** + * List of data products this entity is part of. + */ + dataProducts?: EntityReference[]; + /** + * When `true` indicates the entity has been soft deleted. + */ + deleted?: boolean; + /** + * Description of the glossary. + */ + description: string; + /** + * System glossary can't be deleted. Use this flag to disable them. + */ + disabled?: boolean; + /** + * Display Name that identifies this glossary. + */ + displayName?: string; + /** + * Domains the Glossary belongs to. + */ + domains?: EntityReference[]; + /** + * Status of the Glossary. + */ + entityStatus?: EntityStatus; + /** + * Entity extension data with custom attributes added to the entity. + */ + extension?: any; + /** + * FullyQualifiedName same as name. + */ + fullyQualifiedName?: string; + /** + * Link to the resource corresponding to this entity. + */ + href?: string; + /** + * Unique identifier of a glossary instance. + */ + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + /** + * Change that lead to this version of the entity. + */ + incrementalChangeDescription?: ChangeDescription; + /** + * Glossary terms that are direct children in this glossary are mutually exclusive. When + * mutually exclusive is `true` only one term can be used to label an entity. When mutually + * exclusive is `false`, multiple terms from this group can be used to label an entity. + */ + mutuallyExclusive?: boolean; + /** + * Name of the glossary + */ + name: string; + /** + * Namespace prefix to IRI mappings for terms imported from an external ontology. Used to + * render CURIEs and preserve identity when re-exporting the glossary as RDF/OWL. + */ + namespaces?: Namespace[]; + /** + * Owners of this glossary. + */ + owners?: EntityReference[]; + provider?: ProviderType; + /** + * User references of the reviewers for this glossary. + */ + reviewers?: EntityReference[]; + /** + * Tags for this glossary. + */ + tags?: TagLabel[]; + /** + * Total number of terms in the glossary. This includes all the children in the hierarchy. + */ + termCount?: number; + /** + * Last update time corresponding to the new version of the entity in Unix epoch time + * milliseconds. + */ + updatedAt?: number; + /** + * User who made the update. + */ + updatedBy?: string; + /** + * Count of how many times terms from this glossary are used. + */ + usageCount?: number; + /** + * Metadata version of the entity. + */ + version?: number; + /** + * Votes on the entity. + */ + votes?: Votes; +} + +/** + * Status of the Glossary. + * + * General lifecycle stage for entities that reference this vocabulary. Specialized entities + * can declare their own status schema and lifecycle policy. Entity types without an + * entityStatus property have no lifecycle. When a create request omits the stage, the + * server assigns the entity type's initial stage. + * + * Approval status of the glossary term. + * + * Approval status of this relation edge. + */ +export enum EntityStatus { + Approved = "Approved", + Archived = "Archived", + Deprecated = "Deprecated", + Draft = "Draft", + InReview = "In Review", + Rejected = "Rejected", + Unprocessed = "Unprocessed", +} + +export interface Namespace { + /** + * Full namespace IRI the prefix expands to (e.g., `http://example.com/ontology/hcp#`). + */ + namespace?: string; + /** + * Short prefix for the namespace (e.g., `hcp`). + */ + prefix?: string; +} + +/** + * This schema defines the type for labeling an entity with a Tag. + */ +export interface TagLabel { + /** + * Timestamp when this tag was applied in ISO 8601 format + */ + appliedAt?: Date; + /** + * Who it is that applied this tag (e.g: a bot, AI or a human) + */ + appliedBy?: string; + /** + * Description for the tag label. + */ + description?: string; + /** + * Display Name that identifies this tag. + */ + displayName?: string; + /** + * Link to the tag resource. + */ + href?: string; + /** + * Label type describes how a tag label was applied. 'Manual' indicates the tag label was + * applied by a person. 'Derived' indicates a tag label was derived using the associated tag + * relationship (see Classification.json for more details). 'Propagated` indicates a tag + * label was propagated from upstream based on lineage. 'Automated' is used when a tool was + * used to determine the tag label. + */ + labelType: LabelType; + /** + * Additional metadata associated with this tag label, such as recognizer information for + * automatically applied tags. + */ + metadata?: TagLabelMetadata; + /** + * Name of the tag or glossary term. + */ + name?: string; + /** + * An explanation of why this tag was proposed, specially for autoclassification tags + */ + reason?: string; + /** + * Label is from Tags or Glossary. + */ + source: TagSource; + /** + * 'Suggested' state is used when a tag label is suggested by users or tools. Owner of the + * entity must confirm the suggested labels before it is marked as 'Confirmed'. + */ + state: TagState; + style?: Style; + tagFQN: string; +} + +/** + * Label type describes how a tag label was applied. 'Manual' indicates the tag label was + * applied by a person. 'Derived' indicates a tag label was derived using the associated tag + * relationship (see Classification.json for more details). 'Propagated` indicates a tag + * label was propagated from upstream based on lineage. 'Automated' is used when a tool was + * used to determine the tag label. + */ +export enum LabelType { + Automated = "Automated", + Derived = "Derived", + Generated = "Generated", + Manual = "Manual", + Propagated = "Propagated", +} + +/** + * Additional metadata associated with this tag label, such as recognizer information for + * automatically applied tags. + * + * Additional metadata associated with a tag label, including information about how the tag + * was applied. + */ +export interface TagLabelMetadata { + /** + * Epoch time in milliseconds when the certification tag expires + */ + expiryDate?: number; + /** + * Metadata about the recognizer that automatically applied this tag + */ + recognizer?: TagLabelRecognizerMetadata; +} + +/** + * Metadata about the recognizer that automatically applied this tag + * + * Metadata about the recognizer that applied a tag, including scoring and pattern + * information. + */ +export interface TagLabelRecognizerMetadata { + /** + * Details of patterns that matched during recognition + */ + patterns?: PatternMatch[]; + /** + * Unique identifier of the recognizer that applied this tag + */ + recognizerId: string; + /** + * Human-readable name of the recognizer + */ + recognizerName: string; + /** + * Confidence score assigned by the recognizer (0.0 to 1.0) + */ + score: number; + /** + * What the recognizer analyzed to apply this tag + */ + target?: Target; +} + +/** + * Information about a pattern that matched during recognition + */ +export interface PatternMatch { + /** + * Name of the pattern that matched + */ + name: string; + /** + * Regular expression or pattern definition + */ + regex?: string; + /** + * Confidence score for this specific pattern match + */ + score: number; +} + +/** + * What the recognizer analyzed to apply this tag + */ +export enum Target { + ColumnName = "column_name", + Content = "content", +} + +/** + * Label is from Tags or Glossary. + */ +export enum TagSource { + Classification = "Classification", + Glossary = "Glossary", +} + +/** + * 'Suggested' state is used when a tag label is suggested by users or tools. Owner of the + * entity must confirm the suggested labels before it is marked as 'Confirmed'. + */ +export enum TagState { + Confirmed = "Confirmed", + Suggested = "Suggested", +} + +/** + * UI Style is used to associate a color code and/or icon to entity to customize the look of + * that entity in UI. + */ +export interface Style { + /** + * Hex Color Code to mark an entity such as GlossaryTerm, Tag, Domain or Data Product. + */ + color?: string; + /** + * Cover image configuration for the entity. + */ + coverImage?: CoverImage; + /** + * An icon to associate with GlossaryTerm, Tag, Domain or Data Product. + */ + iconURL?: string; +} + +/** + * Cover image configuration for the entity. + * + * Cover image configuration for an entity. This is used to display a banner or header image + * for entities like Domain, Glossary, Data Product, etc. + */ +export interface CoverImage { + /** + * Position of the cover image in CSS background-position format. Supports keywords (top, + * center, bottom) or pixel values (e.g., '20px 30px'). + */ + position?: string; + /** + * URL of the cover image. + */ + url?: string; +} + +/** + * Votes on the entity. + * + * This schema defines the Votes for a Data Asset. + */ +export interface Votes { + /** + * List of all the Users who downVoted + */ + downVoters?: EntityReference[]; + /** + * Total down-votes the entity has + */ + downVotes?: number; + /** + * List of all the Users who upVoted + */ + upVoters?: EntityReference[]; + /** + * Total up-votes the entity has + */ + upVotes?: number; +} + +export enum OperationType { + AddRelationship = "ADD_RELATIONSHIP", + CreateGlossary = "CREATE_GLOSSARY", + CreateTerm = "CREATE_TERM", + DeleteAxiom = "DELETE_AXIOM", + DeleteConcept = "DELETE_CONCEPT", + DeleteMapping = "DELETE_MAPPING", + DeleteProperty = "DELETE_PROPERTY", + DeleteRelationship = "DELETE_RELATIONSHIP", + DeleteTerm = "DELETE_TERM", + UpdateRelationship = "UPDATE_RELATIONSHIP", + UpdateTerm = "UPDATE_TERM", + UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", + UpsertConcept = "UPSERT_CONCEPT", + UpsertMapping = "UPSERT_MAPPING", + UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", +} + +/** + * A formal object, data, or annotation property owned by an ontology, independent of + * glossary relation types. + */ +export interface OntologyProperty { + changeDescription?: ChangeDescription; + characteristics?: Characteristic[]; + deleted?: boolean; + /** + * A deprecated definition stays resolvable for existing references but should not be used + * for new ones. + */ + deprecated?: boolean; + description?: string; + /** + * Semantic IRIs of properties disjoint with this property. + */ + disjointWith?: string[]; + displayName?: string; + /** + * Semantic IRIs of the classes in the property domain. + */ + domain?: string[]; + /** + * Allowed typed values for a DATA property, projected as an OWL data enumeration. An absent + * datatype denotes xsd:string. Empty means no enumeration constraint; an enumeration needs + * at least two allowed values. + */ + enumValues?: Literal[]; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + /** + * Semantic IRI of the inverse object property. + */ + inverse?: string; + /** + * Persisted semantic IRI. Renaming the catalog entity must preserve this identity. + */ + iri: string; + /** + * Marks a DATA property as the one whose value names its class's instances. This annotation + * does not assert functionality or uniqueness. A class has at most one such property, and + * the field is absent when unset. + */ + isDisplayName?: boolean; + /** + * Identifier intent for a DATA property. This annotation does not assert functionality, an + * OWL key, or uniqueness in source data. + */ + isIdentifier?: boolean; + kind: PropertyKind; + name: string; + /** + * Owning ontology entity. Glossaries do not own ontology definitions. + */ + ontology: EntityReference; + owners?: EntityReference[]; + /** + * Ordered object-property IRIs whose composition implies this property. + */ + propertyChain?: string[]; + provider?: ProviderType; + /** + * Semantic IRIs of range classes or datatypes. + */ + range?: string[]; + /** + * IRI of the property in the same ontology that replaces this one. + */ + replacedBy?: string; + /** + * Semantic IRIs of the named properties this property specializes (rdfs:subPropertyOf). + * Each must be a declared property of the same kind; a property cannot name itself, and the + * links cannot form a cycle. + */ + superProperties?: string[]; + /** + * Unit IRI or display symbol for a DATA property, retained as an annotation without + * implying conversion. + */ + unit?: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +export enum Characteristic { + Asymmetric = "ASYMMETRIC", + Functional = "FUNCTIONAL", + InverseFunctional = "INVERSE_FUNCTIONAL", + Irreflexive = "IRREFLEXIVE", + Reflexive = "REFLEXIVE", + Symmetric = "SYMMETRIC", + Transitive = "TRANSITIVE", +} + +export enum PropertyKind { + Annotation = "ANNOTATION", + Data = "DATA", + Object = "OBJECT", +} + +/** + * A stable, directed semantic relationship between two glossary terms. + */ +export interface OntologyRelationship { + createdAt: number; + /** + * User who first authored or imported the relationship. + */ + createdBy: string; + fromTerm: EntityReference; + id: string; + provenance: Provenance; + relationshipType: EntityReference; + status: EntityStatus; + toTerm: EntityReference; +} + +/** + * The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI. + * + * A SHACL node shape that targets one class of an ontology and lists constraints on the + * properties of its instances. + */ +export interface OntologyShape { + changeDescription?: ChangeDescription; + /** + * Constraints on the properties of the target class, in authored order. + */ + constraints: OntologyShapeConstraint[]; + deleted?: boolean; + description: string; + displayName: string; + fullyQualifiedName: string; + href?: string; + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + incrementalChangeDescription?: ChangeDescription; + name: string; + ontology: EntityReference; + owners?: EntityReference[]; + provider?: ProviderType; + severity: Severity; + /** + * Full IRI of the class the shape applies to. + */ + targetConcept: string; + updatedAt?: number; + updatedBy?: string; + version?: number; +} + +/** + * One constraint of an ontology shape: the values a property may take on instances of the + * shape's target class. + */ +export interface OntologyShapeConstraint { + /** + * Every value must be an instance of this class. + */ + classIri?: string; + /** + * Every value must be a literal of this datatype. + */ + datatypeIri?: string; + /** + * Identity of the constraint inside its shape. It stays the same when the constraint is + * edited. + */ + id: string; + /** + * Every value must be one of these nodes. + */ + in?: Value[]; + maxCount?: number; + maxInclusive?: Literal; + minCount?: number; + minInclusive?: Literal; + /** + * Full IRI of the ontology property the constraint applies to. + */ + path: string; + /** + * Every value's lexical form must match this regular expression. + */ + pattern?: string; +} + +/** + * A node a constraint accepts: an IRI or a literal, never both. + */ +export interface Value { + iri?: string; + literal?: Literal; +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + +export enum CandidateState { + Active = "ACTIVE", + Undone = "UNDONE", +} + +/** + * This schema defines te Glossary term entities. + */ +export interface GlossaryTerm { + /** + * Change that lead to this version of the entity. + */ + changeDescription?: ChangeDescription; + /** + * Other glossary terms that are children of this glossary term. + */ + children?: EntityReference[]; + /** + * Count of immediate children glossary terms. + */ + childrenCount?: number; + /** + * Optional mappings to external concepts (e.g., SKOS alignments). + */ + conceptMappings?: ConceptMapping[]; + /** + * Reference to the data contract for this entity. + */ + dataContract?: EntityReference; + /** + * List of data products this entity is part of. + */ + dataProducts?: EntityReference[]; + /** + * When `true` indicates the entity has been soft deleted. + */ + deleted?: boolean; + /** + * Description of the glossary term. + */ + description: string; + /** + * System glossary can't be deleted. Use this flag to disable them. + */ + disabled?: boolean; + /** + * Display Name that identifies this glossary. + */ + displayName?: string; + /** + * Domains the Glossary Term belongs to. When not set, the Glossary TErm inherits the domain + * from the Glossary it belongs to. + */ + domains?: EntityReference[]; + /** + * Approval status of the glossary term. + */ + entityStatus?: EntityStatus; + /** + * Entity extension data with custom attributes added to the entity. + */ + extension?: any; + /** + * A unique name that identifies a glossary term. It captures name hierarchy of glossary of + * terms in the form of `glossaryName.parentTerm.childTerm`. + */ + fullyQualifiedName?: string; + /** + * Glossary that this term belongs to. + */ + glossary: EntityReference; + /** + * Link to the resource corresponding to this entity. + */ + href?: string; + /** + * Unique identifier of a glossary term instance. + */ + id: string; + /** + * Bot user that performed the action on behalf of the actual user. + */ + impersonatedBy?: string; + /** + * Change that lead to this version of the entity. + */ + incrementalChangeDescription?: ChangeDescription; + /** + * Canonical IRI of this term in its source ontology (e.g., + * `http://example.com/ontology/hcp#HealthcareProvider`). Preserves identity across ontology + * import/export round-trips and is used as the RDF subject when present. Empty for terms + * not sourced from an external ontology. + */ + iri?: string; + /** + * Glossary terms that are children of this term are mutually exclusive. When mutually + * exclusive is `true` only one term can be used to label an entity from this group. When + * mutually exclusive is `false`, multiple terms from this group can be used to label an + * entity. + */ + mutuallyExclusive?: boolean; + /** + * Preferred name for the glossary term. + */ + name: string; + /** + * Owners of this glossary term. + */ + owners?: EntityReference[]; + /** + * Parent glossary term that this term is child of. When `null` this term is the root term + * of the glossary. + */ + parent?: EntityReference; + provider?: ProviderType; + /** + * Link to a reference from an external glossary. + */ + references?: TermReference[]; + /** + * Other glossary terms that are related to this glossary term with typed semantic relations. + */ + relatedTerms?: TermRelation[]; + /** + * User names of the reviewers for this glossary. + */ + reviewers?: EntityReference[]; + style?: Style; + /** + * Alternate names that are synonyms or near-synonyms for the glossary term. + */ + synonyms?: string[]; + /** + * Tags associated with this glossary term. These tags captures relationship of a glossary + * term with a tag automatically. As an example a glossary term 'User.PhoneNumber' might + * have an associated tag 'PII.Sensitive'. When 'User.Address' is used to label a column in + * a table, 'PII.Sensitive' label is also applied automatically due to Associated tag + * relationship. + */ + tags?: TagLabel[]; + /** + * Last update time corresponding to the new version of the entity in Unix epoch time + * milliseconds. + */ + updatedAt?: number; + /** + * User who made the update. + */ + updatedBy?: string; + /** + * Count of how many times this and it's children glossary terms are used as labels. + */ + usageCount?: number; + /** + * Metadata version of the entity. + */ + version?: number; + /** + * Votes on the entity. + */ + votes?: Votes; +} + +export interface TermReference { + /** + * Name that identifies the source of an external glossary term. Example `HealthCare.gov`. + */ + endpoint?: string; + /** + * Name that identifies the source of an external glossary term. Example `HealthCare.gov`. + */ + name?: string; +} + +/** + * This schema defines the TermRelation type used for establishing typed semantic + * relationships between glossary terms. + */ +export interface TermRelation { + /** + * Time the relationship was first persisted. + */ + createdAt?: number; + /** + * User who first authored or imported the relationship. + */ + createdBy?: string; + /** + * Unique identifier of this relation edge. + */ + id?: string; + /** + * How this relation edge originated. Defaults to 'Manual'. + */ + provenance?: Provenance; + /** + * Resolved first-class relationship type. + */ + relationshipType?: EntityReference; + /** + * Type of the relation (e.g., 'broader', 'narrower', 'synonym', 'relatedTo'). Defaults to + * 'relatedTo' for backward compatibility. + */ + relationType?: string; + /** + * Approval status of this relation edge. + */ + status?: EntityStatus; + /** + * Reference to the related glossary term. + */ + term: EntityReference; +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinition.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinition.ts new file mode 100644 index 000000000000..a1e209a841ba --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinition.ts @@ -0,0 +1,61 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A definition that a person declined to add to an ontology. The record is keyed by the + * operation type, the definition's IRI and the digest of its content, so a definition that + * changes is no longer declined. + */ +export interface OntologyDeclinedDefinition { + /** + * The change set the declined operation came from. + */ + changeSetId: string; + declinedAt: number; + declinedBy: string; + /** + * The definition's IRI. An axiom has none of its own, so it carries its subject IRI. + */ + iri: string; + ontologyId: string; + /** + * The declined operation's id in that change set. + */ + operationId: string; + operationType: OperationType; + /** + * Lower-case hexadecimal SHA-256 of the definition's canonical JSON, without id, version, + * updatedAt, updatedBy, href and changeDescription. Only the server computes it. + */ + payloadDigest: string; + reason?: string; +} + +export enum OperationType { + AddRelationship = "ADD_RELATIONSHIP", + CreateGlossary = "CREATE_GLOSSARY", + CreateTerm = "CREATE_TERM", + DeleteAxiom = "DELETE_AXIOM", + DeleteConcept = "DELETE_CONCEPT", + DeleteMapping = "DELETE_MAPPING", + DeleteProperty = "DELETE_PROPERTY", + DeleteRelationship = "DELETE_RELATIONSHIP", + DeleteTerm = "DELETE_TERM", + UpdateRelationship = "UPDATE_RELATIONSHIP", + UpdateTerm = "UPDATE_TERM", + UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", + UpsertConcept = "UPSERT_CONCEPT", + UpsertMapping = "UPSERT_MAPPING", + UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinitionMatches.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinitionMatches.ts new file mode 100644 index 000000000000..68748035867e --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinitionMatches.ts @@ -0,0 +1,90 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * For each candidate operation, whether a declined definition matches its type, IRI and + * content digest. Results come in the order of the candidates. + */ +export interface OntologyDeclinedDefinitionMatches { + matches: Match[]; +} + +export interface Match { + declined: boolean; + /** + * Absent for an operation that carries no definition. + */ + iri?: string; + operationId: string; + operationType: OperationType; + /** + * The digest the server computed for the candidate. Absent for an operation that carries no + * definition. + */ + payloadDigest?: string; + /** + * The matching record, present exactly when declined is true. + */ + record?: OntologyDeclinedDefinition; +} + +export enum OperationType { + AddRelationship = "ADD_RELATIONSHIP", + CreateGlossary = "CREATE_GLOSSARY", + CreateTerm = "CREATE_TERM", + DeleteAxiom = "DELETE_AXIOM", + DeleteConcept = "DELETE_CONCEPT", + DeleteMapping = "DELETE_MAPPING", + DeleteProperty = "DELETE_PROPERTY", + DeleteRelationship = "DELETE_RELATIONSHIP", + DeleteTerm = "DELETE_TERM", + UpdateRelationship = "UPDATE_RELATIONSHIP", + UpdateTerm = "UPDATE_TERM", + UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", + UpsertConcept = "UPSERT_CONCEPT", + UpsertMapping = "UPSERT_MAPPING", + UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", +} + +/** + * The matching record, present exactly when declined is true. + * + * A definition that a person declined to add to an ontology. The record is keyed by the + * operation type, the definition's IRI and the digest of its content, so a definition that + * changes is no longer declined. + */ +export interface OntologyDeclinedDefinition { + /** + * The change set the declined operation came from. + */ + changeSetId: string; + declinedAt: number; + declinedBy: string; + /** + * The definition's IRI. An axiom has none of its own, so it carries its subject IRI. + */ + iri: string; + ontologyId: string; + /** + * The declined operation's id in that change set. + */ + operationId: string; + operationType: OperationType; + /** + * Lower-case hexadecimal SHA-256 of the definition's canonical JSON, without id, version, + * updatedAt, updatedBy, href and changeDescription. Only the server computes it. + */ + payloadDigest: string; + reason?: string; +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinitionPage.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinitionPage.ts new file mode 100644 index 000000000000..461fa59d36a6 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/ontologyDeclinedDefinitionPage.ts @@ -0,0 +1,72 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * One page of an ontology's declined definitions, oldest decision first. + */ +export interface OntologyDeclinedDefinitionPage { + /** + * Cursor for the next page. Absent on the last page. + */ + after?: string; + records: OntologyDeclinedDefinition[]; +} + +/** + * A definition that a person declined to add to an ontology. The record is keyed by the + * operation type, the definition's IRI and the digest of its content, so a definition that + * changes is no longer declined. + */ +export interface OntologyDeclinedDefinition { + /** + * The change set the declined operation came from. + */ + changeSetId: string; + declinedAt: number; + declinedBy: string; + /** + * The definition's IRI. An axiom has none of its own, so it carries its subject IRI. + */ + iri: string; + ontologyId: string; + /** + * The declined operation's id in that change set. + */ + operationId: string; + operationType: OperationType; + /** + * Lower-case hexadecimal SHA-256 of the definition's canonical JSON, without id, version, + * updatedAt, updatedBy, href and changeDescription. Only the server computes it. + */ + payloadDigest: string; + reason?: string; +} + +export enum OperationType { + AddRelationship = "ADD_RELATIONSHIP", + CreateGlossary = "CREATE_GLOSSARY", + CreateTerm = "CREATE_TERM", + DeleteAxiom = "DELETE_AXIOM", + DeleteConcept = "DELETE_CONCEPT", + DeleteMapping = "DELETE_MAPPING", + DeleteProperty = "DELETE_PROPERTY", + DeleteRelationship = "DELETE_RELATIONSHIP", + DeleteTerm = "DELETE_TERM", + UpdateRelationship = "UPDATE_RELATIONSHIP", + UpdateTerm = "UPDATE_TERM", + UpsertAxiom = "UPSERT_AXIOM", + UpsertBinding = "UPSERT_BINDING", + UpsertConcept = "UPSERT_CONCEPT", + UpsertMapping = "UPSERT_MAPPING", + UpsertProperty = "UPSERT_PROPERTY", + UpsertShape = "UPSERT_SHAPE", +} From 90847fca410133727ead512ed92414d339d1d734 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 13:31:15 -0800 Subject: [PATCH 119/203] Add a table constraint only for a suggestion task, pin the exact comparison of the suggestion type, and give four tests a positive control --- ...stion-task-can-carry-a-table-constraint.md | 8 +- .../TaskTableConstraintSuggestionIT.java | 113 ++++++++++++++++++ .../service/tasks/TaskWorkflowHandler.java | 3 +- .../tasks/TableConstraintSuggestionTest.java | 80 +++++++++++-- 4 files changed, 189 insertions(+), 15 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index 53a622806ed1..b814a09d1163 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,9 +1,9 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact) - **Deciders:** OpenMetadata maintainers -- **Guard:** `TableConstraintSuggestionTest` (the type check on a resolution, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply), `SuggestionTypeRoutingTest`, `TaskTableConstraintSuggestionIT` +- **Guard:** `TableConstraintSuggestionTest` (the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply), `SuggestionTypeRoutingTest`, `TaskTableConstraintSuggestionIT` - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type ## Context @@ -43,6 +43,10 @@ declined. constraints with the new one added, so a constraint set the write would refuse (for example a foreign key to a table that was deleted) is refused with a 400 while the task is still open and can still be rejected. +- Only a task of type `Suggestion` adds a table constraint. A task of another type whose payload + names one is handled as before this change and adds nothing, whatever form it is bound to. +- The suggestion type is compared exactly. A resolution that spells `TableConstraint` with another + case or with a space around it is refused like any other change of type. - Rejecting leaves the table unchanged and the task `Rejected`. - A client finds the suggestions already made for a table, and the ones declined, by listing the tasks about that table with type `Suggestion` and a status, and reading `payload.suggestionType` diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 1ca13bf1a926..5aaad4c3f234 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -32,6 +32,7 @@ import org.openmetadata.it.factories.DatabaseSchemaTestFactory; import org.openmetadata.it.factories.DatabaseServiceTestFactory; import org.openmetadata.it.factories.TableTestFactory; +import org.openmetadata.it.factories.UserTestFactory; import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; @@ -39,8 +40,12 @@ import org.openmetadata.schema.api.tasks.ResolveTask; import org.openmetadata.schema.entity.data.DatabaseSchema; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.feed.FormSchema; +import org.openmetadata.schema.entity.feed.TaskFormSchema; +import org.openmetadata.schema.entity.feed.UiSchema; import org.openmetadata.schema.entity.services.DatabaseService; import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.schema.type.TableConstraint.RelationshipType; @@ -398,6 +403,114 @@ private static String descriptionOf(Table table) { .getDescription(); } + /** + * A form that applies suggestions to a custom task, and lets a user who may only edit descriptions + * resolve it, gives that user no way to add a table constraint. The form is bound to custom tasks + * of the Review category, which no other test files, so it cannot change another test's task. + */ + @Test + void aCustomTaskCarryingAConstraintPayloadAddsNoConstraintForAUserWhoMayOnlyEditDescriptions( + TestNamespace ns) { + User editor = UserTestFactory.createUser(ns, "constraint_editor"); + OpenMetadataClient editorClient = + SdkClients.createClient(editor.getName(), editor.getEmail(), new String[] {}); + String assignee = editor.getFullyQualifiedName(); + Table filed = adminTable(ns, "customfiled"); + Table switched = adminTable(ns, "customswitched"); + TaskFormSchema form = createSuggestionForm(ns); + try { + Task constraintTask = + fileCustom( + ns, + filed, + "filed", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.SORT_KEY, "id"))), + assignee); + Task descriptionTask = + fileCustom( + ns, + switched, + "switched", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "a description"), + assignee); + String filedUpdatedBy = updatedByOf(filed); + String switchedUpdatedBy = updatedByOf(switched); + + Task approvedConstraint = + editorClient + .tasks() + .resolve( + constraintTask.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + Task approvedSwitch = + resolve( + editorClient, + descriptionTask, + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name")))); + + assertEquals(TaskEntityStatus.Approved, approvedConstraint.getStatus()); + assertEquals( + TaskEntityStatus.Approved, + SdkClients.adminClient().tasks().get(constraintTask.getId().toString()).getStatus()); + assertEquals(List.of(), constraintsOf(filed)); + assertEquals(filedUpdatedBy, updatedByOf(filed)); + assertEquals(TaskEntityStatus.Approved, approvedSwitch.getStatus()); + assertEquals( + TaskEntityStatus.Approved, + SdkClients.adminClient().tasks().get(descriptionTask.getId().toString()).getStatus()); + assertEquals(List.of(), constraintsOf(switched)); + assertEquals(switchedUpdatedBy, updatedByOf(switched)); + } finally { + SdkClients.adminClient() + .taskFormSchemas() + .delete(form.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + } + } + + private static TaskFormSchema createSuggestionForm(TestNamespace ns) { + return SdkClients.adminClient() + .taskFormSchemas() + .create( + new TaskFormSchema() + .withId(UUID.randomUUID()) + .withName(ns.prefix("suggestion-form")) + .withTaskType(TaskEntityType.CustomTask.value()) + .withTaskCategory(TaskCategory.Review.value()) + .withFormSchema( + new FormSchema() + .withAdditionalProperty("type", "object") + .withAdditionalProperty("properties", Map.of())) + .withUiSchema( + new UiSchema() + .withAdditionalProperty( + "ui:handler", + Map.of("type", "suggestion", "permission", "EditDescription")))); + } + + private static Task fileCustom( + TestNamespace ns, Table table, String label, Map payload, String assignee) { + return SdkClients.adminClient() + .tasks() + .create( + new CreateTask() + .withName(ns.prefix("custom-" + label)) + .withCategory(TaskCategory.Review) + .withType(TaskEntityType.CustomTask) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload(payload) + .withAssignees(List.of(assignee))); + } + + private static String updatedByOf(Table table) { + return SdkClients.adminClient() + .tables() + .getByName(table.getFullyQualifiedName(), TABLE_FIELDS) + .getUpdatedBy(); + } + private static void assertStillOpen(Task task) { assertEquals( TaskEntityStatus.Open, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 63d142b38154..baa223a7e4ce 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -1388,7 +1388,8 @@ private void applySuggestion( tags.size(), entity.getName()); } - } else if (TableConstraintSuggestion.TYPE.equals(suggestionType)) { + } else if (TableConstraintSuggestion.isTableConstraint(task) + && TableConstraintSuggestion.TYPE.equals(suggestionType)) { applyTableConstraint(payloadNode, entity, repository, user); } else { LOG.debug("[TaskWorkflowHandler] Unknown suggestion type: {}", suggestionType); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java index 1259e555dfa4..a22fc853acba 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -37,6 +37,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.openmetadata.schema.EntityInterface; @@ -48,7 +51,6 @@ import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.schema.type.TableConstraint.RelationshipType; -import org.openmetadata.schema.type.TaskEntityStatus; import org.openmetadata.schema.type.TaskEntityType; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -332,13 +334,12 @@ void aUniqueConstraintWithReferredColumns_isRefused() { } @Test - void aFailureWhileApplying_escapesAndLeavesTheTaskOpen() throws Exception { + void aFailureWhileApplying_escapesWithItsCause() throws Exception { EntityRepository repository = mock(EntityRepository.class); doThrow(new IllegalStateException("write failed")) .when(repository) .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); - task.setStatus(TaskEntityStatus.Open); java.lang.reflect.InvocationTargetException thrown = assertThrows( @@ -346,24 +347,35 @@ void aFailureWhileApplying_escapesAndLeavesTheTaskOpen() throws Exception { () -> invokeApplySuggestion(task, orders, repository, "approver")); assertEquals("write failed", thrown.getCause().getMessage()); - assertEquals(TaskEntityStatus.Open, task.getStatus()); } - @Test - void aTaskOfAnotherTypeCarryingAConstraintPayload_getsNoCheckAndNoRethrow() throws Exception { - Task task = taskWithValue("not json at all").withType(TaskEntityType.DescriptionUpdate); + @ParameterizedTest + @EnumSource( + value = TaskEntityType.class, + names = {"CustomTask", "DescriptionUpdate"}) + void aTaskOfAnotherTypeCarryingAConstraintPayload_getsNoCheckNoWriteAndNoRethrow( + TaskEntityType otherType) throws Exception { + Task unchecked = taskWithValue("not json at all").withType(otherType); EntityRepository repository = mock(EntityRepository.class); doThrow(new IllegalStateException("write failed")) .when(repository) .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); Task applied = - task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))) - .withType(TaskEntityType.DescriptionUpdate); + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))).withType(otherType); - assertEquals(false, TableConstraintSuggestion.isTableConstraint(task)); - assertDoesNotThrow(() -> TableConstraintSuggestion.require(task)); - assertDoesNotThrow(() -> TableConstraintSuggestion.requireToApply(task, null, null)); + assertEquals(false, TableConstraintSuggestion.isTableConstraint(unchecked)); + assertDoesNotThrow(() -> TableConstraintSuggestion.require(unchecked)); + assertDoesNotThrow(() -> TableConstraintSuggestion.requireToApply(unchecked, null, null)); assertDoesNotThrow(() -> invokeApplySuggestion(applied, orders, repository, "approver")); + verify(repository, never()) + .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + + Task suggestion = applied.withType(TaskEntityType.Suggestion); + java.lang.reflect.InvocationTargetException thrown = + assertThrows( + java.lang.reflect.InvocationTargetException.class, + () -> invokeApplySuggestion(suggestion, orders, repository, "approver")); + assertEquals("write failed", thrown.getCause().getMessage()); } @Test @@ -420,6 +432,40 @@ void aResolutionBetweenOtherTypesOrOfTheSameType_isNotRefusedHere() { () -> TableConstraintSuggestion.requireSameSuggestionType( constraintTask, Map.of("reasoning", "no type given"))); + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is 'Description', the resolution says 'TableConstraint'", + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + descriptionTask(), Map.of("suggestionType", "TableConstraint"))) + .getMessage()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "tableconstraint", + "Tableconstraint", + "TABLECONSTRAINT", + " TableConstraint", + "TableConstraint " + }) + void aResolutionNamingTheTypeWithAnotherCaseOrSpacing_isRefused(String spelling) { + Task constraintTask = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is 'TableConstraint', the resolution says '" + + spelling + + "'", + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + constraintTask, Map.of("suggestionType", spelling))) + .getMessage()); } @Test @@ -453,11 +499,21 @@ void aTableRepositoryRefusalOfTheConstraints_refusesApproving() { @Test void approvingAnEqualConstraint_doesNotValidateTheTable() { orders.setTableConstraints(List.of(constraint(ConstraintType.UNIQUE, List.of("email")))); + doThrow(new IllegalArgumentException("Table not found: " + CUSTOMERS)) + .when(tableRepository) + .validateTableConstraints(any(Table.class), any()); TableConstraintSuggestion.requireToApply( task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), null, null); verify(tableRepository, never()).validateTableConstraints(any(Table.class), any()); + Task notThereYet = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("order_id"))); + assertEquals( + "Table not found: " + CUSTOMERS, + assertThrows( + IllegalArgumentException.class, + () -> TableConstraintSuggestion.requireToApply(notThereYet, null, null)) + .getMessage()); } private Task descriptionTask() { From fc8ba01e6a8a29eadd5c93bb0198ea212362ccc9 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 17:58:06 -0800 Subject: [PATCH 120/203] Take the task form out of what approving a constraint suggestion needs and does A suggestion task's form, bound to its category, could name a narrower permission, a handler of another type or approve actions without applySuggestion. Approving a table constraint now asks for EditAll before any form is read, and applies the suggestion and nothing else, whatever handler and actions the form names. --- ...stion-task-can-carry-a-table-constraint.md | 12 +- .../TaskTableConstraintSuggestionIT.java | 204 +++++++++++++++++- .../service/jdbi3/TaskRepository.java | 6 + .../service/tasks/TaskWorkflowHandler.java | 9 + ...askRepositoryConstraintPermissionTest.java | 147 +++++++++++++ .../tasks/TableConstraintSuggestionTest.java | 165 ++++++++++++++ 6 files changed, 538 insertions(+), 5 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TaskRepositoryConstraintPermissionTest.java diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index b814a09d1163..2d45a22e396c 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,9 +1,9 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does) - **Deciders:** OpenMetadata maintainers -- **Guard:** `TableConstraintSuggestionTest` (the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply), `SuggestionTypeRoutingTest`, `TaskTableConstraintSuggestionIT` +- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category) - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type ## Context @@ -27,8 +27,12 @@ declined. is a column of an existing table. A foreign key has one referred column for each column, and another type has none. Approving repeats these checks on the payload the approver resolved with. - Approving needs `EditAll` on the table. A PATCH of `tableConstraints` maps to no narrower - operation in `ResourceRegistry`, so `TaskRepository#getOperationForSuggestion` returns `EDIT_ALL` - and the task's own authorization check runs before anything is written. + operation in `ResourceRegistry`, so `TaskRepository#getOperationForTask` returns `EDIT_ALL` for a + constraint suggestion, before it reads any task form, and the task's own authorization check + runs before anything is written. +- No task form changes what approving a constraint suggestion needs or does. Approving needs + `EditAll` on the table and adds the constraint, whatever form the task's category matches. + A form's permission, handler and actions apply to other tasks as before. - Applying patches the table as the approver through the table repository, so its own validation runs. A constraint equal to one already on the table (same type, columns and referred columns) writes nothing and the task still resolves. A second primary key is refused with a 400 naming diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 5aaad4c3f234..1c25a413d4f4 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -36,6 +36,7 @@ import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.tasks.BulkTaskOperation; import org.openmetadata.schema.api.tasks.CreateTask; import org.openmetadata.schema.api.tasks.ResolveTask; import org.openmetadata.schema.entity.data.DatabaseSchema; @@ -46,6 +47,9 @@ import org.openmetadata.schema.entity.services.DatabaseService; import org.openmetadata.schema.entity.tasks.Task; import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.BulkTaskOperationParams; +import org.openmetadata.schema.type.BulkTaskOperationResult; +import org.openmetadata.schema.type.BulkTaskOperationType; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.schema.type.TableConstraint.RelationshipType; @@ -470,6 +474,194 @@ void aCustomTaskCarryingAConstraintPayloadAddsNoConstraintForAUserWhoMayOnlyEdit } } + private static final String EDIT_ALL_REQUIRED = + "Principal: CatalogPrincipal{name='shared_user2'} operations [EditAll] not allowed"; + + /** + * A task form bound to the category of a constraint suggestion can narrow the right to resolve + * the task. It cannot narrow the right to add a table constraint: that stays EditAll on the table + * for each way of resolving. No other test files a suggestion of the Review category, so the + * form cannot reach another test's task. + */ + @Test + void aFormNamingEditDescriptionDoesNotLowerTheRightToApproveAConstraintSuggestion( + TestNamespace ns) { + String user2 = SharedEntities.get().USER2.getFullyQualifiedName(); + OpenMetadataClient user2Client = SdkClients.user2Client(); + Table table = ownedTable(ns, "formperm"); + Table applied = ownedTable(ns, "formpermapply"); + Table bulked = ownedTable(ns, "formpermbulk"); + TaskFormSchema form = createSuggestionFormFor(ns, TaskCategory.Review, "suggestion", null); + try { + Task resolved = fileConstraint(ns, TaskCategory.Review, table, "resolve", user2); + Task viaApply = fileConstraint(ns, TaskCategory.Review, applied, "apply", user2); + Task viaBulk = fileConstraint(ns, TaskCategory.Review, bulked, "bulk", user2); + String updatedBy = updatedByOf(table); + awaitWorkflowTask(resolved); + awaitWorkflowTask(viaApply); + awaitWorkflowTask(viaBulk); + + ForbiddenException resolveDenied = + assertThrows( + ForbiddenException.class, + () -> + user2Client + .tasks() + .resolve( + resolved.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved))); + ForbiddenException applyDenied = + assertThrows(ForbiddenException.class, () -> apply(user2Client, viaApply)); + BulkTaskOperationResult bulkResult = bulkApprove(user2Client, viaBulk); + + assertEquals(EDIT_ALL_REQUIRED, resolveDenied.getMessage()); + assertEquals(EDIT_ALL_REQUIRED, applyDenied.getMessage()); + assertEquals(0, bulkResult.getSuccessful()); + assertEquals(1, bulkResult.getFailed()); + assertEquals(EDIT_ALL_REQUIRED, bulkResult.getResults().get(0).getError()); + for (Task task : List.of(resolved, viaApply, viaBulk)) { + assertStillOpen(task); + } + assertEquals(List.of(), constraintsOf(table)); + assertEquals(List.of(), constraintsOf(applied)); + assertEquals(List.of(), constraintsOf(bulked)); + assertEquals(updatedBy, updatedByOf(table)); + + Task approved = + SdkClients.user3Client() + .tasks() + .resolve( + resolved.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + assertEquals("shared_user3", updatedByOf(table)); + } finally { + deleteForm(form); + } + } + + /** + * What approving a constraint suggestion does comes from the suggestion, not from a form bound to + * its category: under a form that names another handler, no action, or an action that writes + * another field, approving adds the constraint and nothing else, and rejecting writes nothing. + * Each form has a category of its own that no other test files a suggestion under. + */ + @Test + void aFormNamingAnotherHandlerOrActionsChangesNothingApprovingAConstraintSuggestionDoes( + TestNamespace ns) { + Object noActions = List.of(); + Object patchesTheDescription = + List.of( + Map.of( + "type", + "patchEntityField", + "entityField", + "description", + "value", + "from the form")); + Object[][] forms = { + {TaskCategory.Approval, "approval", noActions}, + {TaskCategory.Incident, "suggestion", patchesTheDescription}, + {TaskCategory.Custom, "custom", List.of(Map.of("type", "setDescription"))} + }; + for (Object[] bound : forms) { + TaskCategory category = (TaskCategory) bound[0]; + Table approvedTable = ownedTable(ns, "approve" + category.value().toLowerCase()); + Table rejectedTable = ownedTable(ns, "reject" + category.value().toLowerCase()); + TaskFormSchema form = createSuggestionFormFor(ns, category, (String) bound[1], bound[2]); + try { + Task approving = fileConstraint(ns, category, approvedTable, "approve", null); + Task rejecting = fileConstraint(ns, category, rejectedTable, "reject", null); + awaitWorkflowTask(approving); + awaitWorkflowTask(rejecting); + String descriptionBefore = descriptionOf(approvedTable); + + Task approved = + SdkClients.user3Client() + .tasks() + .resolve( + approving.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + Task rejected = + SdkClients.user3Client() + .tasks() + .resolve( + rejecting.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus(), category.value()); + List constraints = constraintsOf(approvedTable); + assertEquals(1, constraints.size(), category.value()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + assertEquals(descriptionBefore, descriptionOf(approvedTable), category.value()); + assertEquals(TaskEntityStatus.Rejected, rejected.getStatus(), category.value()); + assertEquals(List.of(), constraintsOf(rejectedTable), category.value()); + assertEquals(descriptionBefore, descriptionOf(rejectedTable), category.value()); + } finally { + deleteForm(form); + } + } + } + + private static Task fileConstraint( + TestNamespace ns, TaskCategory category, Table table, String label, String assignee) { + return fileIn( + ns, + category, + table, + label, + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + assignee == null ? null : List.of(assignee)); + } + + private static TaskFormSchema createSuggestionFormFor( + TestNamespace ns, TaskCategory category, String handler, Object approveActions) { + UiSchema ui = + new UiSchema() + .withAdditionalProperty( + "ui:handler", Map.of("type", handler, "permission", "EditDescription")); + if (approveActions != null) { + ui.withAdditionalProperty( + "ui:execution", Map.of("approve", Map.of("actions", approveActions))); + } + return SdkClients.adminClient() + .taskFormSchemas() + .create( + new TaskFormSchema() + .withId(UUID.randomUUID()) + .withName(ns.prefix("suggestion-form-" + category.value().toLowerCase())) + .withTaskType(TaskEntityType.Suggestion.value()) + .withTaskCategory(category.value()) + .withFormSchema( + new FormSchema() + .withAdditionalProperty("type", "object") + .withAdditionalProperty("properties", Map.of())) + .withUiSchema(ui)); + } + + private static void deleteForm(TaskFormSchema form) { + SdkClients.adminClient() + .taskFormSchemas() + .delete(form.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + } + + private static BulkTaskOperationResult bulkApprove(OpenMetadataClient client, Task task) { + BulkTaskOperation operation = + new BulkTaskOperation() + .withTaskIds(List.of(task.getId().toString())) + .withOperation(BulkTaskOperationType.Approve) + .withParams(new BulkTaskOperationParams().withComment("approve")); + return client + .getHttpClient() + .execute(HttpMethod.POST, "/v1/tasks/bulk", operation, BulkTaskOperationResult.class); + } + private static TaskFormSchema createSuggestionForm(TestNamespace ns) { return SdkClients.adminClient() .taskFormSchemas() @@ -598,10 +790,20 @@ private static Task file( String label, Map payload, List assignees) { + return fileIn(ns, TaskCategory.MetadataUpdate, table, label, payload, assignees); + } + + private static Task fileIn( + TestNamespace ns, + TaskCategory category, + Table table, + String label, + Map payload, + List assignees) { CreateTask request = new CreateTask() .withName(ns.prefix("constraint-" + label)) - .withCategory(TaskCategory.MetadataUpdate) + .withCategory(category) .withType(TaskEntityType.Suggestion) .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) .withPayload(payload); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index b429bcf18bde..6c5bfff6a7bd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -1458,6 +1458,12 @@ private MetadataOperation getOperationForTask(Task task) { return null; } + // No task form lowers the right to add a table constraint: whatever form the task's category + // matches, approving needs EditAll on the table. + if (TableConstraintSuggestion.isTableConstraint(task)) { + return MetadataOperation.EDIT_ALL; + } + MetadataOperation schemaBoundOperation = TaskFormExecutionResolver.resolve(task).permissionOperation(); if (schemaBoundOperation != null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index baa223a7e4ce..7e6fdb0b20ee 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -830,6 +830,15 @@ private void applyEntityChanges( EntityInterface entity = Entity.getEntity(aboutRef, "*", Include.ALL); EntityRepository repository = Entity.getEntityRepository(aboutRef.getType()); + // No task form changes what approving a table constraint does: it adds the constraint and + // nothing else, and rejecting it writes nothing, whatever handler and actions the form names. + if (TableConstraintSuggestion.isTableConstraint(task)) { + if (approved) { + applySuggestion(task, effectivePayload, entity, repository, user); + } + return; + } + List actions = approved ? executionPlan.approveActions() : executionPlan.rejectActions(); if (actions == null || actions.isEmpty()) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TaskRepositoryConstraintPermissionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TaskRepositoryConstraintPermissionTest.java new file mode 100644 index 000000000000..65499350501a --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TaskRepositoryConstraintPermissionTest.java @@ -0,0 +1,147 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.jdbi3; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.ws.rs.core.SecurityContext; +import java.security.Principal; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.openmetadata.schema.entity.feed.TaskFormSchema; +import org.openmetadata.schema.entity.feed.UiSchema; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.service.Entity; +import org.openmetadata.service.security.AuthRequest; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; + +/** + * The right to resolve a suggestion task on its table comes from the suggested change. A task form + * bound to the task's category can narrow it for a description suggestion, never for a table + * constraint. + */ +class TaskRepositoryConstraintPermissionTest { + private static final String TABLE_FQN = "svc.db.schema.orders"; + private MockedStatic entity; + private Authorizer authorizer; + private SecurityContext securityContext; + private TaskFormSchemaRepository formRepository; + + @BeforeEach + void setUp() { + formRepository = mock(TaskFormSchemaRepository.class); + when(formRepository.resolve(anyString(), any(), any())) + .thenReturn(Optional.of(formWithPermission("EditDescription"))); + entity = mockStatic(Entity.class); + entity + .when(() -> Entity.getEntityRepository(Entity.TASK_FORM_SCHEMA)) + .thenAnswer(i -> formRepository); + authorizer = mock(Authorizer.class); + Principal principal = mock(Principal.class); + when(principal.getName()).thenReturn("shared_user2"); + securityContext = mock(SecurityContext.class); + when(securityContext.getUserPrincipal()).thenReturn(principal); + } + + @AfterEach + void tearDown() { + entity.close(); + } + + @Test + void aConstraintSuggestion_needsEditAllOnTheTableWhateverPermissionTheFormNames() { + TaskRepository repository = mock(TaskRepository.class, CALLS_REAL_METHODS); + + repository.checkPermissionsForResolveTask( + authorizer, suggestion("TableConstraint"), false, securityContext); + + ArgumentCaptor tableOperation = + ArgumentCaptor.forClass(OperationContext.class); + verify(authorizer, times(2)) + .authorize(any(SecurityContext.class), tableOperation.capture(), any()); + OperationContext table = tableOperation.getAllValues().get(1); + assertEquals(Entity.TABLE, table.getResource()); + assertEquals( + List.of(MetadataOperation.EDIT_ALL), table.getOperations((ResourceContextInterface) null)); + verify(authorizer, never()).authorizeRequests(any(), any(), any()); + } + + @Test + void aDescriptionSuggestion_stillAsksForThePermissionTheFormNames() { + TaskRepository repository = mock(TaskRepository.class, CALLS_REAL_METHODS); + + repository.checkPermissionsForResolveTask( + authorizer, suggestion("Description"), false, securityContext); + + ArgumentCaptor> requests = ArgumentCaptor.forClass(List.class); + verify(authorizer).authorizeRequests(any(), requests.capture(), any()); + assertEquals( + List.of(MetadataOperation.EDIT_DESCRIPTION, MetadataOperation.EDIT_ALL), + requests.getValue().stream() + .map( + request -> + request + .operationContext() + .getOperations((ResourceContextInterface) null) + .get(0)) + .toList()); + } + + private static TaskFormSchema formWithPermission(String permission) { + return new TaskFormSchema() + .withUiSchema( + new UiSchema() + .withAdditionalProperty( + "ui:handler", Map.of("type", "suggestion", "permission", permission))); + } + + private static Task suggestion(String suggestionType) { + return new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withAbout( + new EntityReference() + .withId(UUID.randomUUID()) + .withType(Entity.TABLE) + .withFullyQualifiedName(TABLE_FQN)) + .withPayload( + Map.of( + "suggestionType", + suggestionType, + "fieldPath", + suggestionType.equals("Description") ? "description" : "tableConstraints", + "suggestedValue", + "x")); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java index a22fc853acba..a4f0c11cb1d6 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -24,7 +24,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import jakarta.json.JsonPatch; import java.lang.reflect.Method; @@ -44,6 +46,8 @@ import org.mockito.MockedStatic; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.feed.TaskFormSchema; +import org.openmetadata.schema.entity.feed.UiSchema; import org.openmetadata.schema.entity.tasks.Task; import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.EntityReference; @@ -58,6 +62,7 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.TableRepository; +import org.openmetadata.service.jdbi3.TaskFormSchemaRepository; class TableConstraintSuggestionTest { private static final String ORDERS = "svc.db.schema.orders"; @@ -65,14 +70,19 @@ class TableConstraintSuggestionTest { private MockedStatic entity; private Table orders; private TableRepository tableRepository; + private TaskFormSchemaRepository formRepository; @BeforeEach void setUp() { orders = table("orders", ORDERS, "order_id", "customer_id", "email"); Table customers = table("customers", CUSTOMERS, "id"); tableRepository = mock(TableRepository.class); + formRepository = mock(TaskFormSchemaRepository.class); entity = mockStatic(Entity.class); entity.when(() -> Entity.getEntityRepository(Entity.TABLE)).thenAnswer(i -> tableRepository); + entity + .when(() -> Entity.getEntityRepository(Entity.TASK_FORM_SCHEMA)) + .thenAnswer(i -> formRepository); entity .when(() -> Entity.getEntity(any(EntityReference.class), anyString(), any(Include.class))) .thenAnswer(invocation -> orders); @@ -516,6 +526,161 @@ void approvingAnEqualConstraint_doesNotValidateTheTable() { .getMessage()); } + @ParameterizedTest + @ValueSource( + strings = { + "approval handler with no approve actions", + "suggestion handler with the approve action setDescription", + "suggestion handler with the approve action patchEntityField", + "custom handler with the approve action replaceOwners" + }) + void approving_underAnyForm_addsTheConstraintAndMakesNoOtherChange(String formName) + throws Exception { + boundTo(formName); + EntityRepository repository = tableRepository; + TableConstraint unique = constraint(ConstraintType.UNIQUE, List.of("email")); + + invokeApplyEntityChanges(task(Entity.TABLE, unique), true, repository); + + ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); + verify(repository, times(1)) + .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any(), (String) any()); + assertEquals( + "[{\"op\":\"add\",\"path\":\"/tableConstraints\",\"value\":[{\"constraintType\":\"UNIQUE\"," + + "\"columns\":[\"email\"]}]}]", + patch.getValue().toJsonArray().toString()); + assertEquals(null, orders.getDescription()); + } + + @Test + void approving_withTheDefaultForm_addsTheSameConstraint() throws Exception { + EntityRepository repository = tableRepository; + + invokeApplyEntityChanges( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), true, repository); + + verify(repository, times(1)) + .patch( + any(), eq(orders.getId()), eq("approver"), any(JsonPatch.class), any(), (String) any()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "approval handler with no approve actions", + "suggestion handler with the approve action setDescription" + }) + void rejecting_underAnyForm_writesNothing(String formName) throws Exception { + boundTo(formName); + EntityRepository repository = tableRepository; + + invokeApplyEntityChanges( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), false, repository); + + verify(repository, never()) + .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + } + + @Test + void rejecting_underAFormWhoseRejectActionAppliesTheSuggestion_writesNothing() throws Exception { + when(formRepository.resolve(anyString(), any(), any())) + .thenReturn( + Optional.of( + form( + Map.of("type", "suggestion"), + Map.of( + "reject", Map.of("actions", List.of(Map.of("type", "applySuggestion"))))))); + EntityRepository repository = tableRepository; + + invokeApplyEntityChanges( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), false, repository); + + verify(repository, never()) + .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + } + + @Test + void aFailureWhileApprovingUnderAnyForm_escapesSoTheTaskStaysOpen() throws Exception { + boundTo("approval handler with no approve actions"); + doThrow(new IllegalStateException("write failed")) + .when(tableRepository) + .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + + java.lang.reflect.InvocationTargetException thrown = + assertThrows( + java.lang.reflect.InvocationTargetException.class, + () -> + invokeApplyEntityChanges( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), + true, + tableRepository)); + + assertEquals("write failed", thrown.getCause().getMessage()); + } + + @Test + void aDescriptionSuggestionUnderTheDefaultForm_isStillAppliedByTheSameCall() throws Exception { + ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); + + invokeApplyEntityChanges(descriptionTask(), true, tableRepository); + + verify(tableRepository, times(1)) + .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any(), (String) any()); + assertTrue(patch.getValue().toJsonArray().toString().contains("/description")); + } + + private void boundTo(String formName) { + TaskFormSchema form = + switch (formName) { + case "approval handler with no approve actions" -> form( + Map.of("type", "approval"), Map.of("approve", Map.of("actions", List.of()))); + case "suggestion handler with the approve action setDescription" -> form( + Map.of("type", "suggestion"), + Map.of("approve", Map.of("actions", List.of(Map.of("type", "setDescription"))))); + case "suggestion handler with the approve action patchEntityField" -> form( + Map.of("type", "suggestion"), + Map.of( + "approve", + Map.of( + "actions", + List.of( + Map.of( + "type", + "patchEntityField", + "entityField", + "description", + "value", + "patched by the form"))))); + default -> form( + Map.of("type", "custom"), + Map.of("approve", Map.of("actions", List.of(Map.of("type", "replaceOwners"))))); + }; + when(formRepository.resolve(anyString(), any(), any())).thenReturn(Optional.of(form)); + } + + private static TaskFormSchema form(Map handler, Map execution) { + return new TaskFormSchema() + .withUiSchema( + new UiSchema() + .withAdditionalProperty("ui:handler", handler) + .withAdditionalProperty("ui:execution", execution)); + } + + private static void invokeApplyEntityChanges( + Task task, boolean approved, EntityRepository repository) throws Exception { + Method applyEntityChanges = + TaskWorkflowHandler.class.getDeclaredMethod( + "applyEntityChanges", + Task.class, + boolean.class, + String.class, + Object.class, + String.class); + applyEntityChanges.setAccessible(true); + applyEntityChanges.invoke( + TaskWorkflowHandler.getInstance(), task, approved, null, null, "approver"); + } + private Task descriptionTask() { Map payload = new java.util.LinkedHashMap<>(); payload.put("suggestionType", "Description"); From 4f7dbd6b71004050768cc814e6e0414d59011dfe Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 18:10:43 -0800 Subject: [PATCH 121/203] Test that a custom task carrying a constraint payload still runs its form's actions --- .../TaskTableConstraintSuggestionIT.java | 69 ++++++++++++++++++- 1 file changed, 67 insertions(+), 2 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 1c25a413d4f4..aafc7cd20972 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -609,6 +609,57 @@ void aFormNamingAnotherHandlerOrActionsChangesNothingApprovingAConstraintSuggest } } + /** + * A task of another type that carries a constraint payload keeps what its form says: the form's + * action runs, and no constraint is added. The form is bound to custom tasks of the Incident + * category, which no other test files. + */ + @Test + void aCustomTaskCarryingAConstraintPayloadStillRunsItsFormsActionsAndAddsNoConstraint( + TestNamespace ns) { + Table table = adminTable(ns, "customactions"); + TaskFormSchema form = + createFormFor( + ns, + TaskEntityType.CustomTask, + TaskCategory.Incident, + List.of( + Map.of( + "type", + "patchEntityField", + "entityField", + "description", + "value", + "from form"))); + try { + Task task = + SdkClients.adminClient() + .tasks() + .create( + new CreateTask() + .withName(ns.prefix("custom-actions")) + .withCategory(TaskCategory.Incident) + .withType(TaskEntityType.CustomTask) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload( + payload( + JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))))); + + Task approved = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + assertEquals("from form", descriptionOf(table)); + assertEquals(List.of(), constraintsOf(table)); + } finally { + deleteForm(form); + } + } + private static Task fileConstraint( TestNamespace ns, TaskCategory category, Table table, String label, String assignee) { return fileIn( @@ -622,6 +673,20 @@ private static Task fileConstraint( private static TaskFormSchema createSuggestionFormFor( TestNamespace ns, TaskCategory category, String handler, Object approveActions) { + return createFormFor(ns, TaskEntityType.Suggestion, category, handler, approveActions); + } + + private static TaskFormSchema createFormFor( + TestNamespace ns, TaskEntityType type, TaskCategory category, Object approveActions) { + return createFormFor(ns, type, category, "custom", approveActions); + } + + private static TaskFormSchema createFormFor( + TestNamespace ns, + TaskEntityType type, + TaskCategory category, + String handler, + Object approveActions) { UiSchema ui = new UiSchema() .withAdditionalProperty( @@ -635,8 +700,8 @@ private static TaskFormSchema createSuggestionFormFor( .create( new TaskFormSchema() .withId(UUID.randomUUID()) - .withName(ns.prefix("suggestion-form-" + category.value().toLowerCase())) - .withTaskType(TaskEntityType.Suggestion.value()) + .withName(ns.prefix("form-" + type.value() + "-" + category.value().toLowerCase())) + .withTaskType(type.value()) .withTaskCategory(category.value()) .withFormSchema( new FormSchema() From c7e16d0e35fbbcd3ba111ee55f49fc7185b08964 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 27 Nov 2026 21:02:26 -0800 Subject: [PATCH 122/203] Hold a table constraint suggestion's payload to the keys of the suggestion payload schema A table constraint suggestion is refused, with a 400 that names each key the generated SuggestionPayload does not declare, when it is filed, replaced or patched, when a resolution adds such a key, and when it is approved with the resolution's payload laid over it. Keys are compared exactly. With that, no payload key other than the suggestion's own can decide what approving it needs or does. The replaceOwners case of the unit test now carries newOwners. --- ...stion-task-can-carry-a-table-constraint.md | 11 +- .../TaskTableConstraintSuggestionIT.java | 230 ++++++++++++++++++ .../service/resources/tasks/TaskResource.java | 10 + .../tasks/TableConstraintSuggestion.java | 61 +++++ .../service/tasks/TaskWorkflowHandler.java | 1 + .../tasks/TableConstraintSuggestionTest.java | 95 +++++++- 6 files changed, 405 insertions(+), 3 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index 2d45a22e396c..5f71a770536d 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,9 +1,9 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema) - **Deciders:** OpenMetadata maintainers -- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category) +- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing, patching, replacing and resolving; a task that carries every declared key) - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type ## Context @@ -33,6 +33,11 @@ declined. - No task form changes what approving a constraint suggestion needs or does. Approving needs `EditAll` on the table and adds the constraint, whatever form the task's category matches. A form's permission, handler and actions apply to other tasks as before. +- A constraint suggestion's payload holds only the keys of the suggestion payload schema, so no + other key decides what approving it needs or does. Filing, replacing or patching a task, and a + resolution whose payload adds a key, are refused with a 400 that names each key the schema does + not declare, and approving repeats the check on the merged payload. Keys are compared exactly. + The names come from the generated `SuggestionPayload`, so the rule follows the schema. - Applying patches the table as the approver through the table repository, so its own validation runs. A constraint equal to one already on the table (same type, columns and referred columns) writes nothing and the task still resolves. A second primary key is refused with a 400 naming @@ -52,6 +57,8 @@ declined. - The suggestion type is compared exactly. A resolution that spells `TableConstraint` with another case or with a space around it is refused like any other change of type. - Rejecting leaves the table unchanged and the task `Rejected`. +- A timer that an administrator adds to a workflow can close a task without applying it, as for + every task type. - A client finds the suggestions already made for a table, and the ones declined, by listing the tasks about that table with type `Suggestion` and a status, and reading `payload.suggestionType` and `payload.suggestedValue`. No list filter was added for it. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index aafc7cd20972..8f0fa99baace 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -660,6 +660,236 @@ void aCustomTaskCarryingAConstraintPayloadStillRunsItsFormsActionsAndAddsNoConst } } + private static final String KEYS_REFUSED = + "A table constraint suggestion carries only the keys of the suggestion payload (confidence, " + + "currentValue, fieldPath, reasoning, source, suggestedValue, suggestionType); not allowed: "; + + @Test + void aSuggestionNamingAChangeRequestIsRefusedWhenFiledAndNoTaskIsStored(TestNamespace ns) { + Table table = ownedTable(ns, "crkey"); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + fileWithExtraKey(ns, table, "crkey", "changeRequestId", UUID.randomUUID().toString())); + + assertEquals(List.of(), tasksAbout(table)); + assertEquals(List.of(), constraintsOf(table)); + } + + @Test + void aSuggestionCarryingTheKeyOfAFormActionIsRefusedWhenFiledAndNoTaskIsStored(TestNamespace ns) { + Table table = ownedTable(ns, "ownerskey"); + List> newOwners = + List.of(Map.of("id", SharedEntities.get().USER2.getId().toString(), "type", "user")); + + assertEquals( + KEYS_REFUSED + "newOwners", + fileWithExtraKey(ns, table, "ownerskey", "newOwners", newOwners)); + + assertEquals(List.of(), tasksAbout(table)); + } + + @Test + void aKeyThatDiffersFromADeclaredKeyOnlyInCaseIsRefused(TestNamespace ns) { + Table table = ownedTable(ns, "casekey"); + + assertEquals( + KEYS_REFUSED + "SuggestedValue", + fileWithExtraKey(ns, table, "casekey", "SuggestedValue", "x")); + assertEquals(List.of(), tasksAbout(table)); + } + + @Test + void aSuggestionCarryingEveryDeclaredKeyIsFiledAndApprovingAddsExactlyItsConstraint( + TestNamespace ns) { + Table table = ownedTable(ns, "allkeys"); + Map payload = + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))); + payload.put("currentValue", "[]"); + + Task task = + file( + ns, + table, + "allkeys", + payload, + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + + assertEquals( + List.of( + "confidence", + "currentValue", + "fieldPath", + "reasoning", + "source", + "suggestedValue", + "suggestionType"), + storedPayloadKeys(task)); + awaitWorkflowTask(task); + Task approved = resolve(SdkClients.user3Client(), task, null); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + assertEquals(null, constraints.get(0).getReferredColumns()); + assertEquals("shared_user3", updatedByOf(table)); + } + + @Test + void theKeysOfAnOpenSuggestionCannotChangeAfterItIsFiled(TestNamespace ns) { + Table table = ownedTable(ns, "frozen"); + Task task = + file( + ns, + table, + "frozen", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + List filed = storedPayloadKeys(task); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + patchRefused( + task, + "[{\"op\":\"add\",\"path\":\"/payload/changeRequestId\",\"value\":\"" + + UUID.randomUUID() + + "\"}]")); + assertEquals(filed, storedPayloadKeys(task)); + assertEquals( + KEYS_REFUSED + "newOwners", + patchRefused(task, "[{\"op\":\"add\",\"path\":\"/payload/newOwners\",\"value\":[]}]")); + assertEquals(filed, storedPayloadKeys(task)); + CreateTask putAgain = + new CreateTask() + .withName(ns.prefix("constraint-frozen")) + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.Suggestion) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload( + withKey( + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + "newOwners", + List.of())); + assertEquals( + KEYS_REFUSED + "newOwners", + assertThrows( + InvalidRequestException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.PUT, "/v1/tasks", putAgain, Task.class)) + .getMessage()); + assertEquals(filed, storedPayloadKeys(task)); + assertStillOpen(task); + + patchAccepted( + task, "[{\"op\":\"replace\",\"path\":\"/payload/reasoning\",\"value\":\"edited\"}]"); + assertEquals( + "edited", + JsonUtils.getMap( + SdkClients.adminClient().tasks().get(task.getId().toString(), "*").getPayload()) + .get("reasoning")); + assertStillOpen(task); + } + + @Test + void aResolutionThatAddsAKeyIsRefusedAndTheTaskStaysOpen(TestNamespace ns) { + Table table = ownedTable(ns, "reskey"); + Task task = + file( + ns, + table, + "reskey", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + Map extra = Map.of("changeRequestId", UUID.randomUUID().toString()); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + assertThrows( + InvalidRequestException.class, () -> resolve(SdkClients.user3Client(), task, extra)) + .getMessage()); + assertEquals( + KEYS_REFUSED + "changeRequestId", + assertThrows( + InvalidRequestException.class, + () -> + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Rejected) + .withPayload( + JsonUtils.convertValue( + extra, org.openmetadata.schema.api.tasks.Payload.class)))) + .getMessage()); + + assertEquals(List.of(), constraintsOf(table)); + assertStillOpen(task); + assertEquals( + List.of(), + storedPayloadKeys(task).stream().filter(k -> k.equals("changeRequestId")).toList()); + } + + private static Map withKey( + Map payload, String key, Object value) { + payload.put(key, value); + return payload; + } + + private static String fileWithExtraKey( + TestNamespace ns, Table table, String label, String key, Object value) { + return assertThrows( + InvalidRequestException.class, + () -> + file( + ns, + table, + label, + withKey( + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + key, + value), + List.of(SharedEntities.get().USER3.getFullyQualifiedName()))) + .getMessage(); + } + + private static List tasksAbout(Table table) { + ListParams params = new ListParams(); + params.addFilter("aboutEntity", table.getFullyQualifiedName()); + return SdkClients.adminClient().tasks().list(params).getData(); + } + + private static List storedPayloadKeys(Task task) { + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + return JsonUtils.getMap(stored.getPayload()).keySet().stream().sorted().toList(); + } + + private static String patchRefused(Task task, String patch) { + return assertThrows(InvalidRequestException.class, () -> patchTask(task, patch)).getMessage(); + } + + private static void patchAccepted(Task task, String patch) { + patchTask(task, patch); + } + + private static void patchTask(Task task, String patch) { + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + "/v1/tasks/" + task.getId(), + patch, + org.openmetadata.sdk.network.RequestOptions.builder() + .header("Content-Type", "application/json-patch+json") + .build()); + } + private static Task fileConstraint( TestNamespace ns, TaskCategory category, Table table, String label, String assignee) { return fileIn( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java index 8fc0fd748490..6e6467c06dad 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java @@ -115,6 +115,7 @@ import org.openmetadata.service.security.policyevaluator.SubjectContext; import org.openmetadata.service.security.policyevaluator.TaskResourceContext; import org.openmetadata.service.tasks.IncidentWorkflowStages; +import org.openmetadata.service.tasks.TableConstraintSuggestion; import org.openmetadata.service.tasks.TaskWorkflowLifecycleResolver; import org.openmetadata.service.util.EntityUtil; import org.openmetadata.service.util.EntityUtil.Fields; @@ -1158,6 +1159,7 @@ public Response createOrUpdate( } requireCreatableThroughApi(create); Task task = getTask(create, securityContext.getUserPrincipal().getName()); + TableConstraintSuggestion.requireDeclaredKeys(task); enforceDomainOnlyPolicyForTask(securityContext, task); authorizeCreateTaskOnAboutEntity(securityContext, task); return createOrUpdate(uriInfo, securityContext, task); @@ -1430,6 +1432,14 @@ private void validateTaskPatch(Task original, Task patched, boolean callerIsAdmi rejectPayloadOrAboutEditAfterOpen(original, patched); rejectServerOpenedTaskEdit(original, patched); rejectWorkflowBindingEdits(original, patched); + rejectUndeclaredConstraintKeys(original, patched); + } + + /** A table constraint suggestion's payload holds only the keys the suggestion payload declares. */ + private static void rejectUndeclaredConstraintKeys(Task original, Task patched) { + if (!Objects.equals(original.getPayload(), patched.getPayload())) { + TableConstraintSuggestion.requireDeclaredKeys(patched); + } } /** The type and category of a task decide which resolve rules apply to it. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java index c81c48fbf515..2b3d7ad7433e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java @@ -17,6 +17,7 @@ import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; @@ -24,10 +25,13 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.entity.tasks.Task; import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.SuggestionPayload; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.schema.type.TaskEntityType; @@ -48,6 +52,9 @@ * a foreign key, referred columns of existing tables. Approving also refuses a second primary key * (ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint). A resolution cannot change a * task's suggestion type to or from {@code TableConstraint}. + * + *

    Its payload holds only the keys that {@link SuggestionPayload} declares, so no other key can + * decide what approving the task needs or does. */ public final class TableConstraintSuggestion { public static final String TYPE = "TableConstraint"; @@ -57,8 +64,60 @@ public final class TableConstraintSuggestion { private static final Set SUPPORTED = EnumSet.of(ConstraintType.PRIMARY_KEY, ConstraintType.UNIQUE, ConstraintType.FOREIGN_KEY); + private static final Set DECLARED_KEYS = declaredKeys(); + private TableConstraintSuggestion() {} + /** The property names of the generated {@link SuggestionPayload}, which follow its schema. */ + private static Set declaredKeys() { + var mapper = JsonUtils.getObjectMapper(); + return mapper + .getSerializationConfig() + .introspect(mapper.constructType(SuggestionPayload.class)) + .findProperties() + .stream() + .map(BeanPropertyDefinition::getName) + .collect(Collectors.toCollection(TreeSet::new)); + } + + /** + * Refuses a payload that has a top-level key {@link SuggestionPayload} does not declare. Keys are + * compared exactly, so {@code SuggestedValue} is not {@code suggestedValue}. + */ + public static void requireDeclaredKeys(JsonNode payload) { + Set undeclared = new TreeSet<>(); + payload + .fieldNames() + .forEachRemaining( + key -> { + if (!DECLARED_KEYS.contains(key)) { + undeclared.add(key); + } + }); + if (!undeclared.isEmpty()) { + throw BadRequestException.of( + "A table constraint suggestion carries only the keys of the suggestion payload (%s); not allowed: %s" + .formatted(String.join(", ", DECLARED_KEYS), String.join(", ", undeclared))); + } + } + + /** Refuses a payload of a table constraint suggestion that has a key the schema does not declare. */ + public static void requireDeclaredKeys(Task task) { + if (isTableConstraint(task)) { + requireDeclaredKeys(JsonUtils.valueToTree(task.getPayload())); + } + } + + /** + * Refuses a resolution whose payload adds a key the suggestion payload does not declare to a + * table constraint suggestion, whatever the resolution is. + */ + public static void requireDeclaredKeys(Task task, Object requestPayload) { + if (isTableConstraint(task) && requestPayload != null) { + requireDeclaredKeys(JsonUtils.valueToTree(requestPayload)); + } + } + public static boolean isTableConstraint(Task task) { return task != null && task.getType() == TaskEntityType.Suggestion @@ -91,6 +150,7 @@ public static void requireSameSuggestionType(Task task, Object requestPayload) { /** Refuses filing a table constraint suggestion that names no valid constraint of its table. */ public static void require(Task task) { if (isTableConstraint(task)) { + requireDeclaredKeys(task); validate(task, JsonUtils.valueToTree(task.getPayload())); } } @@ -104,6 +164,7 @@ public static void requireToApply(Task task, Object requestPayload, String newVa JsonNode merged = JsonUtils.valueToTree( TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + requireDeclaredKeys(merged); Table table = loadTable(task); TableConstraint constraint = validate(task, merged, table); toAdd(table, constraint) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 7e6fdb0b20ee..ee937de6b67e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -200,6 +200,7 @@ public Task resolveTask( effectiveResolutionType, user); TaskFieldTarget.requireToApply(task, effectiveResolutionType, resolvedPayload); + TableConstraintSuggestion.requireDeclaredKeys(task, resolvedPayload); if (isPositiveResolution(effectiveResolutionType)) { TableConstraintSuggestion.requireSameSuggestionType(task, resolvedPayload); TableConstraintSuggestion.requireToApply(task, resolvedPayload, newValue); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java index a4f0c11cb1d6..4156f84ed060 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -388,6 +388,92 @@ void aTaskOfAnotherTypeCarryingAConstraintPayload_getsNoCheckNoWriteAndNoRethrow assertEquals("write failed", thrown.getCause().getMessage()); } + private static final String KEYS_REFUSED = + "A table constraint suggestion carries only the keys of the suggestion payload (confidence, " + + "currentValue, fieldPath, reasoning, source, suggestedValue, suggestionType); not allowed: "; + + @ParameterizedTest + @ValueSource( + strings = { + "changeRequestId", + "newOwners", + "feedback", + "expirationDate", + "lifecycleMove", + "proposedChanges", + "assignees", + "SuggestedValue", + "suggestedvalue", + " suggestedValue" + }) + void aKeyTheSuggestionPayloadDoesNotDeclare_isRefusedWhenFiledAndWhenApproved(String key) { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + payloadOf(task).put(key, "x"); + + assertEquals( + KEYS_REFUSED + key, + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)) + .getMessage()); + assertEquals( + KEYS_REFUSED + key, + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.requireToApply(task, null, null)) + .getMessage()); + } + + @Test + void everyKeyTheSuggestionPayloadDeclares_isAccepted() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + Map payload = payloadOf(task); + payload.put("currentValue", "[]"); + payload.put("confidence", 80.0); + payload.put("source", "Agent"); + payload.put("reasoning", "The column is unique in the sampled rows"); + + assertEquals(7, payload.size()); + assertDoesNotThrow(() -> TableConstraintSuggestion.require(task)); + assertDoesNotThrow(() -> TableConstraintSuggestion.requireToApply(task, null, null)); + } + + @Test + void severalUndeclaredKeys_areAllNamedInOrder() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + payloadOf(task).put("newOwners", "x"); + payloadOf(task).put("changeRequestId", "y"); + + assertEquals( + KEYS_REFUSED + "changeRequestId, newOwners", + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)) + .getMessage()); + } + + @Test + void aResolutionPayloadThatAddsAnUndeclaredKey_isRefusedForAConstraintSuggestionOnly() { + Task constraintTask = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + Task descriptionTask = descriptionTask(); + Map resolution = Map.of("changeRequestId", "x"); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.requireDeclaredKeys(constraintTask, resolution)) + .getMessage()); + assertDoesNotThrow( + () -> + TableConstraintSuggestion.requireDeclaredKeys( + constraintTask, Map.of("source", "User"))); + assertDoesNotThrow(() -> TableConstraintSuggestion.requireDeclaredKeys(constraintTask, null)); + assertDoesNotThrow( + () -> TableConstraintSuggestion.requireDeclaredKeys(descriptionTask, resolution)); + } + + @SuppressWarnings("unchecked") + private static Map payloadOf(Task task) { + return (Map) task.getPayload(); + } + @Test void aResolutionCannotTurnADescriptionSuggestionIntoAConstraint() { Task description = descriptionTask(); @@ -539,8 +625,14 @@ void approving_underAnyForm_addsTheConstraintAndMakesNoOtherChange(String formNa boundTo(formName); EntityRepository repository = tableRepository; TableConstraint unique = constraint(ConstraintType.UNIQUE, List.of("email")); + Task approved = task(Entity.TABLE, unique); + payloadOf(approved) + .put( + "newOwners", + List.of( + Map.of("id", UUID.randomUUID().toString(), "type", "user", "name", "newcomer"))); - invokeApplyEntityChanges(task(Entity.TABLE, unique), true, repository); + invokeApplyEntityChanges(approved, true, repository); ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); verify(repository, times(1)) @@ -550,6 +642,7 @@ void approving_underAnyForm_addsTheConstraintAndMakesNoOtherChange(String formNa + "\"columns\":[\"email\"]}]}]", patch.getValue().toJsonArray().toString()); assertEquals(null, orders.getDescription()); + assertEquals(null, orders.getOwners()); } @Test From 5342031eed3490db87c968aaef439ceb43cdc657 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 28 Nov 2026 09:42:53 -0800 Subject: [PATCH 123/203] Refuse a resolution of any type that would write a key outside the suggestion payload schema into a constraint suggestion --- .../TaskTableConstraintSuggestionIT.java | 235 ++++++++++++++++-- .../service/resources/tasks/TaskResource.java | 1 - .../tasks/TableConstraintSuggestion.java | 24 +- .../service/tasks/TaskWorkflowHandler.java | 2 +- .../tasks/TableConstraintSuggestionTest.java | 82 +++++- 5 files changed, 311 insertions(+), 33 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 8f0fa99baace..cbbab85f3f55 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -18,6 +18,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; @@ -63,6 +69,7 @@ import org.openmetadata.sdk.exceptions.InvalidRequestException; import org.openmetadata.sdk.models.ListParams; import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; import org.openmetadata.service.governance.workflows.WorkflowHandler; import org.openmetadata.service.util.FullyQualifiedName; @@ -762,26 +769,6 @@ void theKeysOfAnOpenSuggestionCannotChangeAfterItIsFiled(TestNamespace ns) { KEYS_REFUSED + "newOwners", patchRefused(task, "[{\"op\":\"add\",\"path\":\"/payload/newOwners\",\"value\":[]}]")); assertEquals(filed, storedPayloadKeys(task)); - CreateTask putAgain = - new CreateTask() - .withName(ns.prefix("constraint-frozen")) - .withCategory(TaskCategory.MetadataUpdate) - .withType(TaskEntityType.Suggestion) - .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) - .withPayload( - withKey( - payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), - "newOwners", - List.of())); - assertEquals( - KEYS_REFUSED + "newOwners", - assertThrows( - InvalidRequestException.class, - () -> - SdkClients.adminClient() - .getHttpClient() - .execute(HttpMethod.PUT, "/v1/tasks", putAgain, Task.class)) - .getMessage()); assertEquals(filed, storedPayloadKeys(task)); assertStillOpen(task); @@ -836,6 +823,206 @@ void aResolutionThatAddsAKeyIsRefusedAndTheTaskStaysOpen(TestNamespace ns) { storedPayloadKeys(task).stream().filter(k -> k.equals("changeRequestId")).toList()); } + @Test + void aSuggestionFiledByPutWithAKeyOutsideTheSchemaIsRefusedAndNoTaskIsStored(TestNamespace ns) { + Table table = ownedTable(ns, "putkey"); + CreateTask put = + new CreateTask() + .withName(ns.prefix("constraint-putkey")) + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.Suggestion) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload( + withKey( + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + "newOwners", + List.of())); + + assertEquals( + KEYS_REFUSED + "newOwners", + assertThrows( + InvalidRequestException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.PUT, "/v1/tasks", put, Task.class)) + .getMessage()); + + assertEquals(List.of(), tasksAbout(table)); + } + + @Test + void aPatchThatTurnsADescriptionSuggestionIntoAConstraintCannotAddAKey(TestNamespace ns) { + Table table = ownedTable(ns, "typepatch"); + Task task = + file( + ns, + table, + "typepatch", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "Orders placed by customers"), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + List filed = storedPayloadKeys(task); + + assertEquals( + KEYS_REFUSED + "newOwners", + patchRefused( + task, + "[{\"op\":\"replace\",\"path\":\"/payload/suggestionType\",\"value\":\"TableConstraint\"}," + + "{\"op\":\"replace\",\"path\":\"/payload/fieldPath\",\"value\":\"tableConstraints\"}," + + "{\"op\":\"replace\",\"path\":\"/payload/suggestedValue\",\"value\":" + + JsonUtils.pojoToJson( + JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))) + + "},{\"op\":\"add\",\"path\":\"/payload/newOwners\",\"value\":[]}]")); + + Map stored = + JsonUtils.getMap( + SdkClients.adminClient().tasks().get(task.getId().toString(), "*").getPayload()); + assertEquals("Description", stored.get("suggestionType")); + assertEquals(filed, storedPayloadKeys(task)); + assertStillOpen(task); + } + + @Test + void aVoteThatWouldWriteAKeyOutsideTheSchemaIsRefusedWhateverItDecidesAndTheTaskStaysOpen( + TestNamespace ns) { + String workflowName = "constraintVotes" + UUID.randomUUID().toString().substring(0, 8); + JsonNode workflow = createVotingWorkflow(workflowName); + TaskFormSchema form = null; + try { + form = createVotingForm(ns, workflowName, "changeRequestId"); + Table table = ownedTable(ns, "votes"); + Task task = fileForVotes(ns, table, "votes"); + List filed = storedPayloadKeys(task); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + assertThrows( + InvalidRequestException.class, + () -> + vote( + SdkClients.user3Client(), + task, + TaskResolutionType.Rejected, + UUID.randomUUID().toString())) + .getMessage()); + assertEquals(filed, storedPayloadKeys(task)); + assertStillOpen(task); + + assertEquals( + TaskEntityStatus.Open, + vote(SdkClients.user3Client(), task, TaskResolutionType.Rejected, null).getStatus()); + assertEquals(filed, storedPayloadKeys(task)); + assertStillOpen(task); + assertEquals(List.of(), constraintsOf(table)); + + Table approvedTable = ownedTable(ns, "votesapproved"); + Task approving = fileForVotes(ns, approvedTable, "votesapproved"); + vote(SdkClients.user3Client(), approving, TaskResolutionType.Approved, null); + Task approved = vote(SdkClients.adminClient(), approving, TaskResolutionType.Approved, null); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(approvedTable); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + } finally { + if (form != null) { + deleteForm(form); + } + deleteWorkflow(workflow); + } + } + + private static JsonNode createVotingWorkflow(String name) { + ObjectNode workflow; + try (InputStream in = + TaskTableConstraintSuggestionIT.class.getResourceAsStream( + "/json/data/governance/workflows/SuggestionTaskWorkflow.json")) { + workflow = + (ObjectNode) JsonUtils.readTree(new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + workflow.put("name", name).put("displayName", name); + workflow.remove("fullyQualifiedName"); + ObjectNode review = (ObjectNode) workflow.get("nodes").get(1).get("config"); + review.put("approvalThreshold", 2).put("rejectionThreshold", 2); + return JsonUtils.readTree( + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.POST, + "/v1/governance/workflowDefinitions", + JsonUtils.convertValue(workflow, Map.class), + RequestOptions.builder().build())); + } + + private static void deleteWorkflow(JsonNode workflow) { + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.DELETE, + "/v1/governance/workflowDefinitions/" + + workflow.get("id").asText() + + "?hardDelete=true&recursive=true", + null, + RequestOptions.builder().build()); + } + + private static TaskFormSchema createVotingForm( + TestNamespace ns, String workflowName, String valueField) { + return SdkClients.adminClient() + .taskFormSchemas() + .create( + new TaskFormSchema() + .withId(UUID.randomUUID()) + .withName(ns.prefix("form-votes")) + .withTaskType(TaskEntityType.Suggestion.value()) + .withTaskCategory(TaskCategory.Review.value()) + .withWorkflowDefinitionRef(workflowName) + .withFormSchema( + new FormSchema() + .withAdditionalProperty("type", "object") + .withAdditionalProperty("properties", Map.of())) + .withUiSchema( + new UiSchema() + .withAdditionalProperty( + "ui:handler", + Map.of( + "type", + "suggestion", + "permission", + "EditAll", + "valueField", + valueField)))); + } + + /** Files a constraint suggestion for the voting workflow, assigned to two users. */ + private static Task fileForVotes(TestNamespace ns, Table table, String label) { + Task task = + fileConstraintTo( + ns, + TaskCategory.Review, + table, + label, + List.of(SharedEntities.get().USER3.getFullyQualifiedName(), "admin")); + awaitWorkflowTask(task); + return task; + } + + private static Task vote( + OpenMetadataClient client, Task task, TaskResolutionType type, String newValue) { + ResolveTask request = new ResolveTask().withResolutionType(type).withComment("vote"); + if (newValue != null) { + request.setNewValue(newValue); + } + return client.tasks().resolve(task.getId().toString(), request); + } + private static Map withKey( Map payload, String key, Object value) { payload.put(key, value); @@ -892,13 +1079,19 @@ private static void patchTask(Task task, String patch) { private static Task fileConstraint( TestNamespace ns, TaskCategory category, Table table, String label, String assignee) { + return fileConstraintTo( + ns, category, table, label, assignee == null ? null : List.of(assignee)); + } + + private static Task fileConstraintTo( + TestNamespace ns, TaskCategory category, Table table, String label, List assignees) { return fileIn( ns, category, table, label, payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), - assignee == null ? null : List.of(assignee)); + assignees); } private static TaskFormSchema createSuggestionFormFor( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java index 6e6467c06dad..10dcb218e728 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java @@ -1159,7 +1159,6 @@ public Response createOrUpdate( } requireCreatableThroughApi(create); Task task = getTask(create, securityContext.getUserPrincipal().getName()); - TableConstraintSuggestion.requireDeclaredKeys(task); enforceDomainOnlyPolicyForTask(securityContext, task); authorizeCreateTaskOnAboutEntity(securityContext, task); return createOrUpdate(uriInfo, securityContext, task); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java index 2b3d7ad7433e..3f718d768e65 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; @@ -109,13 +110,26 @@ public static void requireDeclaredKeys(Task task) { } /** - * Refuses a resolution whose payload adds a key the suggestion payload does not declare to a - * table constraint suggestion, whatever the resolution is. + * Refuses a resolution that would write a key the suggestion payload does not declare into a + * table constraint suggestion, whatever the resolution is: a key of the request's payload, or the + * form's value field when the request carries a new value. A key the task already stores is not + * the resolution's, so it does not refuse a resolution that adds no key. */ - public static void requireDeclaredKeys(Task task, Object requestPayload) { - if (isTableConstraint(task) && requestPayload != null) { - requireDeclaredKeys(JsonUtils.valueToTree(requestPayload)); + public static void requireNoNewKeys(Task task, Object requestPayload, String newValue) { + if (!isTableConstraint(task)) { + return; + } + ObjectNode added = JsonUtils.getObjectNode(); + if (requestPayload != null) { + JsonUtils.valueToTree(requestPayload) + .fields() + .forEachRemaining(e -> added.set(e.getKey(), e.getValue())); + } + String valueField = TaskFormExecutionResolver.resolve(task).valueField(); + if (newValue != null && valueField != null) { + added.put(valueField, newValue); } + requireDeclaredKeys(added); } public static boolean isTableConstraint(Task task) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index ee937de6b67e..add517220816 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -200,7 +200,7 @@ public Task resolveTask( effectiveResolutionType, user); TaskFieldTarget.requireToApply(task, effectiveResolutionType, resolvedPayload); - TableConstraintSuggestion.requireDeclaredKeys(task, resolvedPayload); + TableConstraintSuggestion.requireNoNewKeys(task, resolvedPayload, newValue); if (isPositiveResolution(effectiveResolutionType)) { TableConstraintSuggestion.requireSameSuggestionType(task, resolvedPayload); TableConstraintSuggestion.requireToApply(task, resolvedPayload, newValue); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java index 4156f84ed060..2e058c5df65c 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -56,10 +56,12 @@ import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.schema.type.TableConstraint.RelationshipType; import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TaskResolutionType; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.governance.approval.ApprovalDecisionService; import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.TableRepository; import org.openmetadata.service.jdbi3.TaskFormSchemaRepository; @@ -458,15 +460,81 @@ void aResolutionPayloadThatAddsAnUndeclaredKey_isRefusedForAConstraintSuggestion KEYS_REFUSED + "changeRequestId", assertThrows( BadRequestException.class, - () -> TableConstraintSuggestion.requireDeclaredKeys(constraintTask, resolution)) + () -> TableConstraintSuggestion.requireNoNewKeys(constraintTask, resolution, null)) .getMessage()); assertDoesNotThrow( () -> - TableConstraintSuggestion.requireDeclaredKeys( - constraintTask, Map.of("source", "User"))); - assertDoesNotThrow(() -> TableConstraintSuggestion.requireDeclaredKeys(constraintTask, null)); + TableConstraintSuggestion.requireNoNewKeys( + constraintTask, Map.of("source", "User"), null)); assertDoesNotThrow( - () -> TableConstraintSuggestion.requireDeclaredKeys(descriptionTask, resolution)); + () -> TableConstraintSuggestion.requireNoNewKeys(constraintTask, null, null)); + assertDoesNotThrow( + () -> TableConstraintSuggestion.requireNoNewKeys(descriptionTask, resolution, null)); + } + + @ParameterizedTest + @EnumSource( + value = TaskResolutionType.class, + names = {"Approved", "Rejected"}) + void aNewValueUnderAnUndeclaredValueField_isRefusedForEveryResolution(TaskResolutionType type) { + boundTo(form(Map.of("type", "suggestion", "valueField", "changeRequestId"), Map.of())); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + BadRequestException refused = + assertThrows( + BadRequestException.class, () -> resolve(task, type, UUID.randomUUID().toString())); + + assertEquals(KEYS_REFUSED + "changeRequestId", refused.getMessage()); + } + + @Test + void aRejectionWithNoNewValueUnderAnUndeclaredValueField_passesTheKeyCheck() { + boundTo(form(Map.of("type", "suggestion", "valueField", "changeRequestId"), Map.of())); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals(DECISION_REACHED, resolveToTheDecision(task, TaskResolutionType.Rejected, null)); + } + + @Test + void aNewValueUnderADeclaredValueField_passesTheKeyCheck() { + boundTo(form(Map.of("type", "suggestion", "valueField", "reasoning"), Map.of())); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals(DECISION_REACHED, resolveToTheDecision(task, TaskResolutionType.Rejected, "why")); + } + + @Test + void aStoredLifecycleMove_doesNotStopARejectionAndStopsApproval() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + payloadOf(task).put("lifecycleMove", "Archive"); + + assertEquals(DECISION_REACHED, resolveToTheDecision(task, TaskResolutionType.Rejected, null)); + assertEquals( + KEYS_REFUSED + "lifecycleMove", + assertThrows( + BadRequestException.class, () -> resolve(task, TaskResolutionType.Approved, null)) + .getMessage()); + } + + private static final String DECISION_REACHED = "the decision was recorded"; + + private static void resolve(Task task, TaskResolutionType type, String newValue) { + TaskWorkflowHandler.getInstance() + .resolveTask(task, null, type, newValue, null, null, "approver"); + } + + /** Runs a resolution up to the point where it would record the resolver's decision. */ + private static String resolveToTheDecision(Task task, TaskResolutionType type, String newValue) { + try (MockedStatic decisions = + mockStatic(ApprovalDecisionService.class)) { + decisions + .when(() -> ApprovalDecisionService.recordForTask(any(), any(), any(), any(), any())) + .thenThrow(new IllegalStateException(DECISION_REACHED)); + resolve(task, type, newValue); + return "the resolution went on"; + } catch (IllegalStateException reached) { + return reached.getMessage(); + } } @SuppressWarnings("unchecked") @@ -722,6 +790,10 @@ void aDescriptionSuggestionUnderTheDefaultForm_isStillAppliedByTheSameCall() thr assertTrue(patch.getValue().toJsonArray().toString().contains("/description")); } + private void boundTo(TaskFormSchema form) { + when(formRepository.resolve(anyString(), any(), any())).thenReturn(Optional.of(form)); + } + private void boundTo(String formName) { TaskFormSchema form = switch (formName) { From 945c70577333193abe4f0a97ff7d9721419ca5dd Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 28 Nov 2026 09:42:58 -0800 Subject: [PATCH 124/203] Record what a constraint suggestion refuses and what a configured workflow does to it --- ...stion-task-can-carry-a-table-constraint.md | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index 5f71a770536d..41bbe7bd9006 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,9 +1,9 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type) - **Deciders:** OpenMetadata maintainers -- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing, patching, replacing and resolving; a task that carries every declared key) +- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply, a new value under a value field outside the schema, a stored key that does not stop a rejection), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing by POST or PUT, patching, resolving and voting, a vote refused without storing its key, a patch that changes the type of a task; a task that carries every declared key) - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type ## Context @@ -34,10 +34,18 @@ declined. `EditAll` on the table and adds the constraint, whatever form the task's category matches. A form's permission, handler and actions apply to other tasks as before. - A constraint suggestion's payload holds only the keys of the suggestion payload schema, so no - other key decides what approving it needs or does. Filing, replacing or patching a task, and a - resolution whose payload adds a key, are refused with a 400 that names each key the schema does - not declare, and approving repeats the check on the merged payload. Keys are compared exactly. - The names come from the generated `SuggestionPayload`, so the rule follows the schema. + other key decides what approving it needs or does. Filing by POST or PUT, patching, and a + resolution of any type whose payload or new value would add a key are refused with a 400 that + names each key the schema does not declare, before anything is recorded or stored. A new value + adds the key that the task form names as its value field, so it is refused when that key is + not declared. The seeded suggestion forms name no value field. A key the task already stores + does not refuse a resolution that adds none, and approving checks the merged payload. Keys are + compared exactly. The names come from the generated `SuggestionPayload`, so the rule follows + the schema. +- A workflow that an administrator configures to write a key into a task's payload, such as a + lifecycle move, makes a constraint suggestion bound to it impossible to approve, because + approving checks the merged payload. The suggestion can still be rejected, and the table stays + unchanged. - Applying patches the table as the approver through the table repository, so its own validation runs. A constraint equal to one already on the table (same type, columns and referred columns) writes nothing and the task still resolves. A second primary key is refused with a 400 naming @@ -45,9 +53,10 @@ declined. a constraint is raised to the caller, unlike the other suggestion types, so a task is never `Approved` for a constraint that was not added. - A resolution cannot change a suggestion task's type to or from `TableConstraint`. Approving is - authorized for the type the task was filed with, so a resolution payload that names another type - would add a constraint on the right to edit something narrower. Such a resolution is refused with - a 400 before the workflow moves, and a change between the other types is as it was. + authorized for the task's current type, which a PATCH of an open task can change, so a resolution + payload that names another type would add a constraint on the right to edit something + narrower. Such a resolution is refused with a 400 before the workflow moves, and a change + between the other types is as it was. - Before the workflow moves, approving runs the table repository's own validation on the table's constraints with the new one added, so a constraint set the write would refuse (for example a foreign key to a table that was deleted) is refused with a 400 while the task is still open and From 3015b23adefa75b280bbba0dd96d227d522074a3 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 28 Nov 2026 09:57:27 -0800 Subject: [PATCH 125/203] Keep the tests that bind a form to review suggestions from running together --- .../it/tests/TaskTableConstraintSuggestionIT.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index cbbab85f3f55..043ad4cc9073 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -34,6 +34,7 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.bootstrap.SharedEntities; import org.openmetadata.it.factories.DatabaseSchemaTestFactory; import org.openmetadata.it.factories.DatabaseServiceTestFactory; @@ -481,16 +482,20 @@ void aCustomTaskCarryingAConstraintPayloadAddsNoConstraintForAUserWhoMayOnlyEdit } } + /** A form is found by its task type and category, so two forms for one pair must not coexist. */ + private static final String REVIEW_FORMS = "suggestionReviewForms"; + private static final String EDIT_ALL_REQUIRED = "Principal: CatalogPrincipal{name='shared_user2'} operations [EditAll] not allowed"; /** * A task form bound to the category of a constraint suggestion can narrow the right to resolve * the task. It cannot narrow the right to add a table constraint: that stays EditAll on the table - * for each way of resolving. No other test files a suggestion of the Review category, so the - * form cannot reach another test's task. + * for each way of resolving. Another test also binds a form to suggestions of the Review + * category, so the two hold {@link #REVIEW_FORMS} and never run together. */ @Test + @ResourceLock(REVIEW_FORMS) void aFormNamingEditDescriptionDoesNotLowerTheRightToApproveAConstraintSuggestion( TestNamespace ns) { String user2 = SharedEntities.get().USER2.getFullyQualifiedName(); @@ -887,6 +892,7 @@ void aPatchThatTurnsADescriptionSuggestionIntoAConstraintCannotAddAKey(TestNames } @Test + @ResourceLock(REVIEW_FORMS) void aVoteThatWouldWriteAKeyOutsideTheSchemaIsRefusedWhateverItDecidesAndTheTaskStaysOpen( TestNamespace ns) { String workflowName = "constraintVotes" + UUID.randomUUID().toString().substring(0, 8); From bb076e009593557c1c86f6d68b489b3728761745 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 28 Nov 2026 12:59:14 -0800 Subject: [PATCH 126/203] Regenerate the UI's TypeScript types for table constraint suggestions --- .../resources/ui/src/generated/type/suggestionPayload.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/suggestionPayload.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/suggestionPayload.ts index 628a22bfa22d..cef1a67ed4cd 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/type/suggestionPayload.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/suggestionPayload.ts @@ -26,6 +26,7 @@ export interface SuggestionPayload { * Path to the property being updated. For a Description or Tag suggestion it is written as * .[....]., for example * 'columns.customer_id.description', or 'description' / 'tags' alone for the entity itself. + * A TableConstraint suggestion's path is 'tableConstraints'. */ fieldPath: string; /** @@ -37,7 +38,10 @@ export interface SuggestionPayload { */ source?: Source; /** - * Suggested new value for the field. + * Suggested new value for the field. For a TableConstraint suggestion it is one + * tableConstraint object written as JSON: its constraintType (PRIMARY_KEY, UNIQUE or + * FOREIGN_KEY), its columns, and for a foreign key its referredColumns as full column names + * and its relationshipType. */ suggestedValue: string; /** @@ -64,6 +68,7 @@ export enum SuggestionType { Description = "Description", Domain = "Domain", Owner = "Owner", + TableConstraint = "TableConstraint", Tag = "Tag", Tier = "Tier", } From cee7432c34a4b60ff406170a20099a7f6f91c53e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 28 Nov 2026 15:56:26 -0800 Subject: [PATCH 127/203] Regenerate the UI's TypeScript types for the paged expand statement --- .../data/ontologyAggregateStatementRequest.ts | 34 ++++++++++++------- .../data/ontologyExpandStatementRequest.ts | 16 ++++++++- .../api/data/ontologyStatementPlan.ts | 30 +++++++++++----- 3 files changed, 59 insertions(+), 21 deletions(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts index 74f6d03c327c..b900aaaad90d 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyAggregateStatementRequest.ts @@ -13,12 +13,17 @@ /** * Asks for a counting statement. Without a relation it counts the records of the class. * With a relation and a direction it returns, by default, the 8 records of the class that - * relate to the most records along that relation, each with its count. With the measure - * `linkCount` it returns one number, the links of the relation. A link is a pair of a - * record of the class that binds the relation and an object key with no null part. Forward - * from the binding class the count is every link. Inverse from the other class it is the - * links whose object is a record of the class asked, and the row filter of the object class - * applies only when the count starts from it. + * relate to the most records along that relation, each with its count. Each record's number + * counts its joined rows, so a pair that two rows hold counts twice. In either direction + * the related record must exist, with a whole key, and pass the row filter of its class, + * which a forward link count does not ask. So the numbers need not add up to `linkCount`. + * With the measure `linkCount` it returns one number, the links of the relation. A link is + * a pair of a record of the class that binds the relation and an object key with no null + * part. The record passes the row filter of its class, and a row of a link table or another + * contributing table counts only when it passes that table's own row filter. Forward from + * the binding class the count is every link. The object need not be a record. Inverse from + * the other class it is the links whose object is a record of the class asked, and the row + * filter of the object class applies only when the count starts from it. */ export interface OntologyAggregateStatementRequest { direction?: Direction; @@ -54,12 +59,17 @@ export enum Direction { * takes one, and a request that names none counts `topRecords`. * * What an aggregate over a relation counts. `topRecords` returns the 8 records of the class - * that relate to the most records along the relation, each with its count. `linkCount` - * returns one number, the links of the relation. A link is a pair of a record of the class - * that binds the relation and an object key with no null part. Forward from the binding - * class the count is every link. Inverse from the other class it is the links whose object - * is a record of the start class, and the object need not be a record when the count starts - * from the binding class. A request that names none asks for `topRecords`. + * that relate to the most records along the relation, each with its count. Each record's + * number counts its joined rows, so a pair that two rows hold counts twice. In either + * direction the related record must exist, with a whole key, and pass the row filter of its + * class, which a forward link count does not ask. So the numbers need not add up to + * `linkCount`. `linkCount` returns one number, the links of the relation. A link is a pair + * of a record of the class that binds the relation and an object key with no null part. The + * record passes the row filter of its class, and a row of a link table or another + * contributing table counts only when it passes that table's own row filter. Forward from + * the binding class the count is every link. Inverse from the other class it is the links + * whose object is a record of the start class, and the object need not be a record when the + * count starts from the binding class. A request that names none asks for `topRecords`. */ export enum Measure { LinkCount = "linkCount", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyExpandStatementRequest.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyExpandStatementRequest.ts index 6650caaf7e5a..451e44f5b23d 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyExpandStatementRequest.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyExpandStatementRequest.ts @@ -12,9 +12,23 @@ */ /** * Asks for the statement that lists the records one record relates to along one relation. - * The statement asks for 26 rows, and the 26th says only that more exist. + * The statement asks for 26 rows, and the 26th says only that more exist. It orders the + * related records by their key, so a client reads the next page by sending the key of the + * last related record it holds as `after`. The engine compares and orders with its own + * collation, so a client must not merge pages that came from two connections. */ export interface OntologyExpandStatementRequest { + /** + * The key of the last related record the client holds, in the key order of the related + * class, typed as `key` is: one value for each column of the related key, each parsed as + * the data type of its column. The statement then returns the related records whose key + * comes after it. Leave it out, or send an empty list, to start at the first related + * record. A value of the wrong type for its column, or a number of values other than the + * key has, is a 400. Two keys that the engine's collation holds equal compare as one key, + * such as `x` and `X` under MySQL's default collation, so a page that ends on one of them + * starts after both and the other is skipped. + */ + after?: any[]; direction: Direction; key: any[]; /** diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts index 5274b0449cfd..84ae98fd462c 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyStatementPlan.ts @@ -44,8 +44,17 @@ export interface OntologyStatementPlan { * What an aggregate over a relation counts. Absent on every other statement, including the * count of a class. */ - measure?: Measure; - relation?: Relation; + measure?: Measure; + /** + * The indexes of the result columns that hold the key of the related record, in key order, + * for a client to send the values of these columns in the last row it keeps as `after` and + * read the next page. Only an `expand` statement sets it, and only when every column of its + * related key has a type the generator writes values for, such as a number or a string and + * not JSON. Every other statement leaves it empty, `topRecords` too, though it orders by + * its count. An empty list means the statement takes no `after`. + */ + orderedBy?: number[]; + relation?: Relation; /** * The most rows a reader takes from the result. `find` and `expand` take 25, `open` takes * 100, a relation count takes 8, and a class count and a link count take 1. @@ -162,12 +171,17 @@ export enum EngineFamily { * count of a class. * * What an aggregate over a relation counts. `topRecords` returns the 8 records of the class - * that relate to the most records along the relation, each with its count. `linkCount` - * returns one number, the links of the relation. A link is a pair of a record of the class - * that binds the relation and an object key with no null part. Forward from the binding - * class the count is every link. Inverse from the other class it is the links whose object - * is a record of the start class, and the object need not be a record when the count starts - * from the binding class. A request that names none asks for `topRecords`. + * that relate to the most records along the relation, each with its count. Each record's + * number counts its joined rows, so a pair that two rows hold counts twice. In either + * direction the related record must exist, with a whole key, and pass the row filter of its + * class, which a forward link count does not ask. So the numbers need not add up to + * `linkCount`. `linkCount` returns one number, the links of the relation. A link is a pair + * of a record of the class that binds the relation and an object key with no null part. The + * record passes the row filter of its class, and a row of a link table or another + * contributing table counts only when it passes that table's own row filter. Forward from + * the binding class the count is every link. Inverse from the other class it is the links + * whose object is a record of the start class, and the object need not be a record when the + * count starts from the binding class. A request that names none asks for `topRecords`. */ export enum Measure { LinkCount = "linkCount", From c39f8c472d326a78a427df7ad80ed7776f33f77d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 28 Nov 2026 23:00:39 -0800 Subject: [PATCH 128/203] Read the first level of the ancestor walk in chunks and test both halves of its bound --- .../jdbi3/OntologyConceptBindingStore.java | 21 +-- ...ologyConceptBindingStoreAncestorsTest.java | 166 +++++++++++++++++- 2 files changed, 176 insertions(+), 11 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 748daaa58504..fc4d7fa48c0b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -8,6 +8,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -414,24 +415,24 @@ public Set ancestors(final OntologyConcept concept) { /** * The named parents of every class that a walk up from {@code starts} reaches, by the IRI of the * class. One statement reads each level for the whole frontier, so the statements are one per - * level whatever the number of starts. The walk is bound as a whole, by the classes it finds above - * the starts and by the axioms it reads. The starts themselves are not counted. + * level whatever the number of starts, except that a first level longer than one IN list is read + * in chunks, in the order of the starts. The walk is bound as a whole, chunks included, by the + * classes it finds above the starts and by the axioms it reads. The starts themselves are not + * counted. */ public Map> namedParentsAbove( final UUID ontologyId, final Collection starts) { final Map> parents = new HashMap<>(); - final Set visited = new HashSet<>(starts); + final Set visited = new LinkedHashSet<>(starts); final int startCount = visited.size(); - Set pending = Set.copyOf(visited); + Set pending = new LinkedHashSet<>(visited); int traversed = 0; while (!pending.isEmpty()) { final var axioms = - dao.ontologyReferenceDAO() - .ancestors( - ontologyId, - pending.stream().map(DigestUtils::sha256Hex).toList(), - MAX_ANCESTORS + 1, - ""); + EntityDAO.queryInChunks( + pending.stream().map(DigestUtils::sha256Hex).toList(), + chunk -> + dao.ontologyReferenceDAO().ancestors(ontologyId, chunk, MAX_ANCESTORS + 1, "")); traversed += axioms.size(); requireBound(Math.max(visited.size() - startCount, traversed)); pending = levelAbove(axioms, pending, visited, parents); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java index 3ab1352fd24b..49f04dd2ba14 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java @@ -25,6 +25,7 @@ import java.net.URI; import java.util.ArrayList; import java.util.Comparator; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -59,6 +60,7 @@ class OntologyConceptBindingStoreAncestorsTest { private static final class Axioms { private final List stored = new ArrayList<>(); private final AtomicInteger statements = new AtomicInteger(); + private final AtomicInteger mostHashes = new AtomicInteger(); private final OntologyConceptBindingStore store; private record Stored(String name, String subjectHash, String json) {} @@ -71,7 +73,9 @@ private record Stored(String name, String subjectHash, String json) {} .thenAnswer( call -> { statements.incrementAndGet(); - final List hashes = call.getArgument(1); + final List asked = call.getArgument(1); + mostHashes.accumulateAndGet(asked.size(), Math::max); + final Set hashes = new HashSet<>(asked); final int limit = call.getArgument(2); return stored.stream() .filter(axiom -> hashes.contains(axiom.subjectHash())) @@ -102,6 +106,28 @@ Axioms subclass(final String name, final String child, final String parent) { return this; } + /** One axiom that puts {@code child} under every one of {@code parents}. */ + Axioms subclassOfAll(final String name, final String child, final List parents) { + final OntologyAxiom axiom = + new OntologyAxiom() + .withId(UUID.randomUUID()) + .withName(name) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(iri(child)) + .withExpressions( + parents.stream() + .map( + parent -> + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(iri(parent))) + .toList()); + stored.add( + new Stored( + name, DigestUtils.sha256Hex(iri(child).toString()), JsonUtils.pojoToJson(axiom))); + return this; + } + /** {@code length} single-parent steps above {@code bottom}, each class named for its step. */ Axioms chain(final String bottom, final int length) { String child = bottom; @@ -125,6 +151,10 @@ Map> above(final String... starts) { int statements() { return statements.get(); } + + int mostHashesInAStatement() { + return mostHashes.get(); + } } private static URI iri(final String name) { @@ -200,6 +230,140 @@ void oneStartUnderAChainOf9999AxiomsHasAnAncestorSetOfExactlyTheBound() { assertEquals(10_000, axioms.ancestors("Start").size()); } + private static String step(final int index) { + return index == 0 ? "Start" : "StartAbove" + index; + } + + /** The chain of 5,999 steps over Start, and {@code skips} axioms that put step i under i + 2. */ + private static Axioms chainWithSkips(final int skips) { + final Axioms axioms = new Axioms().chain("Start", 5_999); + for (int i = 0; i < skips; i++) { + axioms.subclass("Skip" + i, step(i), step(i + 2)); + } + return axioms; + } + + /** 5,999 classes above Start, 5,999 + 4,002 = 10,001 axioms: over the bound by the axioms. */ + @Test + void oneStartWithMoreAxiomsThanClassesAboveItIsRefusedByTheAxioms() { + final Axioms axioms = chainWithSkips(4_002); + + final BadRequestException refusedAbove = + assertThrows(BadRequestException.class, () -> axioms.above("Start")); + final BadRequestException refusedAncestors = + assertThrows(BadRequestException.class, () -> axioms.ancestors("Start")); + + assertEquals(REFUSED, refusedAbove.getMessage()); + assertEquals(REFUSED, refusedAncestors.getMessage()); + } + + /** The same 5,999 classes above Start and 10,000 axioms: at the bound, answered. */ + @Test + void oneStartWithExactlyTheBoundInAxiomsAndFewerClassesAboveItIsWalked() { + final Axioms axioms = chainWithSkips(4_001); + + assertEquals(5_999, axioms.above("Start").size()); + assertEquals(6_000, axioms.ancestors("Start").size()); + } + + /** 10,001 starts with one axiom each under one class: 1 class above, 10,001 axioms in one read. */ + @Test + void startsWhoseAxiomsAreMoreThanTheBoundAreRefusedAfterTheFirstStatement() { + final Axioms axioms = new Axioms(); + final List starts = new ArrayList<>(); + for (int i = 0; i < 10_001; i++) { + starts.add("Sharing" + i); + axioms.subclass("Axiom" + i, "Sharing" + i, "Named"); + } + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> axioms.above(starts.toArray(String[]::new))); + + assertEquals(REFUSED, refused.getMessage()); + assertEquals(1, axioms.statements()); + } + + /** Two axioms of 5,001 named parents each: 10,002 classes in the one level, refused at once. */ + @Test + void aLevelOfMoreClassesThanTheBoundIsRefusedBeforeAnotherStatementIsAsked() { + final List first = new ArrayList<>(); + final List second = new ArrayList<>(); + for (int i = 0; i < 5_001; i++) { + first.add("ParentA" + i); + second.add("ParentB" + i); + } + final Axioms axioms = + new Axioms() + .subclassOfAll("AxiomA", "Start", first) + .subclassOfAll("AxiomB", "Start", second); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> axioms.above("Start")); + + assertEquals(REFUSED, refused.getMessage()); + assertEquals(1, axioms.statements()); + } + + /** 30,001 starts, a chunk of 30,000 and one more. 5,001 of them are under Named: 1 class above. */ + @Test + void startsLongerThanOneChunkAreReadInChunksAndWalkedOnce() { + final Axioms axioms = new Axioms(); + final String[] starts = new String[CHUNK + 1]; + for (int i = 0; i <= CHUNK; i++) { + starts[i] = "Sharing" + i; + } + for (int i = 0; i < 5_000; i++) { + axioms.subclass("Axiom" + i, "Sharing" + i, "Named"); + } + axioms.subclass("AxiomLast", "Sharing" + CHUNK, "Named"); + + final Map> parents = axioms.above(starts); + + assertEquals(5_001, parents.size()); + assertEquals(Set.of(iri("Named").toString()), parents.get(iri("Sharing30000").toString())); + assertEquals(30_000, axioms.mostHashesInAStatement()); + assertEquals(3, axioms.statements()); + } + + /** + * The first chunk of starts holds 9,999 axioms and the last start, alone in the second chunk, 1: + * 10,000 axioms in two statements, which the bound allows. With 2 on the last start the two + * chunks together hold 10,001, though neither is over the limit of its own statement. + */ + @Test + void theChunksOfTheFirstLevelAreBoundTogether() { + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> chunkedStarts(2).above(chunkedStartNames())); + final Axioms control = chunkedStarts(1); + + assertEquals(REFUSED, refused.getMessage()); + assertEquals(1, control.above(chunkedStartNames()).get(iri("Last").toString()).size()); + assertEquals(3, control.statements()); + } + + private static final int CHUNK = 30_000; + + private static String[] chunkedStartNames() { + final String[] starts = new String[CHUNK + 1]; + for (int i = 0; i < CHUNK; i++) { + starts[i] = "Sharing" + i; + } + starts[CHUNK] = "Last"; + return starts; + } + + /** 9,999 starts of the first chunk have an axiom each, and Last, in the second, {@code last}. */ + private static Axioms chunkedStarts(final int last) { + final Axioms axioms = new Axioms(); + for (int i = 0; i < 9_999; i++) { + axioms.subclass("Axiom" + i, "Sharing" + i, "Named"); + } + for (int i = 0; i < last; i++) { + axioms.subclass("Last" + i, "Last", "Named" + i); + } + return axioms; + } + @Test void twoChainsThatMeetAreWalkedInThreeStatements() { final Axioms axioms = twoParentsThatMeet(); From befbb1ac5c5504b16310372706e597a753b4a250 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 28 Nov 2026 23:05:36 -0800 Subject: [PATCH 129/203] Test a sharing class whose first parent leads to the named class --- .../it/tests/OntologyShapeCheckReadsIT.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index 59e2edf0aace..9629d68e07fb 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -632,6 +632,33 @@ void aDraftWhoseSharingClassReachesTheNamedClassOnlyThroughItsSecondParentWalksB assertDraftReads(second, 3); } + /** + * The same two parents with the order reversed: the parent that leads to the named class has the + * axiom whose name sorts first, so it is read first and the dead end second. The answer and the + * statements are those of the case above, whichever parent is read first. + */ + @Test + void aDraftWhoseSharingClassReachesTheNamedClassThroughItsFirstParentAlsoWalksBothParents( + final TestNamespace ns) { + final Reads first = + sharedBy( + ns, + "firstParent", + DRAFT, + (ontology, fixture) -> { + final OntologyConcept sharer = sharesTable(fixture, "Sharer", "products"); + subclassOf(ontology, sharer, fixture.type("AParent")); + subclassOf(ontology, sharer, fixture.type("BParent")); + subclassOf(ontology, fixture.type("AParent"), fixture.type("Product")); + subclassOf(ontology, fixture.type("BParent"), fixture.type("Elsewhere")); + }); + + assertEquals( + SHARED_BY_CHAINS_THAT_MEET_DRAFT_STATEMENTS, first.statements().size(), first::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(first).getReason()); + assertDraftReads(first, 3); + } + /** * A class of another ontology has the IRI of a subclass of Product and binds the filtered table. * It is no candidate, so the class part is checked. From 88b1a1dafd6d79bbdb4c86591e396ae83285d176 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 28 Nov 2026 23:05:41 -0800 Subject: [PATCH 130/203] State the chunked first level and the axiom bound of the walk in the shape check record --- ...ape-check-is-exact-or-it-is-not-offered.md | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md index a52ea3b16bcb..212395947675 100644 --- a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) · v4 2026-11-25 (the statements do not grow with the classes a `class` part names, a filtered one included) · v5 2026-11-26 (the subclass question walks the ancestors of all the sharing classes together, and its bound leaves the sharing classes out) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads, and the cost of the subclass question), `OntologyConceptBindingFirstRowsIT` (the cap of the first rows is per table), `OntologyConceptBindingStoreAncestorsTest` (the bound of the walk, the statements of chains that meet, and a class under two classes), `OntologyConceptBindingsIT` (a property of a class reached only through a second parent is applicable) +- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads, the cost of the subclass question, and a sharing class whose second parent leads to the named class, read second and first), `OntologyConceptBindingFirstRowsIT` (the cap of the first rows is per table), `OntologyConceptBindingStoreAncestorsTest` (both halves of the bound of the walk, the classes above the starts and the axioms read, the level of more than 10,000 classes, a first level of more starts than one chunk holds and the bound across its chunks, the statements of chains that meet, and a class under two classes), `OntologyConceptBindingsIT` (a property of a class reached only through a second parent is applicable) - **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) ## Context @@ -402,12 +402,16 @@ rows counts the rows of one table and not of all the tables a call reads, and another holds one subclass. The walk is bound once for all the sharing classes together, at 10,000. It counts the classes it -finds above the sharing classes and the axioms it reads. It does not count the sharing classes -themselves, so the bound does not shrink with the number of them. Binding inheritance counts as it -did: the class and the classes above it, 10,000 at most. A draft whose sharing classes have more than -10,000 classes or axioms above them together answers 400, where its release answers, because a -release holds no such bound. The reads test asserts 53 statements from a draft where a sharing -class reaches the named class both directly and through a longer chain, because the class that both -chains reach is asked for once, and where it reaches the named class only through its second parent, -and 50 where the only class on the table is one of another ontology, which is no candidate and -leaves nothing to walk. +finds above the sharing classes and the axioms it reads, whichever is larger. It does not count the +sharing classes themselves, so the bound does not shrink with the number of them. The first level +reads its starts in chunks of one IN list, so that Postgres, which refuses more than 65,535 +parameters in a statement, and MySQL answer the same draft the same way, and the bound counts the +chunks together. A level of more than 10,000 classes is refused at once, before the next statement. +Binding inheritance counts as it did: the class and the classes above it, 10,000 at most, and it +also refuses more than 10,000 axioms read. A draft whose sharing classes have more than 10,000 +classes or axioms above them together answers 400, where its release answers, because a release +holds no such bound. The reads test asserts 53 statements from a draft where a sharing class +reaches the named class both directly and through a longer chain, because the class that both +chains reach is asked for once, and where it reaches the named class only through its second +parent, read second and read first, and 50 where the only class on the table is one of another +ontology, which is no candidate and leaves nothing to walk. From c156e5db817c4123a6c2e40bf61be94ede79b8d2 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 29 Nov 2026 17:05:53 -0800 Subject: [PATCH 131/203] Test that the chunks of the first level are bound together when no new class follows --- ...ologyConceptBindingStoreAncestorsTest.java | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java index 49f04dd2ba14..943a8be088f8 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java @@ -61,6 +61,7 @@ private static final class Axioms { private final List stored = new ArrayList<>(); private final AtomicInteger statements = new AtomicInteger(); private final AtomicInteger mostHashes = new AtomicInteger(); + private final AtomicInteger lastHashes = new AtomicInteger(); private final OntologyConceptBindingStore store; private record Stored(String name, String subjectHash, String json) {} @@ -75,6 +76,7 @@ private record Stored(String name, String subjectHash, String json) {} statements.incrementAndGet(); final List asked = call.getArgument(1); mostHashes.accumulateAndGet(asked.size(), Math::max); + lastHashes.set(asked.size()); final Set hashes = new HashSet<>(asked); final int limit = call.getArgument(2); return stored.stream() @@ -155,6 +157,10 @@ int statements() { int mostHashesInAStatement() { return mostHashes.get(); } + + int hashesInTheLastStatement() { + return lastHashes.get(); + } } private static URI iri(final String name) { @@ -326,19 +332,28 @@ void startsLongerThanOneChunkAreReadInChunksAndWalkedOnce() { } /** - * The first chunk of starts holds 9,999 axioms and the last start, alone in the second chunk, 1: - * 10,000 axioms in two statements, which the bound allows. With 2 on the last start the two - * chunks together hold 10,001, though neither is over the limit of its own statement. + * Every parent is a start, so the first level finds no new class and no level follows. The first + * chunk of starts holds 9,999 axioms and the last start, alone in the second chunk, 1 or 2: + * 10,000 axioms in two statements, which the bound allows, or 10,001, which it does not, though + * neither chunk is over the limit of its own statement. */ @Test void theChunksOfTheFirstLevelAreBoundTogether() { - final BadRequestException refused = - assertThrows(BadRequestException.class, () -> chunkedStarts(2).above(chunkedStartNames())); + final Axioms refusing = chunkedStarts(2); final Axioms control = chunkedStarts(1); + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> refusing.above(chunkedStartNames())); + final Map> parents = control.above(chunkedStartNames()); + assertEquals(REFUSED, refused.getMessage()); - assertEquals(1, control.above(chunkedStartNames()).get(iri("Last").toString()).size()); - assertEquals(3, control.statements()); + assertEquals(2, refusing.statements()); + assertEquals(1, refusing.hashesInTheLastStatement()); + assertEquals(2, control.statements()); + assertEquals(10_000, parents.size()); + assertEquals(Set.of(iri("X1").toString()), parents.get(iri("X0").toString())); + assertEquals(Set.of(iri("X9999").toString()), parents.get(iri("X9998").toString())); + assertEquals(Set.of(iri("X0").toString()), parents.get(iri("Last").toString())); } private static final int CHUNK = 30_000; @@ -346,20 +361,20 @@ void theChunksOfTheFirstLevelAreBoundTogether() { private static String[] chunkedStartNames() { final String[] starts = new String[CHUNK + 1]; for (int i = 0; i < CHUNK; i++) { - starts[i] = "Sharing" + i; + starts[i] = "X" + i; } starts[CHUNK] = "Last"; return starts; } - /** 9,999 starts of the first chunk have an axiom each, and Last, in the second, {@code last}. */ + /** X(i) is under X(i+1) for the 9,999 axioms of the first chunk, and Last, alone in the second, under {@code last} of them. */ private static Axioms chunkedStarts(final int last) { final Axioms axioms = new Axioms(); for (int i = 0; i < 9_999; i++) { - axioms.subclass("Axiom" + i, "Sharing" + i, "Named"); + axioms.subclass("Axiom" + i, "X" + i, "X" + (i + 1)); } for (int i = 0; i < last; i++) { - axioms.subclass("Last" + i, "Last", "Named" + i); + axioms.subclass("Last" + i, "Last", "X" + i); } return axioms; } From 9876ea2678622cbcacf5028f0ebbd37d70215516 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 29 Nov 2026 17:41:25 -0800 Subject: [PATCH 132/203] Regenerate the UI's TypeScript types for the shape checks of a class --- .../generated/api/data/ontologyShapeChecks.ts | 352 ++++++++++++++++++ 1 file changed, 352 insertions(+) create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyShapeChecks.ts diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyShapeChecks.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyShapeChecks.ts new file mode 100644 index 000000000000..5f5ac26467d1 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyShapeChecks.ts @@ -0,0 +1,352 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * How each constraint of the shapes that target a class is checked on the tables the class + * binds. A constraint is answered part by part: by a data quality test that finds a + * violation exactly when a record breaks the part, by nothing because the mapping already + * holds it, or not at all, and then with the reason. Nothing is created, scheduled or run + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). + */ +export interface OntologyShapeChecks { + /** + * IRI of the class. + */ + classIri: string; + /** + * Id of the class. + */ + conceptId: string; + /** + * The shapes of that version that target the class and that the caller may view, in name + * order. A shape that targets a parent of the class is not listed. + */ + shapes: CheckedShape[]; + /** + * The version of the ontology that the class, its shapes and its properties were read from. + * Table bindings sit outside versions and are always current. + */ + version: VersionRead; +} + +/** + * One shape that targets the class. + */ +export interface CheckedShape { + /** + * The constraints of the shape, in the order the shape holds them. + */ + constraints: CheckedConstraint[]; + /** + * Id of the shape. + */ + id: string; + /** + * Name of the shape. + */ + name: string; + severity: Severity; +} + +/** + * One constraint of a shape with the answer for each part it states. + */ +export interface CheckedConstraint { + /** + * Id of the constraint within its shape. + */ + id: string; + /** + * The parts the constraint states, in the order `minCount`, `maxCount`, `class`, + * `datatype`, `range`, `in`, `pattern`. + */ + parts: CheckedPart[]; + /** + * IRI of the property the constraint is about. Absent when the caller may not view that + * property. + */ + path?: string; +} + +/** + * How one part of a constraint is checked. When the class binds the property in several + * tables and they do not all give the same answer, the part has one entry for each answer. + */ +export interface CheckedPart { + /** + * One test for each table. Present exactly when the outcome is `check`. + */ + checks?: Check[]; + outcome: Outcome; + part: Part; + /** + * Present exactly when the outcome is `notEnforceable`. + */ + reason?: Reason; +} + +/** + * One data quality test on one table: the test `tableCustomSQLQuery` with a statement + * written for the part. `testDefinition`, `entityLink` and `parameterValues` are what a + * request to create a test case takes. The result of the test is 0 violations exactly when + * every record of the class satisfies the part. + */ +export interface Check { + /** + * The columns of that table that hold the values the test reads: the bound column of a data + * property, or the columns of the join of a relation. + */ + columns: Array; + /** + * The table that the test is created on. + */ + entityLink: string; + /** + * Lowercase hex SHA-256 of the shape id, the constraint id, the part, the class id, the + * table id and the bound column path. It names the check and does not depend on a value of + * the constraint, so a changed bound keeps it. + */ + identity: string; + /** + * The statement that lists the keys of the records in violation, for a person to read. + */ + inspectionQuery: string; + /** + * The parameters of the test: the statement in `sqlExpression`, with every colon written as + * a backslash and a colon, then `strategy` `COUNT`, `operator` `<=` and `threshold` `0`. + * The statement returns one number, the records in violation. + */ + parameterValues: TestCaseParameterValue[]; + /** + * Every table binding the check read: the identity table of the class, the table that holds + * the property, and the identity table of the class a `class` part names. All revisions + * come from one consistent read. + */ + readBindings: ReadBinding[]; + /** + * The table the test belongs to: the one whose binding holds the property, which is a link + * table when a link table holds a relation. + */ + table: EntityReference; + /** + * Fully qualified name of the test definition, which is `tableCustomSQLQuery` for every + * check. + */ + testDefinition: string; +} + +/** + * This schema defines the parameter values that can be passed for a Test Case. + */ +export interface TestCaseParameterValue { + /** + * name of the parameter. Must match the parameter names in testCaseParameterDefinition + */ + name?: string; + /** + * value to be passed for the Parameters. These are input from Users. We capture this in + * string and convert during the runtime. + */ + value?: string; + [property: string]: any; +} + +/** + * One table binding that a check was built from, with the binding revision of its class. + */ +export interface ReadBinding { + /** + * Id of the bound table. + */ + assetId: string; + /** + * Id of the class that binds the table. + */ + conceptId: string; + /** + * Revision of the bindings of the class, as the bindings endpoint returns it. + */ + revision: number; +} + +/** + * The table the test belongs to: the one whose binding holds the property, which is a link + * table when a link table holds a relation. + * + * This schema defines the EntityReference type used for referencing an entity. + * EntityReference is used for capturing relationships from one entity to another. For + * example, a table has an attribute called database of type EntityReference that captures + * the relationship of a table `belongs to a` database. + */ +export interface EntityReference { + /** + * If true the entity referred to has been soft-deleted. + */ + deleted?: boolean; + /** + * Optional description of entity. + */ + description?: string; + /** + * Display Name that identifies this entity. + */ + displayName?: string; + /** + * Fully qualified name of the entity instance. For entities such as tables, databases + * fullyQualifiedName is returned in this field. For entities that don't have name hierarchy + * such as `user` and `team` this will be same as the `name` field. + */ + fullyQualifiedName?: string; + /** + * Link to the entity resource. + */ + href?: string; + /** + * Unique identifier that identifies an entity instance. + */ + id: string; + /** + * If true the relationship indicated by this entity reference is inherited from the parent + * entity. + */ + inherited?: boolean; + /** + * Name of the entity instance. + */ + name?: string; + /** + * Entity type/class name - Examples: `database`, `table`, `metrics`, `databaseService`, + * `dashboardService`... + */ + type: string; +} + +/** + * How a part is checked. `check` carries the tests that check it. `heldByMapping` needs no + * test, because the table bindings already hold the part for every record. `notMapped` + * means the class binds the property in no column, or the version read has no such + * property. `notEnforceable` means no test finds exactly the records that break the part, + * and `reason` says why. `hidden` means the caller may not view a table the answer rests + * on, or the property the constraint is about. + */ +export enum Outcome { + Check = "check", + HeldByMapping = "heldByMapping", + Hidden = "hidden", + NotEnforceable = "notEnforceable", + NotMapped = "notMapped", +} + +/** + * One part of a constraint. `range` is `minInclusive` and `maxInclusive` together. + */ +export enum Part { + Class = "class", + Datatype = "datatype", + In = "in", + MaxCount = "maxCount", + MinCount = "minCount", + Pattern = "pattern", + Range = "range", +} + +/** + * Present exactly when the outcome is `notEnforceable`. + * + * Why a part has no exact test. `noIdentityTable`: the class binds the property and has no + * identity table, so it has no records. `severalTables`: the class binds the property in + * several columns, and a count over all of them has no test. `boundOnInverse`: the class + * does not bind the relation and another class binds its inverse. `noJoin` and + * `joinNotConfirmed`: the relation has no join, or one that is only inferred. + * `notARelation` and `notADataProperty`: the part asks for the other kind of property. + * `targetClassNotOnJoin`: the class the part names has no identity table where the join + * arrives. `subclassOnJoinTable`: a subclass of that class has its identity table there + * too, and the filter of the class would leave its records out. `valuesAreRecords`: the + * list names records by IRI. `valueDoesNotFitColumn`: a value does not parse as the data + * type of the column. `tooManyValues`: the list has more than 1,000 values. + * `columnTypeNotSupported`: the data type of the column takes no such comparison. + * `datatypeNotSupported`: the datatype is not one this answer reads. `datatypeMismatch`: + * nothing shows that every value the column can store is of the datatype, because its data + * type stores other values on this engine or was not read for it. `patternNotPortable`: the + * pattern leaves the constructs that are known to be read as SHACL reads them, or is too + * long for a statement. `columnMissing`: a column of the binding left the table. + * `otherDatabase`: a table sits in another database than the identity table. + * `engineNotSupported`: no statement is written for the service type, or none that asks + * this part. A pattern is matched on Postgres only. + */ +export enum Reason { + BoundOnInverse = "boundOnInverse", + ColumnMissing = "columnMissing", + ColumnTypeNotSupported = "columnTypeNotSupported", + DatatypeMismatch = "datatypeMismatch", + DatatypeNotSupported = "datatypeNotSupported", + EngineNotSupported = "engineNotSupported", + JoinNotConfirmed = "joinNotConfirmed", + NoIdentityTable = "noIdentityTable", + NoJoin = "noJoin", + NotADataProperty = "notADataProperty", + NotARelation = "notARelation", + OtherDatabase = "otherDatabase", + PatternNotPortable = "patternNotPortable", + SeveralTables = "severalTables", + SubclassOnJoinTable = "subclassOnJoinTable", + TargetClassNotOnJoin = "targetClassNotOnJoin", + TooManyValues = "tooManyValues", + ValueDoesNotFitColumn = "valueDoesNotFitColumn", + ValuesAreRecords = "valuesAreRecords", +} + +/** + * How serious a failed constraint is, as SHACL defines the severities. + */ +export enum Severity { + Info = "Info", + Violation = "Violation", + Warning = "Warning", +} + +/** + * The version of the ontology that the class, its shapes and its properties were read from. + * Table bindings sit outside versions and are always current. + * + * The version of the ontology that the statement was built from. + */ +export interface VersionRead { + kind: Version; + /** + * Id of the active release, when the statement read a release. + */ + releaseId?: string; + /** + * Release number of that release. + */ + releaseRevision?: number; + /** + * Semantic version of that release. Absent on a release that has none. + */ + semanticVersion?: string; + /** + * Working revision of the ontology, when the statement read the draft. + */ + workingRevision?: number; +} + +/** + * Which version of the ontology a statement reads. `release` is the active release. `draft` + * is the working draft, and reading it takes `EditAll` on the ontology. The class, its + * properties, the display name flag and the relations come from that version. Bindings sit + * outside versions and are always current. + */ +export enum Version { + Draft = "draft", + Release = "release", +} From 42d9b1c163b462e6742cb07f944daaa9cf8729e1 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 29 Nov 2026 21:21:19 -0800 Subject: [PATCH 133/203] Restore a bot user's default role only when the user holds no role --- .../migration/utils/v1114/MigrationUtil.java | 13 +- .../utils/v1114/MigrationUtilTest.java | 179 ++++++++++++++++++ 2 files changed, 187 insertions(+), 5 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v1114/MigrationUtil.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v1114/MigrationUtil.java index 61b3d3552f60..85c0ae6b2b16 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v1114/MigrationUtil.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v1114/MigrationUtil.java @@ -207,6 +207,10 @@ public static void restoreBotRelationshipsIfMissing( * Restores bot user role relationships that were deleted by the Flyway migration issue. The v004 * migration deletes entity_relationship records where toEntity='role', which includes bot user * role assignments. + * + *

    The data loss leaves a bot user with no role at all, so only a bot user that holds no role + * gets its default role back. A bot user that holds any role was not affected by the loss, and its + * roles may have been changed on purpose, so it is left as it is. */ public static void restoreBotUserRolesIfMissing(Handle handle, ConnectionType connectionType) { try { @@ -231,8 +235,8 @@ public static void restoreBotUserRolesIfMissing(Handle handle, ConnectionType co continue; } - if (hasUserRoleRelationship(handle, userId, roleId)) { - LOG.debug("Bot user {} already has role {}", bot.getName(), roleName); + if (hasAnyUserRoleRelationship(handle, userId)) { + LOG.debug("Bot user {} already has a role, skipping", bot.getName()); continue; } @@ -381,18 +385,17 @@ private static String findRoleId(Handle handle, ConnectionType connectionType, S return results.isEmpty() ? null : results.get(0).get("id").toString(); } - private static boolean hasUserRoleRelationship(Handle handle, String userId, String roleId) { + private static boolean hasAnyUserRoleRelationship(Handle handle, String userId) { String query = """ SELECT COUNT(*) as cnt FROM entity_relationship - WHERE fromId = :userId AND toId = :roleId + WHERE fromId = :userId AND fromEntity = 'user' AND toEntity = 'role' AND relation = :relation """; Integer count = handle .createQuery(query) .bind("userId", userId) - .bind("roleId", roleId) .bind("relation", HAS_RELATIONSHIP) .mapTo(Integer.class) .one(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v1114/MigrationUtilTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v1114/MigrationUtilTest.java index 6144871a5901..8acc1b66d257 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v1114/MigrationUtilTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v1114/MigrationUtilTest.java @@ -16,14 +16,19 @@ import java.util.Map; import org.jdbi.v3.core.Handle; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.MockedStatic; import org.openmetadata.schema.api.search.FieldValueBoost; import org.openmetadata.schema.api.search.GlobalSettings; import org.openmetadata.schema.api.search.SearchSettings; +import org.openmetadata.schema.entity.Bot; import org.openmetadata.schema.entity.teams.Role; import org.openmetadata.schema.settings.Settings; import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.BotRepository; import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.ListFilter; import org.openmetadata.service.jdbi3.locator.ConnectionType; import org.openmetadata.service.migration.utils.SearchSettingsMergeUtil; @@ -65,6 +70,46 @@ SELECT COUNT(*) FROM role_entity WHERE json->>'name' = :name """; + private static final String FIND_BOT_USER_POSTGRES = + """ + SELECT id FROM user_entity + WHERE json->>'name' = :name + AND (json->>'isBot')::boolean = true + """; + + private static final String FIND_BOT_USER_MYSQL = + """ + SELECT id FROM user_entity + WHERE JSON_UNQUOTE(JSON_EXTRACT(json, '$.name')) = :name + AND JSON_EXTRACT(json, '$.isBot') = true + """; + + private static final String CHECK_ROLE_EXISTS_MYSQL = + """ + SELECT COUNT(*) FROM role_entity + WHERE JSON_UNQUOTE(JSON_EXTRACT(json, '$.name')) = :name + """; + + private static final String ANY_USER_ROLE_QUERY = + """ + SELECT COUNT(*) as cnt FROM entity_relationship + WHERE fromId = :userId + AND fromEntity = 'user' AND toEntity = 'role' AND relation = :relation + """; + + private static final String INSERT_USER_ROLE_POSTGRES = + """ + INSERT INTO entity_relationship (fromId, toId, fromEntity, toEntity, relation) + VALUES (:userId, :roleId, 'user', 'role', :relation) + ON CONFLICT DO NOTHING + """; + + private static final String INSERT_USER_ROLE_MYSQL = + """ + INSERT IGNORE INTO entity_relationship (fromId, toId, fromEntity, toEntity, relation) + VALUES (:userId, :roleId, 'user', 'role', :relation) + """; + private static final List SYSTEM_POLICIES = List.of( "OrganizationPolicy", @@ -221,6 +266,140 @@ void restoreBotRelationshipsIfMissingInsertsOnlyWhenMatchingBotsExist() { .execute(); } + @Test + void restoreBotUserRolesGivesBuiltInBotWithoutRoleItMappedRole() { + Handle handle = botRoleHandle("ingestion-bot", "user-1", "IngestionBotRole", "role-1", 0); + + runRestoreBotUserRoles(handle, ConnectionType.POSTGRES, "ingestion-bot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_POSTGRES, "user-1", "role-1")).execute(); + } + + @Test + void restoreBotUserRolesGivesApplicationBotWithoutRoleApplicationBotRole() { + Handle handle = + botRoleHandle("searchindexingapplicationbot", "user-2", "ApplicationBotRole", "role-2", 0); + + runRestoreBotUserRoles(handle, ConnectionType.POSTGRES, "SearchIndexingApplicationBot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_POSTGRES, "user-2", "role-2")).execute(); + } + + @Test + void restoreBotUserRolesLeavesApplicationBotThatHoldsAnotherRole() { + Handle handle = + botRoleHandle("narrowedapplicationbot", "user-3", "ApplicationBotRole", "role-2", 1); + + runRestoreBotUserRoles(handle, ConnectionType.POSTGRES, "NarrowedApplicationBot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_POSTGRES, "user-3", "role-2"), never()) + .execute(); + } + + @Test + void restoreBotUserRolesLeavesBotThatAlreadyHoldsItsDefaultRole() { + Handle handle = botRoleHandle("lineage-bot", "user-4", "LineageBotRole", "role-4", 1); + + runRestoreBotUserRoles(handle, ConnectionType.POSTGRES, "lineage-bot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_POSTGRES, "user-4", "role-4"), never()) + .execute(); + } + + @Test + void restoreBotUserRolesChecksAnyRoleWithHasRelationOnMysql() { + Handle handle = mock(Handle.class, RETURNS_DEEP_STUBS); + when(handle.createQuery(FIND_BOT_USER_MYSQL).bind("name", "profiler-bot").mapToMap().list()) + .thenReturn(List.of(Map.of("id", "user-5"))); + when(handle + .createQuery(CHECK_ROLE_EXISTS_MYSQL.replace("COUNT(*)", "id")) + .bind("name", "ProfilerBotRole") + .mapToMap() + .list()) + .thenReturn(List.of(Map.of("id", "role-5"))); + when(handle + .createQuery(ANY_USER_ROLE_QUERY) + .bind("userId", "user-5") + .bind("relation", 10) + .mapTo(Integer.class) + .one()) + .thenReturn(0); + + runRestoreBotUserRoles(handle, ConnectionType.MYSQL, "profiler-bot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_MYSQL, "user-5", "role-5")).execute(); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void restoreBotUserRolesLeavesBotWithAnyRoleOnEveryEngine(ConnectionType connectionType) { + Handle handle = mock(Handle.class, RETURNS_DEEP_STUBS); + boolean mysql = connectionType == ConnectionType.MYSQL; + String findUser = mysql ? FIND_BOT_USER_MYSQL : FIND_BOT_USER_POSTGRES; + String findRole = mysql ? CHECK_ROLE_EXISTS_MYSQL : CHECK_ROLE_EXISTS_POSTGRES; + String insert = mysql ? INSERT_USER_ROLE_MYSQL : INSERT_USER_ROLE_POSTGRES; + when(handle.createQuery(findUser).bind("name", "usage-bot").mapToMap().list()) + .thenReturn(List.of(Map.of("id", "user-6"))); + when(handle + .createQuery(findRole.replace("COUNT(*)", "id")) + .bind("name", "UsageBotRole") + .mapToMap() + .list()) + .thenReturn(List.of(Map.of("id", "role-6"))); + when(handle + .createQuery(ANY_USER_ROLE_QUERY) + .bind("userId", "user-6") + .bind("relation", 10) + .mapTo(Integer.class) + .one()) + .thenReturn(1); + + runRestoreBotUserRoles(handle, connectionType, "usage-bot"); + + verify(insertUserRole(handle, insert, "user-6", "role-6"), never()).execute(); + } + + private Handle botRoleHandle( + String userName, String userId, String roleName, String roleId, int roleCount) { + Handle handle = mock(Handle.class, RETURNS_DEEP_STUBS); + when(handle.createQuery(FIND_BOT_USER_POSTGRES).bind("name", userName).mapToMap().list()) + .thenReturn(List.of(Map.of("id", userId))); + when(handle + .createQuery(CHECK_ROLE_EXISTS_POSTGRES.replace("COUNT(*)", "id")) + .bind("name", roleName) + .mapToMap() + .list()) + .thenReturn(List.of(Map.of("id", roleId))); + when(handle + .createQuery(ANY_USER_ROLE_QUERY) + .bind("userId", userId) + .bind("relation", 10) + .mapTo(Integer.class) + .one()) + .thenReturn(roleCount); + return handle; + } + + private org.jdbi.v3.core.statement.Update insertUserRole( + Handle handle, String insert, String userId, String roleId) { + return handle + .createUpdate(insert) + .bind("userId", userId) + .bind("roleId", roleId) + .bind("relation", 10); + } + + private void runRestoreBotUserRoles( + Handle handle, ConnectionType connectionType, String botName) { + BotRepository botRepository = mock(BotRepository.class); + when(botRepository.listAll(any(), any(ListFilter.class))) + .thenReturn(List.of(new Bot().withName(botName))); + try (MockedStatic entity = mockStatic(Entity.class)) { + entity.when(() -> Entity.getEntityRepository(Entity.BOT)).thenReturn(botRepository); + MigrationUtil.restoreBotUserRolesIfMissing(handle, connectionType); + } + } + @Test void checkAndLogDataLossSymptomsHandlesCountsAndQueryFailuresGracefully() { Handle handle = mock(Handle.class, RETURNS_DEEP_STUBS); From 56ebc63505765c40dd3089b1ab6894788dc6103b Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 29 Nov 2026 21:26:32 -0800 Subject: [PATCH 134/203] Add an integration test for restoring a bot user's default role --- .../it/tests/BotUserRoleRecoveryIT.java | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BotUserRoleRecoveryIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BotUserRoleRecoveryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BotUserRoleRecoveryIT.java new file mode 100644 index 000000000000..c0a2bc4220ba --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BotUserRoleRecoveryIT.java @@ -0,0 +1,119 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.CreateBot; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.auth.JWTAuthMechanism; +import org.openmetadata.schema.auth.JWTTokenExpiry; +import org.openmetadata.schema.entity.Bot; +import org.openmetadata.schema.entity.teams.AuthenticationMechanism; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.service.Entity; +import org.openmetadata.service.migration.utils.v1114.MigrationUtil; + +/** + * The step that restores a bot user's default role gives the role back to a bot user that holds + * none, and leaves a bot user that holds another role as it is. + */ +@Isolated("Runs the role restore step over every bot in the shared database") +@ExtendWith(TestNamespaceExtension.class) +class BotUserRoleRecoveryIT { + private static final String DEFAULT_ROLE = "ApplicationBotRole"; + private static final String OTHER_ROLE = "DataConsumer"; + + @Test + void restoreGivesDefaultRoleOnlyToBotUserWithoutAnyRole(TestNamespace ns) { + final User botUser = createBotWithUser(ns); + final String userId = botUser.getId().toString(); + final String defaultRoleId = roleId(DEFAULT_ROLE); + final String otherRoleId = roleId(OTHER_ROLE); + + replaceRoles(userId, otherRoleId); + runRestore(); + assertEquals(List.of(otherRoleId), roleIds(userId)); + + replaceRoles(userId, null); + runRestore(); + assertEquals(List.of(defaultRoleId), roleIds(userId)); + } + + private static User createBotWithUser(TestNamespace ns) { + final String name = "rolerecoverybot" + UUID.randomUUID().toString().substring(0, 8); + final AuthenticationMechanism auth = + new AuthenticationMechanism() + .withAuthType(AuthenticationMechanism.AuthType.JWT) + .withConfig(new JWTAuthMechanism().withJWTTokenExpiry(JWTTokenExpiry.Unlimited)); + final User user = + SdkClients.adminClient() + .users() + .create( + new CreateUser() + .withName(name) + .withEmail(name + "@test.com") + .withIsBot(true) + .withAuthenticationMechanism(auth)); + ns.trackRoot(Entity.USER, user.getId()); + final Bot bot = + SdkClients.adminClient().bots().create(new CreateBot().withName(name).withBotUser(name)); + ns.trackRoot(Entity.BOT, bot.getId()); + return user; + } + + private static String roleId(String roleName) { + return SdkClients.adminClient().roles().getByName(roleName).getId().toString(); + } + + private static void runRestore() { + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> + MigrationUtil.restoreBotUserRolesIfMissing( + handle, TestSuiteBootstrap.getConnectionType())); + } + + private static void replaceRoles(String userId, String roleId) { + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> { + handle + .createUpdate( + "DELETE FROM entity_relationship WHERE fromId = :userId" + + " AND fromEntity = 'user' AND toEntity = 'role'") + .bind("userId", userId) + .execute(); + if (roleId != null) { + handle + .createUpdate( + "INSERT INTO entity_relationship" + + " (fromId, toId, fromEntity, toEntity, relation)" + + " VALUES (:userId, :roleId, 'user', 'role', 10)") + .bind("userId", userId) + .bind("roleId", roleId) + .execute(); + } + }); + } + + private static List roleIds(String userId) { + return TestSuiteBootstrap.getJdbi() + .withHandle( + handle -> + handle + .createQuery( + "SELECT toId FROM entity_relationship WHERE fromId = :userId" + + " AND fromEntity = 'user' AND toEntity = 'role' ORDER BY toId") + .bind("userId", userId) + .mapTo(String.class) + .list()); + } +} From ffdd7b4645a069f59553bb2af8cffa992c16b25f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 29 Nov 2026 23:21:47 -0800 Subject: [PATCH 135/203] Leave suggestion types the lists cannot show out of the suggestion lists and their counts --- .../ui/src/rest/suggestionsAPI.test.ts | 81 +++++++++++++++++++ .../resources/ui/src/rest/suggestionsAPI.ts | 28 +++++-- 2 files changed, 101 insertions(+), 8 deletions(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts b/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts index 8fb26e2dadb0..82b9deb4058d 100644 --- a/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts @@ -299,4 +299,85 @@ describe('suggestionsAPI', () => { expect(resolveTask).toHaveBeenCalledWith('task-desc', expect.any(Object)); }); }); + + describe('a suggestion type the lists cannot show', () => { + const TAGS = [{ tagFQN: 'PII.Sensitive', source: 'Classification' }]; + const constraintTask = { + id: 'task-constraint', + about: { type: 'table', fullyQualifiedName: 'db.schema.my_table' }, + payload: { + fieldPath: 'tableConstraints', + suggestionType: 'TableConstraint', + suggestedValue: '{"constraintType":"UNIQUE","columns":["name"]}', + }, + status: TaskEntityStatus.Open, + createdBy: { id: 'user-1', name: 'User 1', type: 'user' }, + }; + const tagTask = { + ...makeTask('task-tag', 'columns.col_1.tags', 'Tag'), + payload: { + fieldPath: 'columns.col_1.tags', + suggestionType: 'Tag', + suggestedValue: JSON.stringify(TAGS), + }, + }; + const mixed = () => ({ + data: { + data: [ + constraintTask, + makeTask('task-desc', 'columns.col_1.description', 'Description'), + tagTask, + ], + paging: { total: 3 }, + }, + }); + + it('lists only the description and the tag suggestion, with a total of 2', async () => { + (APIClient.get as jest.Mock).mockResolvedValue(mixed()); + + const result = await getSuggestionsList(); + + expect(result.data.map((s) => [s.id, s.type])).toEqual([ + ['task-desc', SuggestionType.SuggestDescription], + ['task-tag', SuggestionType.SuggestTagLabel], + ]); + expect(result.paging).toEqual({ total: 2 }); + }); + + it('lists the same two for one user', async () => { + (APIClient.get as jest.Mock).mockResolvedValue(mixed()); + + const result = await getSuggestionsByUserId('user-1'); + + expect(result.data.map((s) => s.id)).toEqual(['task-desc', 'task-tag']); + expect(result.paging).toEqual({ total: 2 }); + }); + + it('accept-all of descriptions and of tags never resolves the constraint suggestion', async () => { + (APIClient.get as jest.Mock).mockResolvedValue(mixed()); + (resolveTask as jest.Mock).mockResolvedValue({}); + + for (const type of [ + SuggestionType.SuggestDescription, + SuggestionType.SuggestTagLabel, + ]) { + await approveRejectAllSuggestions( + 'user-1', + 'db.schema.my_table', + type, + SuggestionAction.Accept + ); + } + + expect(resolveTask).toHaveBeenCalledTimes(2); + expect(resolveTask).toHaveBeenNthCalledWith(1, 'task-desc', { + resolutionType: TaskResolutionType.Approved, + newValue: 'description for task-desc', + }); + expect(resolveTask).toHaveBeenNthCalledWith(2, 'task-tag', { + resolutionType: TaskResolutionType.Approved, + newValue: JSON.stringify(TAGS), + }); + }); + }); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.ts b/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.ts index 76f39d55ea41..9619481d3f23 100644 --- a/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.ts +++ b/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.ts @@ -150,6 +150,24 @@ const taskToSuggestion = (task: Task): Suggestion => { }; }; +// A task whose type has no suggestion type here (a table constraint, for one) has no +// card to show, so it is left out of the lists and out of their counts. +const toShowableSuggestions = ( + tasks: Task[], + paging: PagingResponse['paging'] +): PagingResponse => { + const data = tasks + .map(taskToSuggestion) + .filter((suggestion) => suggestion.type !== undefined); + + const dropped = tasks.length - data.length; + + return { + data, + paging: dropped ? { ...paging, total: paging.total - dropped } : paging, + }; +}; + export const getSuggestionsList = async ( params?: ListSuggestionsParams ): Promise> => { @@ -165,10 +183,7 @@ export const getSuggestionsList = async ( }, }); - return { - data: response.data.data.map(taskToSuggestion), - paging: response.data.paging, - }; + return toShowableSuggestions(response.data.data, response.data.paging); }; export const getSuggestionsByUserId = async ( @@ -188,10 +203,7 @@ export const getSuggestionsByUserId = async ( }, }); - return { - data: response.data.data.map(taskToSuggestion), - paging: response.data.paging, - }; + return toShowableSuggestions(response.data.data, response.data.paging); }; export const updateSuggestionStatus = async ( From b291b5b77e7f347c63494193726c483d9a429355 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 29 Nov 2026 23:22:14 -0800 Subject: [PATCH 136/203] Add the shacl export format to the UI's media type and extension maps --- .../resources/ui/src/rest/ontologyAPI.test.ts | 40 +++++++++++++++++++ .../ui/src/rest/ontologyExport.constants.ts | 2 + 2 files changed, 42 insertions(+) diff --git a/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts b/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts index 7f9794cc91da..261e8955ecb1 100644 --- a/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts @@ -24,12 +24,14 @@ import { Direction } from '../generated/api/data/ontologyConceptQuery'; import { AssetType } from '../generated/api/data/updateOntologyConceptBinding'; import { OntologyChangeSetState } from '../generated/entity/data/ontologyChangeSet'; import APIClient from './axiosClient'; +import { NATIVE_EXPORT_EXTENSIONS } from './ontologyExport.constants'; import { activateOntologyRelease, captureOntologyRelease, createOntology, createOntologyConcept, deleteOntologyConceptBinding, + exportOntologyDraft, exportOntologyRelease, generateOntologyConceptQuery, generateOntologyDomainDraft, @@ -766,3 +768,41 @@ it('reads a bounded review page with the server total and after cursor', async ( signal, }); }); + +describe('a SHACL export', () => { + it('asks a release for the format shacl as text/turtle', async () => { + (APIClient.get as jest.Mock).mockResolvedValueOnce({ data: '@prefix sh:' }); + + await exportOntologyRelease('release-id', 'shacl'); + + expect(APIClient.get).toHaveBeenLastCalledWith( + '/ontology/releases/release-id/export', + { + params: { format: 'shacl' }, + headers: { Accept: 'text/turtle' }, + responseType: 'text', + signal: undefined, + } + ); + }); + + it('asks the draft for the format shacl as text/turtle', async () => { + (APIClient.get as jest.Mock).mockResolvedValueOnce({ data: '@prefix sh:' }); + + await exportOntologyDraft('ontology-id', 'shacl'); + + expect(APIClient.get).toHaveBeenLastCalledWith( + '/ontologies/ontology-id/export', + { + params: { format: 'shacl' }, + headers: { Accept: 'text/turtle' }, + responseType: 'text', + signal: undefined, + } + ); + }); + + it('names a file with the extension ttl', () => { + expect(NATIVE_EXPORT_EXTENSIONS.shacl).toBe('ttl'); + }); +}); diff --git a/openmetadata-ui/src/main/resources/ui/src/rest/ontologyExport.constants.ts b/openmetadata-ui/src/main/resources/ui/src/rest/ontologyExport.constants.ts index 8dc4401b5c1c..4da44a9bc130 100644 --- a/openmetadata-ui/src/main/resources/ui/src/rest/ontologyExport.constants.ts +++ b/openmetadata-ui/src/main/resources/ui/src/rest/ontologyExport.constants.ts @@ -29,6 +29,7 @@ export const NATIVE_EXPORT_MEDIA_TYPES = { jsonld: 'application/ld+json', ntriples: 'application/n-triples', rdfxml: 'application/rdf+xml', + shacl: TURTLE_MEDIA_TYPE, skos: TURTLE_MEDIA_TYPE, 'skos-xl': TURTLE_MEDIA_TYPE, turtle: TURTLE_MEDIA_TYPE, @@ -39,6 +40,7 @@ export const NATIVE_EXPORT_EXTENSIONS = { jsonld: 'jsonld', ntriples: 'nt', rdfxml: 'rdf', + shacl: 'ttl', skos: 'ttl', 'skos-xl': 'ttl', turtle: 'ttl', From b7a67c7a581cf2fe38980014b38c99f58e81dbeb Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sun, 29 Nov 2026 23:22:23 -0800 Subject: [PATCH 137/203] Fix the release path in the shacl export test --- .../src/main/resources/ui/src/rest/ontologyAPI.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts b/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts index 261e8955ecb1..a0922096675a 100644 --- a/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts @@ -776,7 +776,7 @@ describe('a SHACL export', () => { await exportOntologyRelease('release-id', 'shacl'); expect(APIClient.get).toHaveBeenLastCalledWith( - '/ontology/releases/release-id/export', + '/ontologyReleases/release-id/export', { params: { format: 'shacl' }, headers: { Accept: 'text/turtle' }, From c9efda84cfcc47853373fa369d5489775838fd91 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 30 Nov 2026 07:17:32 -0800 Subject: [PATCH 138/203] Send a table constraint suggestion's resolution with its comment once and only the keys its form declares --- .../TaskTab/TaskTabNew.component.test.tsx | 231 ++++++++++++++++++ .../Task/TaskTab/TaskTabNew.component.tsx | 16 +- .../resources/ui/src/rest/ontologyAPI.test.ts | 2 +- ...TaskFormSchemaUtils.resolvePayload.test.ts | 69 ++++++ .../ui/src/utils/TaskFormSchemaUtils.ts | 50 +++- 5 files changed, 363 insertions(+), 5 deletions(-) create mode 100644 openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.resolvePayload.test.ts diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx index d858ff6ee4e3..fc0c41a18ee7 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx @@ -473,6 +473,31 @@ jest.mock('../MetadataCompletionTask/MetadataCompletionTask', () => ({ default: jest.fn().mockReturnValue(

    MetadataCompletionTask

    ), })); +// A transition form's data, as a person fills it in. While it is set, the +// payload fields are one button that submits it; otherwise the real fields render. +let mockFilledPayload: Record | undefined; +jest.mock('../../../../pages/TasksPage/shared/TaskPayloadSchemaFields', () => { + const actual = jest.requireActual( + '../../../../pages/TasksPage/shared/TaskPayloadSchemaFields' + ); + + return { + __esModule: true, + default: (props: { + onChange: (payload: Record) => void; + }) => + mockFilledPayload ? ( + + ) : ( + + ), + }; +}); + const mockProps = { task: MOCK_TASK, owners: [], @@ -1848,3 +1873,209 @@ describe('TaskTabNew Component', () => { }); }); }); + +describe('TaskTabNew resolving a workflow task with a form', () => { + const CONSTRAINT = '{"constraintType":"UNIQUE","columns":["name"]}'; + const transition = (id: 'approve' | 'reject', extra = {}) => ({ + id, + label: id === 'approve' ? 'Approve' : 'Reject', + resolutionType: + id === 'approve' + ? TaskResolutionType.Approved + : TaskResolutionType.Rejected, + targetStageId: id, + targetTaskStatus: + id === 'approve' ? TaskEntityStatus.Approved : TaskEntityStatus.Rejected, + requiresComment: true, + ...extra, + }); + const suggestion = (suggestionType: string, payload: object): Task => ({ + ...MOCK_WORKFLOW_TASK, + type: TaskEntityType.Suggestion, + category: TaskCategory.MetadataUpdate, + payload: { suggestionType, ...payload } as Task['payload'], + }); + const constraintTask = (id: 'approve' | 'reject', extra = {}) => ({ + ...suggestion('TableConstraint', { + fieldPath: 'tableConstraints', + suggestedValue: CONSTRAINT, + }), + availableTransitions: [transition(id, extra)], + }); + const formSchema = ( + properties: Record, + transitionForms?: Record + ) => ({ + name: 'TableConstraintSuggestion', + taskType: TaskEntityType.Suggestion, + taskCategory: TaskCategory.MetadataUpdate, + formSchema: { type: 'object', properties }, + uiSchema: {}, + transitionForms, + }); + + const submit = async ( + task: Task, + schema: ReturnType, + filled: Record + ) => { + const { useAuth } = require('../../../../hooks/authHooks'); + const { + getResolvedTaskFormSchema, + } = require('../../../../utils/TaskFormSchemaUtils'); + const { resolveTask } = require('../../../../rest/tasksAPI'); + + useAuth.mockReturnValue({ isAdminUser: true }); + getResolvedTaskFormSchema.mockResolvedValue(schema); + mockFilledPayload = filled; + await act(async () => { + render(, { + wrapper: MemoryRouter, + }); + }); + await act(async () => { + fireEvent.click(screen.getByTestId('workflow-task-action-primary')); + }); + await act(async () => { + const fillButtons = await screen.findAllByTestId('fill-payload'); + fireEvent.click(fillButtons[fillButtons.length - 1]); + }); + await act(async () => { + fireEvent.click(screen.getByText('label.ok')); + }); + + return resolveTask as jest.Mock; + }; + + afterEach(() => { + mockFilledPayload = undefined; + }); + + it('rejects a constraint suggestion with a comment sent once and no payload', async () => { + const resolveTask = await submit( + constraintTask('reject'), + formSchema({ suggestedValue: { type: 'string' } }), + { + fieldPath: 'tableConstraints', + suggestedValue: CONSTRAINT, + newDescription: 'a default', + comment: 'Not unique', + } + ); + + await waitFor(() => expect(resolveTask).toHaveBeenCalledTimes(1)); + const [, body] = resolveTask.mock.calls[0]; + + expect(body).toEqual({ + transitionId: 'reject', + resolutionType: 'Rejected', + comment: 'Not unique', + newValue: CONSTRAINT, + }); + expect(body.payload).toBeUndefined(); + }); + + it('approves a constraint suggestion with a comment and only the keys its form declares', async () => { + const resolveTask = await submit( + constraintTask('approve', { formRef: 'approveForm' }), + formSchema( + { suggestedValue: { type: 'string' } }, + { + approveForm: { + formSchema: { + type: 'object', + properties: { reasoning: { type: 'string' } }, + }, + }, + } + ), + { + fieldPath: 'tableConstraints', + suggestedValue: CONSTRAINT, + reasoning: 'Checked', + newDescription: 'a default', + comment: 'Looks right', + } + ); + + await waitFor(() => expect(resolveTask).toHaveBeenCalledTimes(1)); + + expect(resolveTask).toHaveBeenCalledWith(MOCK_WORKFLOW_TASK.id, { + transitionId: 'approve', + resolutionType: 'Approved', + comment: 'Looks right', + newValue: CONSTRAINT, + payload: { reasoning: 'Checked' }, + }); + }); + + it('keeps a comment in the payload when the transition form declares it', async () => { + const resolveTask = await submit( + constraintTask('reject', { formRef: 'rejectForm' }), + formSchema( + {}, + { + rejectForm: { + formSchema: { + type: 'object', + properties: { + comment: { type: 'string' }, + reasoning: { type: 'string' }, + }, + }, + }, + } + ), + { comment: 'Not unique', reasoning: 'Seen', suggestedValue: CONSTRAINT } + ); + + await waitFor(() => expect(resolveTask).toHaveBeenCalledTimes(1)); + + expect(resolveTask).toHaveBeenCalledWith(MOCK_WORKFLOW_TASK.id, { + transitionId: 'reject', + resolutionType: 'Rejected', + comment: 'Not unique', + newValue: CONSTRAINT, + payload: { comment: 'Not unique', reasoning: 'Seen' }, + }); + }); + + it.each([ + [ + 'a description suggestion', + suggestion('Description', { + fieldPath: 'description', + suggestedValue: 'A new description', + }), + ], + [ + 'a tag suggestion', + suggestion('Tag', { + fieldPath: 'columns.id.tags', + suggestedValue: '[]', + }), + ], + ])('sends %s the whole form data, as before', async (_name, base) => { + const filled = { + fieldPath: 'x', + suggestedValue: 'filled', + newDescription: 'a default', + comment: 'Fine', + }; + const resolveTask = await submit( + { ...base, availableTransitions: [transition('reject')] }, + formSchema({ suggestedValue: { type: 'string' } }), + filled + ); + + await waitFor(() => expect(resolveTask).toHaveBeenCalledTimes(1)); + + expect(resolveTask).toHaveBeenCalledWith(MOCK_WORKFLOW_TASK.id, { + transitionId: 'reject', + resolutionType: 'Rejected', + comment: 'Fine', + newValue: expect.anything(), + payload: filled, + }); + }); +}); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.tsx index 9364e103de8f..a1f577871fa5 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.tsx @@ -130,6 +130,7 @@ import { getResolvedTaskFormSchema, getTaskFormHandlerConfig, getTaskResolutionNewValue, + getTaskResolvePayload, getTaskTransitionFormSchema, getTaskTransitionUiSchema, hasTaskFormFields, @@ -886,7 +887,12 @@ export const TaskTabNew = ({ payload, transitionUiSchema ), - payload, + payload: getTaskResolvePayload( + task, + payload, + taskFormSchema, + transition + ), comment: commentText, }, getTransitionResolutionType(transition), @@ -958,7 +964,11 @@ export const TaskTabNew = ({ updateTaskData( { newValue: isApprovalWorkflowTask ? taskHandler.approvedValue : newValue, - payload: initialTaskPayload, + payload: getTaskResolvePayload( + task, + initialTaskPayload, + taskFormSchema + ), }, TaskResolutionType.Approved ); @@ -993,7 +1003,7 @@ export const TaskTabNew = ({ payload, taskFormSchema?.uiSchema ), - payload, + payload: getTaskResolvePayload(task, payload, taskFormSchema), }, TaskResolutionType.Approved ); diff --git a/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts b/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts index a0922096675a..8a89426b4ba5 100644 --- a/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/rest/ontologyAPI.test.ts @@ -24,7 +24,6 @@ import { Direction } from '../generated/api/data/ontologyConceptQuery'; import { AssetType } from '../generated/api/data/updateOntologyConceptBinding'; import { OntologyChangeSetState } from '../generated/entity/data/ontologyChangeSet'; import APIClient from './axiosClient'; -import { NATIVE_EXPORT_EXTENSIONS } from './ontologyExport.constants'; import { activateOntologyRelease, captureOntologyRelease, @@ -66,6 +65,7 @@ import { undoOntologyChangeSet, upsertInferenceRule, } from './ontologyAPI'; +import { NATIVE_EXPORT_EXTENSIONS } from './ontologyExport.constants'; jest.mock('./axiosClient', () => ({ delete: jest.fn(), diff --git a/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.resolvePayload.test.ts b/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.resolvePayload.test.ts new file mode 100644 index 000000000000..72554120a4eb --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.resolvePayload.test.ts @@ -0,0 +1,69 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Task, TaskCategory, TaskEntityType } from '../rest/tasksAPI'; +import { getTaskResolvePayload } from './TaskFormSchemaUtils'; + +const task = (suggestionType: string): Task => + ({ + id: 'task-1', + type: TaskEntityType.Suggestion, + category: TaskCategory.MetadataUpdate, + payload: { suggestionType }, + } as unknown as Task); + +const schema = { + name: 'TableConstraintSuggestion', + taskType: 'Suggestion', + formSchema: { + type: 'object', + properties: { suggestedValue: {}, reasoning: {} }, + }, +}; + +const FORM_DATA = { + fieldPath: 'tableConstraints', + suggestedValue: '{"constraintType":"UNIQUE","columns":["name"]}', + reasoning: 'Checked', + comment: 'Not unique', + newDescription: 'a default', +}; + +describe('getTaskResolvePayload', () => { + it('keeps only the keys the form declares for a table constraint suggestion', () => { + expect( + getTaskResolvePayload(task('TableConstraint'), FORM_DATA, schema) + ).toEqual({ + suggestedValue: '{"constraintType":"UNIQUE","columns":["name"]}', + reasoning: 'Checked', + }); + }); + + it('sends no payload for a transition whose form declares nothing', () => { + expect( + getTaskResolvePayload(task('TableConstraint'), FORM_DATA, schema, { + id: 'reject', + }) + ).toBeUndefined(); + }); + + it.each(['Description', 'Tag'])( + 'sends a %s suggestion the form data as it is', + (suggestionType) => { + expect( + getTaskResolvePayload(task(suggestionType), FORM_DATA, schema) + ).toEqual(FORM_DATA); + } + ); +}); diff --git a/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.ts b/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.ts index b2edefa93f23..c85db432cdc1 100644 --- a/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.ts +++ b/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.ts @@ -24,7 +24,7 @@ * limitations under the License. */ -import { cloneDeep, uniqBy } from 'lodash'; +import { cloneDeep, isEmpty, pick, uniqBy } from 'lodash'; import { TaskAvailableTransition } from '../generated/entity/tasks/task'; import { TagLabel } from '../generated/type/tagLabel'; import { @@ -556,6 +556,54 @@ export const getEditableTaskPayload = ( return payload; }; +const isTableConstraintSuggestion = (task: Task) => + task.type === TaskEntityType.Suggestion && + task.payload?.suggestionType === 'TableConstraint'; + +const getDeclaredFormSchema = ( + taskFormSchema?: TaskFormSchema, + transition?: Pick +): JsonSchemaObject | undefined => { + if (!transition) { + return taskFormSchema?.formSchema; + } + const transitionSchema = getTransitionFormConfig(taskFormSchema, transition) + ?.formSchema as JsonSchemaObject | undefined; + + return ( + transitionSchema ?? + (transition.formRef ? taskFormSchema?.formSchema : undefined) + ); +}; + +/** + * The payload a resolution request carries. The server refuses a table + * constraint suggestion's resolution that sends a key outside its payload + * schema, and the form data can hold one (the comment of a transition, a + * default, an editable payload field). So that suggestion sends only the keys + * its form declares, and no payload when the form declares none; the server + * fills the rest from the stored payload. A comment the form does not declare + * is sent as the resolution's own comment. The payload of every other task is + * sent as it is. + */ +export const getTaskResolvePayload = ( + task: Task, + payload: TaskPayload, + taskFormSchema?: TaskFormSchema, + transition?: Pick +): TaskPayload | undefined => { + if (!isTableConstraintSuggestion(task)) { + return payload; + } + const declaredSchema = getDeclaredFormSchema(taskFormSchema, transition); + const declared = Object.keys( + (declaredSchema?.properties as Record | undefined) ?? {} + ); + const declaredPayload = pick(payload, declared); + + return isEmpty(declaredPayload) ? undefined : declaredPayload; +}; + const getFieldResolutionValue = (payload: TaskPayload, valueField?: string) => String( payload[valueField ?? 'newDescription'] ?? payload.suggestedValue ?? '' From 24ed5eae83bde227aa262847c15ec84457b8a751 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 30 Nov 2026 07:30:10 -0800 Subject: [PATCH 139/203] Name the constraint an approval adds in its comment, and correct the record and the type check's Javadoc --- ...stion-task-can-carry-a-table-constraint.md | 24 ++++-- .../TaskTableConstraintSuggestionIT.java | 34 +++++++++ .../tasks/TableConstraintSuggestion.java | 26 ++++++- .../service/tasks/TaskWorkflowHandler.java | 71 +++++++++++------- .../tasks/TableConstraintSuggestionTest.java | 75 +++++++++++++++++++ 5 files changed, 197 insertions(+), 33 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index 41bbe7bd9006..f41c62af1f8d 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,9 +1,9 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type); v7 2026-11-30 (the key rule names the keys a configured workflow writes; the resolution's payload holds the constraint added; an approval's comment names that constraint; the task tab sends only declared keys; the suggestion lists skip types they cannot show) - **Deciders:** OpenMetadata maintainers -- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply, a new value under a value field outside the schema, a stored key that does not stop a rejection), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing by POST or PUT, patching, resolving and voting, a vote refused without storing its key, a patch that changes the type of a task; a task that carries every declared key) +- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply, a new value under a value field outside the schema, a stored key that does not stop a rejection, the comment an approval leaves), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing by POST or PUT, patching, resolving and voting, a vote refused without storing its key, a patch that changes the type of a task; a task that carries every declared key) - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type ## Context @@ -33,19 +33,33 @@ declined. - No task form changes what approving a constraint suggestion needs or does. Approving needs `EditAll` on the table and adds the constraint, whatever form the task's category matches. A form's permission, handler and actions apply to other tasks as before. -- A constraint suggestion's payload holds only the keys of the suggestion payload schema, so no - other key decides what approving it needs or does. Filing by POST or PUT, patching, and a +- Apart from a key that a configured workflow writes (the next bullet), a constraint suggestion's + payload holds only the keys of the suggestion payload schema, so no other key decides what + approving it needs or does. Filing by POST or PUT, patching, and a resolution of any type whose payload or new value would add a key are refused with a 400 that names each key the schema does not declare, before anything is recorded or stored. A new value adds the key that the task form names as its value field, so it is refused when that key is not declared. The seeded suggestion forms name no value field. A key the task already stores - does not refuse a resolution that adds none, and approving checks the merged payload. Keys are + does not refuse a rejection that adds none, and approving checks the merged payload. Keys are compared exactly. The names come from the generated `SuggestionPayload`, so the rule follows the schema. - A workflow that an administrator configures to write a key into a task's payload, such as a lifecycle move, makes a constraint suggestion bound to it impossible to approve, because approving checks the merged payload. The suggestion can still be rejected, and the table stays unchanged. +- The constraint that approving adds is the one in the merged payload: the task's payload with the + resolution's payload laid over it. The resolution's payload, not the task's, holds the constraint + that was added, so an approver who resolves with another valid `suggestedValue` adds that one, + and the task's payload keeps the filed one. A new value never changes the constraint, because the merge + never overwrites a key the payload already has, and `suggestedValue` is always there. The comment that an approval leaves on the task names the + constraint that was added (its type, its columns and, for a foreign key, its referred columns), + or says the table already had it; it never repeats a new value, and a rejection leaves none. +- The task tab of the UI sends a constraint suggestion's resolution with the approver's comment as + the resolution's own comment, and with a payload of only the keys the form of that transition + declares, or none when the form declares none, because the form's data can hold a key the schema + does not declare. The suggestion lists of the UI leave out a suggestion whose type they have no + card for, so a constraint suggestion shows neither as a description nor as a tag, and it is + not counted. - Applying patches the table as the approver through the table repository, so its own validation runs. A constraint equal to one already on the table (same type, columns and referred columns) writes nothing and the task still resolves. A second primary key is refused with a 400 naming diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 043ad4cc9073..a6adfc29a8ea 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -749,6 +749,40 @@ void aSuggestionCarryingEveryDeclaredKeyIsFiledAndApprovingAddsExactlyItsConstra assertEquals("shared_user3", updatedByOf(table)); } + @Test + void approvingWithANewValueAddsTheFiledConstraintAndTheCommentNamesIt(TestNamespace ns) { + Table table = ownedTable(ns, "newvalue"); + Task task = + file( + ns, + table, + "newvalue", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + String otherConstraint = JsonUtils.pojoToJson(constraint(ConstraintType.PRIMARY_KEY, "id")); + + Task approved = + SdkClients.user3Client() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Approved) + .withNewValue(otherConstraint)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals(otherConstraint, stored.getResolution().getNewValue()); + assertEquals( + List.of("Added table constraint: UNIQUE on [name]"), + stored.getComments().stream().map(comment -> comment.getMessage()).toList()); + } + @Test void theKeysOfAnOpenSuggestionCannotChangeAfterItIsFiled(TestNamespace ns) { Table table = ownedTable(ns, "frozen"); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java index 3f718d768e65..67efc7829360 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java @@ -144,8 +144,8 @@ private static String suggestionTypeOf(Object payload) { /** * Refuses a resolution whose payload changes the task's suggestion type to or from {@code - * TableConstraint}. Approving is authorized for the type the task was filed with, so a changed - * type would write a table constraint on the right to edit a description. + * TableConstraint}. Approving is authorized for the task's current type, so a changed type would + * write a table constraint on the right to edit a description. */ public static void requireSameSuggestionType(Task task, Object requestPayload) { if (task == null || task.getType() != TaskEntityType.Suggestion || requestPayload == null) { @@ -234,6 +234,28 @@ public static List withConstraint(Table table, TableConstraint return constraints; } + /** + * The comment an approval leaves: the constraint the resolution adds, from the task's payload + * with the resolution's laid over it, or the equal constraint the table already has. A new value + * is not named, because it never changes the constraint. + */ + public static String resolutionComment(Task task, Object requestPayload, String newValue) { + JsonNode merged = + JsonUtils.valueToTree( + TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + TableConstraint constraint = constraintOf(merged); + boolean added = toAdd(loadTable(task), constraint).isPresent(); + String prefix = added ? "Added table constraint" : "Table already has constraint"; + return "%s: %s".formatted(prefix, describe(constraint)); + } + + private static String describe(TableConstraint constraint) { + String description = + "%s on %s".formatted(constraint.getConstraintType(), listOrEmpty(constraint.getColumns())); + List referred = listOrEmpty(constraint.getReferredColumns()); + return referred.isEmpty() ? description : "%s referring to %s".formatted(description, referred); + } + /** The constraint a task's {@code suggestedValue} carries. */ public static TableConstraint constraintOf(JsonNode payload) { String suggestedValue = payload.path("suggestedValue").asText(""); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index add517220816..1c1d5b2fde8c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -642,10 +642,7 @@ private Task applyTaskResolution( : "null", task.getAbout() != null); - // Add audit comment if assignee provided/modified the value - if (approved && newValue != null && !newValue.isEmpty()) { - addResolutionComment(task, taskRepository, newValue, user); - } + addResolutionComment(task, taskRepository, approved, newValue, resolvedPayload, user); // A memory conflict review decides on rejection too, and a refused decision must fail the // resolution. Other types mutate the target entity only on positive resolutions. @@ -733,36 +730,27 @@ private void persistEditedWorkflowPayload( } /** - * Add a comment to the task recording what value was applied by whom. - * This creates an audit trail for task resolution. + * Add a comment to the task recording what was applied by whom. This creates an audit trail for + * task resolution. */ private void addResolutionComment( - Task task, TaskRepository taskRepository, String newValue, String user) { + Task task, + TaskRepository taskRepository, + boolean approved, + String newValue, + Object resolvedPayload, + String user) { try { - // Check if the newValue differs from the original suggestion - Object payload = task.getPayload(); - String originalSuggestion = null; - if (payload != null) { - JsonNode payloadNode = JsonUtils.valueToTree(payload); - originalSuggestion = payloadNode.path("suggestedValue").asText(null); - } - - // Only add comment if user provided a new value (not just accepting suggestion) - boolean userProvidedValue = - originalSuggestion == null - || originalSuggestion.isEmpty() - || !originalSuggestion.equals(newValue); - - if (userProvidedValue) { - String commentMessage = buildResolutionCommentMessage(task.getType(), newValue); - + Optional commentMessage = + resolutionComment(task, approved, resolvedPayload, newValue); + if (commentMessage.isPresent()) { EntityReference authorRef = Entity.getEntityReferenceByName(Entity.USER, user, Include.NON_DELETED); TaskComment comment = new TaskComment() .withId(UUID.randomUUID()) - .withMessage(commentMessage) + .withMessage(commentMessage.get()) .withAuthor(authorRef) .withCreatedAt(System.currentTimeMillis()); @@ -780,10 +768,41 @@ private void addResolutionComment( } } + /** + * The audit comment of a resolution, when it has one. A table constraint suggestion's approval + * names the constraint it adds, because a new value never changes that constraint. Every other + * task has a comment only when the approver gave a value that differs from the suggestion. + */ + static Optional resolutionComment( + Task task, boolean approved, Object resolvedPayload, String newValue) { + Optional commentMessage = Optional.empty(); + if (approved && TableConstraintSuggestion.isTableConstraint(task)) { + commentMessage = + Optional.of(TableConstraintSuggestion.resolutionComment(task, resolvedPayload, newValue)); + } else if (approved && newValue != null && !newValue.isEmpty()) { + commentMessage = + providesNewValue(task, newValue) + ? Optional.of(buildResolutionCommentMessage(task.getType(), newValue)) + : Optional.empty(); + } + return commentMessage; + } + + private static boolean providesNewValue(Task task, String newValue) { + String originalSuggestion = null; + if (task.getPayload() != null) { + originalSuggestion = + JsonUtils.valueToTree(task.getPayload()).path("suggestedValue").asText(null); + } + return originalSuggestion == null + || originalSuggestion.isEmpty() + || !originalSuggestion.equals(newValue); + } + /** * Build a comment message based on task type and the applied value. */ - private String buildResolutionCommentMessage(TaskEntityType taskType, String newValue) { + private static String buildResolutionCommentMessage(TaskEntityType taskType, String newValue) { String truncatedValue = newValue.length() > 200 ? newValue.substring(0, 200) + "..." : newValue; return switch (taskType) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java index 2e058c5df65c..fd04a0c8457d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -877,6 +877,81 @@ private static void invokeApplySuggestion( TaskWorkflowHandler.getInstance(), task, task.getPayload(), table, repository, user); } + private static final String FILED = "{\"constraintType\":\"UNIQUE\",\"columns\":[\"email\"]}"; + private static final String OTHER = + "{\"constraintType\":\"PRIMARY_KEY\",\"columns\":[\"order_id\"]}"; + + @Test + void anApprovalWithANewValue_namesTheFiledConstraintNotTheNewValue() { + Task task = taskWithValue(FILED); + + assertEquals( + Optional.of("Added table constraint: UNIQUE on [email]"), + TaskWorkflowHandler.resolutionComment(task, true, null, OTHER)); + } + + @Test + void anApprovalWithoutANewValue_namesTheFiledConstraint() { + Task task = taskWithValue(FILED); + + assertEquals( + Optional.of("Added table constraint: UNIQUE on [email]"), + TaskWorkflowHandler.resolutionComment(task, true, null, null)); + } + + @Test + void anApprovalOfAForeignKey_namesItsReferredColumns() { + Task task = + task( + Entity.TABLE, + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id"))); + + assertEquals( + Optional.of( + "Added table constraint: FOREIGN_KEY on [customer_id] referring to [svc.db.schema.customers.id]"), + TaskWorkflowHandler.resolutionComment(task, true, null, null)); + } + + @Test + void anApprovalOfAConstraintTheTableHas_saysSo() { + orders.setTableConstraints(List.of(constraint(ConstraintType.UNIQUE, List.of("email")))); + + assertEquals( + Optional.of("Table already has constraint: UNIQUE on [email]"), + TaskWorkflowHandler.resolutionComment(taskWithValue(FILED), true, null, null)); + } + + @Test + void aRejectionWithANewValue_leavesNoComment() { + assertEquals( + Optional.empty(), + TaskWorkflowHandler.resolutionComment(taskWithValue(FILED), false, null, OTHER)); + } + + @Test + void aDescriptionSuggestionsComment_keepsItsText() { + Task description = + new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withPayload( + Map.of( + "suggestionType", + "Description", + "fieldPath", + "description", + "suggestedValue", + "The filed text")); + + assertEquals( + Optional.of("Resolved with value: The approver's text"), + TaskWorkflowHandler.resolutionComment(description, true, null, "The approver's text")); + assertEquals( + Optional.empty(), + TaskWorkflowHandler.resolutionComment(description, true, null, "The filed text")); + } + private static Table table(String name, String fqn, String... columns) { List columnList = new ArrayList<>(); for (String column : columns) { From 38ba34307ec258b13a771c4df95c769e1abb6169 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 30 Nov 2026 08:51:34 -0800 Subject: [PATCH 140/203] Post a task resolution's comment after its change is applied An approval whose change fails now leaves no comment on the task, which stays open. The comment's text is still decided before the change, on the table as it was. Tests cover an approval whose apply fails and the comment of an approval whose payload carries another constraint. The record and the class Javadoc state when a payload holds the constraint added and which keys a configured workflow can write. --- ...stion-task-can-carry-a-table-constraint.md | 24 ++++-- .../TaskTableConstraintSuggestionIT.java | 86 +++++++++++++++++++ .../tasks/TableConstraintSuggestion.java | 5 +- .../service/tasks/TaskWorkflowHandler.java | 33 ++++--- .../tasks/TableConstraintSuggestionTest.java | 8 ++ 5 files changed, 134 insertions(+), 22 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index f41c62af1f8d..45cae94630ce 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,9 +1,9 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type); v7 2026-11-30 (the key rule names the keys a configured workflow writes; the resolution's payload holds the constraint added; an approval's comment names that constraint; the task tab sends only declared keys; the suggestion lists skip types they cannot show) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type); v7 2026-11-30 (the key rule names the keys a configured workflow writes; the resolution's payload holds the constraint added; an approval's comment names that constraint; the task tab sends only declared keys; the suggestion lists skip types they cannot show); v8 2026-11-30 (the comment is posted after the change is applied; the constraint added is read from the resolution's payload only when it carries one; the lists leave out a constraint suggestion only on the pages they fetched) - **Deciders:** OpenMetadata maintainers -- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply, a new value under a value field outside the schema, a stored key that does not stop a rejection, the comment an approval leaves), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing by POST or PUT, patching, resolving and voting, a vote refused without storing its key, a patch that changes the type of a task; a task that carries every declared key) +- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply, a new value under a value field outside the schema, a stored key that does not stop a rejection, the comment an approval leaves), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing by POST or PUT, patching, resolving and voting, a vote refused without storing its key, a patch that changes the type of a task; a task that carries every declared key; the comment of an approval whose payload carries another constraint; an approval whose apply fails leaves no comment) - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type ## Context @@ -48,18 +48,24 @@ declined. approving checks the merged payload. The suggestion can still be rejected, and the table stays unchanged. - The constraint that approving adds is the one in the merged payload: the task's payload with the - resolution's payload laid over it. The resolution's payload, not the task's, holds the constraint - that was added, so an approver who resolves with another valid `suggestedValue` adds that one, - and the task's payload keeps the filed one. A new value never changes the constraint, because the merge - never overwrites a key the payload already has, and `suggestedValue` is always there. The comment that an approval leaves on the task names the - constraint that was added (its type, its columns and, for a foreign key, its referred columns), - or says the table already had it; it never repeats a new value, and a rejection leaves none. + resolution's payload laid over it. When the resolution's payload carries a + `suggestedValue`, that is the constraint added, and the task's payload keeps the filed one; + otherwise the task's payload holds it. An approver who resolves with another valid + `suggestedValue` therefore adds that one. A new value never changes the constraint, because the + merge never overwrites a key the payload already has, and `suggestedValue` is always there. The + comment that an approval leaves on the task names the constraint that was added (its type, its + columns and, for a foreign key, its referred columns), or says the table already had it; it never + repeats a new value, and a rejection leaves none. The text is decided on the table as it was + before the change, and the comment is posted only after the change is applied, so an approval + whose apply fails leaves no comment on the task, which stays open. This holds for every task + type. A comment that cannot be written does not fail a resolution that was applied. - The task tab of the UI sends a constraint suggestion's resolution with the approver's comment as the resolution's own comment, and with a payload of only the keys the form of that transition declares, or none when the form declares none, because the form's data can hold a key the schema does not declare. The suggestion lists of the UI leave out a suggestion whose type they have no card for, so a constraint suggestion shows neither as a description nor as a tag, and it is - not counted. + not counted in the pages the lists have fetched. A constraint suggestion on a page not yet + fetched stays in the server's total until that page is fetched. - Applying patches the table as the approver through the table repository, so its own validation runs. A constraint equal to one already on the table (same type, columns and referred columns) writes nothing and the task still resolves. A second primary key is refused with a 400 naming diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index a6adfc29a8ea..07d352fb1deb 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -43,9 +43,13 @@ import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.classification.CreateClassification; +import org.openmetadata.schema.api.classification.CreateTag; import org.openmetadata.schema.api.tasks.BulkTaskOperation; import org.openmetadata.schema.api.tasks.CreateTask; import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.entity.classification.Classification; +import org.openmetadata.schema.entity.classification.Tag; import org.openmetadata.schema.entity.data.DatabaseSchema; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.entity.feed.FormSchema; @@ -60,6 +64,7 @@ import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.schema.type.TableConstraint.RelationshipType; +import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.type.TaskCategory; import org.openmetadata.schema.type.TaskEntityStatus; import org.openmetadata.schema.type.TaskEntityType; @@ -71,6 +76,7 @@ import org.openmetadata.sdk.models.ListParams; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; import org.openmetadata.service.governance.workflows.WorkflowHandler; import org.openmetadata.service.util.FullyQualifiedName; @@ -783,6 +789,59 @@ void approvingWithANewValueAddsTheFiledConstraintAndTheCommentNamesIt(TestNamesp stored.getComments().stream().map(comment -> comment.getMessage()).toList()); } + @Test + void approvingWithAnotherConstraintInThePayloadAddsItAndTheCommentNamesIt(TestNamespace ns) { + Table table = ownedTable(ns, "otherconstraint"); + TableConstraint filed = constraint(ConstraintType.UNIQUE, "name"); + String primaryKey = JsonUtils.pojoToJson(constraint(ConstraintType.PRIMARY_KEY, "id")); + Task task = suggest(ns, table, "otherconstraint", filed, null); + awaitWorkflowTask(task); + + Task approved = resolve(SdkClients.adminClient(), task, Map.of("suggestedValue", primaryKey)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.PRIMARY_KEY, constraints.get(0).getConstraintType()); + assertEquals(List.of("id"), constraints.get(0).getColumns()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals( + Map.of("suggestedValue", primaryKey), + JsonUtils.getMap(stored.getResolution().getPayload())); + assertEquals( + JsonUtils.pojoToJson(filed), JsonUtils.getMap(stored.getPayload()).get("suggestedValue")); + assertEquals( + List.of("Added table constraint: PRIMARY_KEY on [id]"), + stored.getComments().stream().map(comment -> comment.getMessage()).toList()); + } + + @Test + void anApprovalWhoseApplyFailsLeavesNoCommentAndTheTaskOpen(TestNamespace ns) { + Table table = ownedTable(ns, "applyfails"); + Tag tag = createTag(ns, "applyfails"); + table.setTags(List.of(tagLabelOf(tag))); + table = SdkClients.adminClient().tables().update(table.getId().toString(), table); + Task task = suggest(ns, table, "applyfails", constraint(ConstraintType.UNIQUE, "name"), null); + awaitWorkflowTask(task); + tag.setDisabled(true); + SdkClients.adminClient().tags().update(tag.getId().toString(), tag); + + InvalidRequestException refused = + assertThrows( + InvalidRequestException.class, () -> resolve(SdkClients.adminClient(), task, null)); + + assertEquals( + "Tag label " + + tag.getFullyQualifiedName() + + " is disabled and can't be assigned to a data asset.", + refused.getMessage()); + assertEquals(400, refused.getStatusCode()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals(TaskEntityStatus.Open, stored.getStatus()); + assertEquals(List.of(), stored.getComments() == null ? List.of() : stored.getComments()); + assertEquals(List.of(), constraintsOf(table)); + } + @Test void theKeysOfAnOpenSuggestionCannotChangeAfterItIsFiled(TestNamespace ns) { Table table = ownedTable(ns, "frozen"); @@ -1258,6 +1317,33 @@ private static String fileRefused( .getMessage(); } + private static Tag createTag(TestNamespace ns, String name) { + Classification classification = + ns.trackRoot( + Entity.CLASSIFICATION, + SdkClients.adminClient() + .classifications() + .create( + new CreateClassification() + .withName(ns.shortPrefix("cls_" + name)) + .withDescription("A classification a table is tagged with"))); + return SdkClients.adminClient() + .tags() + .create( + new CreateTag() + .withName(ns.shortPrefix("tag_" + name)) + .withClassification(classification.getFullyQualifiedName()) + .withDescription("A tag a table is tagged with")); + } + + private static TagLabel tagLabelOf(Tag tag) { + return new TagLabel() + .withTagFQN(tag.getFullyQualifiedName()) + .withSource(TagLabel.TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL) + .withState(TagLabel.State.CONFIRMED); + } + private static Table adminTable(TestNamespace ns, String label) { DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns, service); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java index 67efc7829360..77258c31c185 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java @@ -54,8 +54,9 @@ * (ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint). A resolution cannot change a * task's suggestion type to or from {@code TableConstraint}. * - *

    Its payload holds only the keys that {@link SuggestionPayload} declares, so no other key can - * decide what approving the task needs or does. + *

    Apart from a key that a configured workflow writes, which makes approving the task refused, its + * payload holds only the keys that {@link SuggestionPayload} declares, so no other key can decide + * what approving the task needs or does. */ public final class TableConstraintSuggestion { public static final String TYPE = "TableConstraint"; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 1c1d5b2fde8c..9a34d875e6c3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -642,7 +642,10 @@ private Task applyTaskResolution( : "null", task.getAbout() != null); - addResolutionComment(task, taskRepository, approved, newValue, resolvedPayload, user); + // The text is decided on the entity as it is before the change, and posted only once the change + // has been applied, so a resolution whose change fails leaves no comment on the open task. + Optional commentMessage = + resolutionCommentOrEmpty(task, approved, resolvedPayload, newValue); // A memory conflict review decides on rejection too, and a refused decision must fail the // resolution. Other types mutate the target entity only on positive resolutions. @@ -661,6 +664,8 @@ private Task applyTaskResolution( task.getAbout() != null); } + postResolutionComment(task, taskRepository, commentMessage, user); + EntityReference resolvedByRef = Entity.getEntityReferenceByName(Entity.USER, user, Include.NON_DELETED); @@ -729,20 +734,26 @@ private void persistEditedWorkflowPayload( } } + private Optional resolutionCommentOrEmpty( + Task task, boolean approved, Object resolvedPayload, String newValue) { + try { + return resolutionComment(task, approved, resolvedPayload, newValue); + } catch (Exception e) { + LOG.warn( + "[TaskWorkflowHandler] Failed to build resolution comment for task '{}': {}", + task.getId(), + e.getMessage()); + return Optional.empty(); + } + } + /** * Add a comment to the task recording what was applied by whom. This creates an audit trail for - * task resolution. + * task resolution. A comment that cannot be written never fails a resolution that was applied. */ - private void addResolutionComment( - Task task, - TaskRepository taskRepository, - boolean approved, - String newValue, - Object resolvedPayload, - String user) { + private void postResolutionComment( + Task task, TaskRepository taskRepository, Optional commentMessage, String user) { try { - Optional commentMessage = - resolutionComment(task, approved, resolvedPayload, newValue); if (commentMessage.isPresent()) { EntityReference authorRef = Entity.getEntityReferenceByName(Entity.USER, user, Include.NON_DELETED); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java index fd04a0c8457d..eafa20599564 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -890,6 +890,14 @@ void anApprovalWithANewValue_namesTheFiledConstraintNotTheNewValue() { TaskWorkflowHandler.resolutionComment(task, true, null, OTHER)); } + @Test + void anApprovalWhosePayloadCarriesAnotherConstraint_namesThatConstraint() { + assertEquals( + Optional.of("Added table constraint: PRIMARY_KEY on [order_id]"), + TaskWorkflowHandler.resolutionComment( + taskWithValue(FILED), true, Map.of("suggestedValue", OTHER), null)); + } + @Test void anApprovalWithoutANewValue_namesTheFiledConstraint() { Task task = taskWithValue(FILED); From e128a5b5e0293111cd9cdca07fbf678febd4c7cf Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 30 Nov 2026 08:54:55 -0800 Subject: [PATCH 141/203] Test reject-all and the task tab's two call sites without transitions, and fix a licence header Reject-all of descriptions and of tags never resolves a table constraint suggestion. A constraint suggestion with no transitions sends only the keys its form declares through the resolve action and through the edit modal. The resolvePayload test file loses the extra header line that made the licence step write a second header. --- .../TaskTab/TaskTabNew.component.test.tsx | 75 +++++++++++++++++++ .../ui/src/rest/suggestionsAPI.test.ts | 27 +++++++ ...TaskFormSchemaUtils.resolvePayload.test.ts | 1 - 3 files changed, 102 insertions(+), 1 deletion(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx index fc0c41a18ee7..f9a01f189a39 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx @@ -11,6 +11,7 @@ * limitations under the License. */ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { act } from 'react'; import { MemoryRouter } from 'react-router-dom'; import { EntityType } from '../../../../enums/entity.enum'; @@ -2078,4 +2079,78 @@ describe('TaskTabNew resolving a workflow task with a form', () => { payload: filled, }); }); + + describe('with no transition to take', () => { + const noTransitions = (): Task => ({ + ...suggestion('TableConstraint', { + fieldPath: 'tableConstraints', + suggestedValue: CONSTRAINT, + }), + status: TaskEntityStatus.Open, + availableTransitions: [], + }); + + const renderWithNoTransitions = async () => { + const { useAuth } = require('../../../../hooks/authHooks'); + const { + getResolvedTaskFormSchema, + } = require('../../../../utils/TaskFormSchemaUtils'); + + useAuth.mockReturnValue({ isAdminUser: true }); + getResolvedTaskFormSchema.mockResolvedValue( + formSchema({ suggestedValue: { type: 'string' } }) + ); + await act(async () => { + render(, { + wrapper: MemoryRouter, + }); + }); + }; + + it('resolves a constraint suggestion through the resolve action with only the keys its form declares', async () => { + const { resolveTask } = require('../../../../rest/tasksAPI'); + await renderWithNoTransitions(); + + await act(async () => { + fireEvent.click(screen.getByTestId('edit-accept-task-action-primary')); + }); + + await waitFor(() => expect(resolveTask).toHaveBeenCalledTimes(1)); + + expect(resolveTask).toHaveBeenCalledWith(MOCK_WORKFLOW_TASK.id, { + resolutionType: 'Approved', + newValue: CONSTRAINT, + payload: { suggestedValue: CONSTRAINT }, + }); + }); + + it('resolves a constraint suggestion through the edit modal with only the keys its form declares', async () => { + const { resolveTask } = require('../../../../rest/tasksAPI'); + mockFilledPayload = { + fieldPath: 'tableConstraints', + suggestedValue: CONSTRAINT, + newDescription: 'a default', + }; + await renderWithNoTransitions(); + + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + await user.click(screen.getByTestId('edit-accept-task-action-trigger')); + await user.click(await screen.findByTestId('task-action-menu-item-edit')); + await act(async () => { + const fillButtons = await screen.findAllByTestId('fill-payload'); + fireEvent.click(fillButtons[fillButtons.length - 1]); + }); + await act(async () => { + fireEvent.click(screen.getByText('label.ok')); + }); + + await waitFor(() => expect(resolveTask).toHaveBeenCalledTimes(1)); + + expect(resolveTask).toHaveBeenCalledWith(MOCK_WORKFLOW_TASK.id, { + resolutionType: 'Approved', + newValue: CONSTRAINT, + payload: { suggestedValue: CONSTRAINT }, + }); + }); + }); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts b/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts index 82b9deb4058d..9fa00ae6af95 100644 --- a/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts @@ -379,5 +379,32 @@ describe('suggestionsAPI', () => { newValue: JSON.stringify(TAGS), }); }); + + it('reject-all of descriptions and of tags never resolves the constraint suggestion', async () => { + (APIClient.get as jest.Mock).mockResolvedValue(mixed()); + (resolveTask as jest.Mock).mockResolvedValue({}); + + for (const type of [ + SuggestionType.SuggestDescription, + SuggestionType.SuggestTagLabel, + ]) { + await approveRejectAllSuggestions( + 'user-1', + 'db.schema.my_table', + type, + SuggestionAction.Reject + ); + } + + expect(resolveTask).toHaveBeenCalledTimes(2); + expect(resolveTask).toHaveBeenNthCalledWith(1, 'task-desc', { + resolutionType: TaskResolutionType.Rejected, + newValue: 'description for task-desc', + }); + expect(resolveTask).toHaveBeenNthCalledWith(2, 'task-tag', { + resolutionType: TaskResolutionType.Rejected, + newValue: JSON.stringify(TAGS), + }); + }); }); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.resolvePayload.test.ts b/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.resolvePayload.test.ts index 72554120a4eb..d5b155c49dc5 100644 --- a/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.resolvePayload.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/utils/TaskFormSchemaUtils.resolvePayload.test.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. From 35fb39623e3f908faa48ba036a58a60486c852d9 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Mon, 30 Nov 2026 22:52:32 -0800 Subject: [PATCH 142/203] Say what a failed apply does for each task type, and test the comment of a rejection and of another type The record and a code comment said a failed apply leaves no comment for every task type. A suggestion of another type logs a failed apply and resolves with its comment. The text now says which resolutions leave no comment (a change that throws), adds the limit of reading the table before the change, and the Javadoc of the comment method says what the comment holds. New integration cases show that a rejection stores no comment and that an approval of a suggestion with a value stores its comment. New unit cases pin that the comment is posted before the task is resolved, that a rejection posts none, and that the comment is already posted when the resolution throws. --- ...stion-task-can-carry-a-table-constraint.md | 13 +++- .../TaskTableConstraintSuggestionIT.java | 52 +++++++++++++ .../service/tasks/TaskWorkflowHandler.java | 9 ++- .../tasks/TaskWorkflowHandlerTest.java | 77 +++++++++++++++++++ 4 files changed, 144 insertions(+), 7 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index 45cae94630ce..0b22a95db3e3 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,7 +1,7 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type); v7 2026-11-30 (the key rule names the keys a configured workflow writes; the resolution's payload holds the constraint added; an approval's comment names that constraint; the task tab sends only declared keys; the suggestion lists skip types they cannot show); v8 2026-11-30 (the comment is posted after the change is applied; the constraint added is read from the resolution's payload only when it carries one; the lists leave out a constraint suggestion only on the pages they fetched) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type); v7 2026-11-30 (the key rule names the keys a configured workflow writes; the resolution's payload holds the constraint added; an approval's comment names that constraint; the task tab sends only declared keys; the suggestion lists skip types they cannot show); v8 2026-11-30 (the comment is posted after the change is applied; the constraint added is read from the resolution's payload only when it carries one; the lists leave out a constraint suggestion only on the pages they fetched); v9 2026-11-30 (the record says what a failed apply does for each task type, and the order of the comment and the resolution) - **Deciders:** OpenMetadata maintainers - **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply, a new value under a value field outside the schema, a stored key that does not stop a rejection, the comment an approval leaves), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing by POST or PUT, patching, resolving and voting, a vote refused without storing its key, a patch that changes the type of a task; a task that carries every declared key; the comment of an approval whose payload carries another constraint; an approval whose apply fails leaves no comment) - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type @@ -56,9 +56,14 @@ declined. comment that an approval leaves on the task names the constraint that was added (its type, its columns and, for a foreign key, its referred columns), or says the table already had it; it never repeats a new value, and a rejection leaves none. The text is decided on the table as it was - before the change, and the comment is posted only after the change is applied, so an approval - whose apply fails leaves no comment on the task, which stays open. This holds for every task - type. A comment that cannot be written does not fail a resolution that was applied. + before the change, and the comment is posted only after the change returns, and before the task + is resolved. A change that throws therefore leaves no comment and the task stays open. That + covers a table constraint suggestion whose apply fails, and a memory conflict decision or a + metadata completion check that refuses. A suggestion of another type logs a failed apply and + resolves with its comment, as before. Another user can change the table between the read and the + apply, and then the comment can say "Added" for a constraint the other user added, or "already + has" for one this approval added. A comment that cannot be written does not fail a resolution + that was applied. - The task tab of the UI sends a constraint suggestion's resolution with the approver's comment as the resolution's own comment, and with a payload of only the keys the form of that transition declares, or none when the form declares none, because the form's data can hold a key the schema diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 07d352fb1deb..61c1a48956ea 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -842,6 +842,58 @@ void anApprovalWhoseApplyFailsLeavesNoCommentAndTheTaskOpen(TestNamespace ns) { assertEquals(List.of(), constraintsOf(table)); } + @Test + void aRejectionStoresNoCommentAndAddsNoConstraint(TestNamespace ns) { + Table table = adminTable(ns, "rejectnocomment"); + Task task = + suggest(ns, table, "rejectnocomment", constraint(ConstraintType.UNIQUE, "name"), null); + awaitWorkflowTask(task); + + Task rejected = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals(TaskEntityStatus.Rejected, rejected.getStatus()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals(TaskEntityStatus.Rejected, stored.getStatus()); + assertEquals(List.of(), stored.getComments() == null ? List.of() : stored.getComments()); + assertEquals(List.of(), constraintsOf(table)); + } + + @Test + void approvingADescriptionSuggestionWithAValueStoresItsComment(TestNamespace ns) { + Table table = adminTable(ns, "descriptioncomment"); + Task task = + file( + ns, + table, + "descriptioncomment", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "Orders placed by customers"), + null); + awaitWorkflowTask(task); + + Task approved = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Approved) + .withNewValue("An edited description")); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals( + List.of("Resolved with value: An edited description"), + stored.getComments().stream().map(comment -> comment.getMessage()).toList()); + } + @Test void theKeysOfAnOpenSuggestionCannotChangeAfterItIsFiled(TestNamespace ns) { Table table = ownedTable(ns, "frozen"); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 9a34d875e6c3..28ca44e4db61 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -643,7 +643,7 @@ private Task applyTaskResolution( task.getAbout() != null); // The text is decided on the entity as it is before the change, and posted only once the change - // has been applied, so a resolution whose change fails leaves no comment on the open task. + // has been applied, so a resolution whose change throws leaves no comment on the open task. Optional commentMessage = resolutionCommentOrEmpty(task, approved, resolvedPayload, newValue); @@ -748,8 +748,11 @@ private Optional resolutionCommentOrEmpty( } /** - * Add a comment to the task recording what was applied by whom. This creates an audit trail for - * task resolution. A comment that cannot be written never fails a resolution that was applied. + * Add the resolution's comment to the task as the resolver. The comment holds the text decided + * before the change: the constraint a table constraint approval adds, or the value an approval of + * another type carries. It is posted after the change returns and before the task is resolved, so + * a change that throws leaves no comment. A comment that cannot be written never fails a + * resolution that was applied. */ private void postResolutionComment( Task task, TaskRepository taskRepository, Optional commentMessage, String user) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java index 96215baa0e4b..eebddde78eac 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java @@ -152,6 +152,83 @@ void testRejectWithRequiresCommentTransitionAllowsMissingComment() { } } + @Test + void anApprovalPostsItsCommentAndThenResolvesTheTask() { + Task task = standaloneDescriptionTask(); + TaskRepository taskRepository = mock(TaskRepository.class); + when(taskRepository.resolveTask(any(), any(TaskResolution.class), any(), anyString(), any())) + .thenReturn(task); + + resolveStandalone(task, taskRepository, TaskResolutionType.Approved, "An edited description"); + + ArgumentCaptor posted = ArgumentCaptor.forClass(TaskComment.class); + var order = Mockito.inOrder(taskRepository); + order.verify(taskRepository).addComment(eq(task), posted.capture()); + order + .verify(taskRepository) + .resolveTask(eq(task), any(TaskResolution.class), any(), eq("alice"), any()); + assertEquals( + "Resolved with description: An edited description", posted.getValue().getMessage()); + } + + @Test + void aRejectionPostsNoCommentEvenWhenItCarriesAValue() { + Task task = standaloneDescriptionTask(); + TaskRepository taskRepository = mock(TaskRepository.class); + when(taskRepository.resolveTask(any(), any(TaskResolution.class), any(), anyString(), any())) + .thenReturn(task); + + resolveStandalone(task, taskRepository, TaskResolutionType.Rejected, "An edited description"); + + verify(taskRepository, never()).addComment(any(), any()); + verify(taskRepository) + .resolveTask(eq(task), any(TaskResolution.class), any(), eq("alice"), any()); + } + + @Test + void theCommentIsAlreadyPostedWhenTheResolutionThrows() { + Task task = standaloneDescriptionTask(); + TaskRepository taskRepository = mock(TaskRepository.class); + when(taskRepository.resolveTask(any(), any(TaskResolution.class), any(), anyString(), any())) + .thenThrow(new IllegalStateException("the task could not be saved")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + resolveStandalone( + task, taskRepository, TaskResolutionType.Approved, "An edited description")); + + assertEquals("the task could not be saved", thrown.getMessage()); + ArgumentCaptor posted = ArgumentCaptor.forClass(TaskComment.class); + verify(taskRepository).addComment(eq(task), posted.capture()); + assertEquals( + "Resolved with description: An edited description", posted.getValue().getMessage()); + } + + private static Task standaloneDescriptionTask() { + return new Task() + .withId(UUID.randomUUID()) + .withStatus(TaskEntityStatus.Open) + .withType(TaskEntityType.DescriptionUpdate); + } + + private static void resolveStandalone( + Task task, TaskRepository taskRepository, TaskResolutionType type, String newValue) { + WorkflowHandler workflowHandler = mock(WorkflowHandler.class); + EntityUtil.Fields fields = new EntityUtil.Fields(Set.of("about")); + try (MockedStatic workflowMock = Mockito.mockStatic(WorkflowHandler.class); + MockedStatic entityMock = Mockito.mockStatic(Entity.class)) { + workflowMock.when(WorkflowHandler::getInstance).thenReturn(workflowHandler); + when(workflowHandler.hasActiveRuntimeTask(task.getId())).thenReturn(false); + entityMock.when(() -> Entity.getEntityRepository(Entity.TASK)).thenReturn(taskRepository); + when(taskRepository.getFields(anyString())).thenReturn(fields); + + TaskWorkflowHandler.getInstance() + .resolveTask(task, null, type, newValue, null, null, "alice"); + } + } + @Test void testDefaultRuntimeTaskReadinessWaitIsBoundedBelowOneSecond() { assertTrue(TaskWorkflowHandler.DEFAULT_RUNTIME_TASK_READINESS_WAIT_MILLIS < 1_000L); From dc56c1925013940b858a64e1b9dcbb18d32298fb Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 06:21:01 -0800 Subject: [PATCH 143/203] Say when a resolution's comment is posted, and test a rejection that carries a comment, a description update's comment and the comment's author --- ...stion-task-can-carry-a-table-constraint.md | 4 +-- .../TaskTableConstraintSuggestionIT.java | 36 +++++++++++-------- .../service/tasks/TaskWorkflowHandler.java | 12 +++---- .../tasks/TaskWorkflowHandlerTest.java | 14 ++++++-- 4 files changed, 42 insertions(+), 24 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index 0b22a95db3e3..42eb8a55057f 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -59,8 +59,8 @@ declined. before the change, and the comment is posted only after the change returns, and before the task is resolved. A change that throws therefore leaves no comment and the task stays open. That covers a table constraint suggestion whose apply fails, and a memory conflict decision or a - metadata completion check that refuses. A suggestion of another type logs a failed apply and - resolves with its comment, as before. Another user can change the table between the read and the + metadata completion check that refuses. A suggestion of another type, or another task type such as a + description update, logs a failed apply and resolves with its comment, as before. Another user can change the table between the read and the apply, and then the comment can say "Added" for a constraint the other user added, or "already has" for one this approval added. A comment that cannot be written does not fail a resolution that was applied. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 61c1a48956ea..0ee42b9f70f0 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -61,6 +61,7 @@ import org.openmetadata.schema.type.BulkTaskOperationParams; import org.openmetadata.schema.type.BulkTaskOperationResult; import org.openmetadata.schema.type.BulkTaskOperationType; +import org.openmetadata.schema.type.DescriptionUpdatePayload; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TableConstraint.ConstraintType; import org.openmetadata.schema.type.TableConstraint.RelationshipType; @@ -787,6 +788,9 @@ void approvingWithANewValueAddsTheFiledConstraintAndTheCommentNamesIt(TestNamesp assertEquals( List.of("Added table constraint: UNIQUE on [name]"), stored.getComments().stream().map(comment -> comment.getMessage()).toList()); + assertEquals( + List.of("shared_user3"), + stored.getComments().stream().map(comment -> comment.getAuthor().getName()).toList()); } @Test @@ -854,7 +858,9 @@ void aRejectionStoresNoCommentAndAddsNoConstraint(TestNamespace ns) { .tasks() .resolve( task.getId().toString(), - new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + new ResolveTask() + .withResolutionType(TaskResolutionType.Rejected) + .withComment("Not unique")); assertEquals(TaskEntityStatus.Rejected, rejected.getStatus()); Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); @@ -864,19 +870,20 @@ void aRejectionStoresNoCommentAndAddsNoConstraint(TestNamespace ns) { } @Test - void approvingADescriptionSuggestionWithAValueStoresItsComment(TestNamespace ns) { + void approvingADescriptionUpdateWithAValueStoresItsCommentAndWritesTheValue(TestNamespace ns) { Table table = adminTable(ns, "descriptioncomment"); - Task task = - file( - ns, - table, - "descriptioncomment", - Map.of( - "suggestionType", "Description", - "fieldPath", "description", - "suggestedValue", "Orders placed by customers"), - null); - awaitWorkflowTask(task); + CreateTask request = + new CreateTask() + .withName(ns.prefix("description-update-comment")) + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.DescriptionUpdate) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload( + new DescriptionUpdatePayload() + .withFieldPath("description") + .withCurrentDescription(table.getDescription()) + .withNewDescription("A filed description")); + Task task = SdkClients.adminClient().tasks().create(request); Task approved = SdkClients.adminClient() @@ -888,9 +895,10 @@ void approvingADescriptionSuggestionWithAValueStoresItsComment(TestNamespace ns) .withNewValue("An edited description")); assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + assertEquals("An edited description", descriptionOf(table)); Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); assertEquals( - List.of("Resolved with value: An edited description"), + List.of("Resolved with description: An edited description"), stored.getComments().stream().map(comment -> comment.getMessage()).toList()); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 28ca44e4db61..37d528fa0ce6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -642,8 +642,8 @@ private Task applyTaskResolution( : "null", task.getAbout() != null); - // The text is decided on the entity as it is before the change, and posted only once the change - // has been applied, so a resolution whose change throws leaves no comment on the open task. + // The text is decided on the entity as it is before the change, and posted only after the + // change returns, so a resolution whose change throws leaves no comment on the open task. Optional commentMessage = resolutionCommentOrEmpty(task, approved, resolvedPayload, newValue); @@ -749,10 +749,10 @@ private Optional resolutionCommentOrEmpty( /** * Add the resolution's comment to the task as the resolver. The comment holds the text decided - * before the change: the constraint a table constraint approval adds, or the value an approval of - * another type carries. It is posted after the change returns and before the task is resolved, so - * a change that throws leaves no comment. A comment that cannot be written never fails a - * resolution that was applied. + * before the change: the constraint a table constraint approval adds, or that the table already + * has, or the value an approval of another type carries. It is posted after the change returns + * and before the task is resolved, so a change that throws leaves no comment. A comment that + * cannot be written never fails a resolution that was applied. */ private void postResolutionComment( Task task, TaskRepository taskRepository, Optional commentMessage, String user) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java index eebddde78eac..f7bee9bc2b3e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java @@ -178,7 +178,8 @@ void aRejectionPostsNoCommentEvenWhenItCarriesAValue() { when(taskRepository.resolveTask(any(), any(TaskResolution.class), any(), anyString(), any())) .thenReturn(task); - resolveStandalone(task, taskRepository, TaskResolutionType.Rejected, "An edited description"); + resolveStandalone( + task, taskRepository, TaskResolutionType.Rejected, "An edited description", "Not right"); verify(taskRepository, never()).addComment(any(), any()); verify(taskRepository) @@ -215,6 +216,15 @@ private static Task standaloneDescriptionTask() { private static void resolveStandalone( Task task, TaskRepository taskRepository, TaskResolutionType type, String newValue) { + resolveStandalone(task, taskRepository, type, newValue, null); + } + + private static void resolveStandalone( + Task task, + TaskRepository taskRepository, + TaskResolutionType type, + String newValue, + String comment) { WorkflowHandler workflowHandler = mock(WorkflowHandler.class); EntityUtil.Fields fields = new EntityUtil.Fields(Set.of("about")); try (MockedStatic workflowMock = Mockito.mockStatic(WorkflowHandler.class); @@ -225,7 +235,7 @@ private static void resolveStandalone( when(taskRepository.getFields(anyString())).thenReturn(fields); TaskWorkflowHandler.getInstance() - .resolveTask(task, null, type, newValue, null, null, "alice"); + .resolveTask(task, null, type, newValue, comment, null, "alice"); } } From ed6cc015efcab3e4c38040005603acc637fce65e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 06:33:43 -0800 Subject: [PATCH 144/203] Pass the comment of the rejection case as the comment --- .../org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java index f7bee9bc2b3e..6fdd4615a53d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java @@ -235,7 +235,7 @@ private static void resolveStandalone( when(taskRepository.getFields(anyString())).thenReturn(fields); TaskWorkflowHandler.getInstance() - .resolveTask(task, null, type, newValue, comment, null, "alice"); + .resolveTask(task, null, type, newValue, null, comment, "alice"); } } From 8c4a7950aed53e59f7dcaddedce3e9852bc53977 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 10:22:32 -0800 Subject: [PATCH 145/203] apps: check an app's configuration before the server stores it --- .../apps/AbstractNativeApplication.java | 8 ++ .../service/apps/ApplicationHandler.java | 46 ++++++++ .../apps/bundles/cache/CacheWarmupApp.java | 5 + .../insights/DataInsightsReportApp.java | 5 + .../service/apps/bundles/rdf/RdfIndexApp.java | 5 + .../bundles/searchIndex/SearchIndexApp.java | 5 + .../service/resources/apps/AppResource.java | 24 ++++- .../apps/AppConfigurationCheckTest.java | 101 ++++++++++++++++++ 8 files changed, 198 insertions(+), 1 deletion(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/AbstractNativeApplication.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/AbstractNativeApplication.java index 6ba3acb75cc5..e07ac6d422d0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/AbstractNativeApplication.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/AbstractNativeApplication.java @@ -141,6 +141,14 @@ protected void validateConfig(Map config) { LOG.warn("validateConfig is not implemented for this application. Skipping validation."); } + /** + * Check the configuration the server is about to store for this application. It reads only the + * configuration and has no side effect, so the server can call it on an instance that was never + * initialized. It is separate from {@link #validateConfig}, which an application may also use to + * refuse a run because of the server's state. By default every configuration is accepted. + */ + public void validateConfigForSave(Map config) {} + public void scheduleInternal() { // Validate Native Application AppRuntime runtime = JsonUtils.convertValue(app.getRuntime(), ScheduledExecutionContext.class); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java index 0b798afb433e..0c67fc7e1d9a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java @@ -10,8 +10,10 @@ import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.api.configuration.apps.AppPrivateConfig; @@ -184,6 +186,50 @@ public AbstractNativeApplication initializeApplicationForTrigger( } } + /** + * Ask the application to check the configuration that is about to be stored. The instance comes + * from its constructor alone: {@code init} registers the app in the application context and the + * install steps schedule it, and neither must happen for a configuration that may be refused. + */ + public void validateConfigurationForSave( + App app, CollectionDAO daoCollection, SearchRepository searchRepository) { + try { + Optional> nativeClass = + findNativeApplicationClass(app.getClassName()); + if (nativeClass.isPresent()) { + nativeClass + .get() + .getDeclaredConstructor(CollectionDAO.class, SearchRepository.class) + .newInstance(daoCollection, searchRepository) + .validateConfigForSave(configurationAsMap(app)); + } + } catch (NoSuchMethodException + | InvocationTargetException + | InstantiationException + | IllegalAccessException e) { + LOG.error("Failed to check the configuration of application {}", app.getName(), e); + throw AppException.byMessage( + app.getName(), "validateConfig", e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR); + } + } + + private static Optional> findNativeApplicationClass( + String className) { + try { + Class clz = Class.forName(className); + return AbstractNativeApplication.class.isAssignableFrom(clz) + ? Optional.of(clz.asSubclass(AbstractNativeApplication.class)) + : Optional.empty(); + } catch (ClassNotFoundException e) { + return Optional.empty(); + } + } + + private static Map configurationAsMap(App app) { + Map configuration = JsonUtils.getMap(app.getAppConfiguration()); + return configuration == null ? new HashMap<>() : configuration; + } + public void installApplication( App app, CollectionDAO daoCollection, SearchRepository searchRepository, String installedBy) { try { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java index c36bdb00d541..cca5fe3a6046 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java @@ -831,6 +831,11 @@ public void stop() { @Override protected void validateConfig(Map appConfig) { + validateConfigForSave(appConfig); + } + + @Override + public void validateConfigForSave(Map appConfig) { try { normalizeAppConfig(appConfig); } catch (IllegalArgumentException e) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsReportApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsReportApp.java index 664da68a633e..fff503562b8c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsReportApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsReportApp.java @@ -107,6 +107,11 @@ public void execute(JobExecutionContext jobExecutionContext) { @Override protected void validateConfig(Map config) { + validateConfigForSave(config); + } + + @Override + public void validateConfigForSave(Map config) { try { JsonUtils.convertValue(config, DataInsightsReportAppConfig.class); } catch (IllegalArgumentException e) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/rdf/RdfIndexApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/rdf/RdfIndexApp.java index cdf463f6fa3e..36ca3a7424f6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/rdf/RdfIndexApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/rdf/RdfIndexApp.java @@ -1074,6 +1074,11 @@ public void stop() { @Override protected void validateConfig(Map appConfig) { + validateConfigForSave(appConfig); + } + + @Override + public void validateConfigForSave(Map appConfig) { try { JsonUtils.convertValue(appConfig, EventPublisherJob.class); } catch (IllegalArgumentException e) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/SearchIndexApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/SearchIndexApp.java index 44daa1d9fe35..b5257745b180 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/SearchIndexApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/SearchIndexApp.java @@ -179,6 +179,11 @@ private void purgeSearchIndexTables() { @Override protected void validateConfig(Map appConfig) { + validateConfigForSave(appConfig); + } + + @Override + public void validateConfigForSave(Map appConfig) { try { JsonUtils.convertValue( SearchIndexAppConfigSanitizer.copyWithoutRemovedOptions(appConfig), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java index 1e4978b913bb..073f5babfdce 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java @@ -940,6 +940,7 @@ public Response create( securityContext, getResourceContext(), new OperationContext(APPLICATION, MetadataOperation.CREATE)); + validateConfigurationBeforeSave(app); if (SCHEDULED_TYPES.contains(app.getScheduleType())) { ApplicationHandler.getInstance() .installApplication( @@ -996,6 +997,7 @@ public Response patchApplication( if (reschedules) { authorizeAppOperation(securityContext, id, MetadataOperation.EDIT_ALL); } + validatePatchedConfiguration(app, patch); Response response = patchInternal(uriInfo, securityContext, id, patch); App updatedApp = (App) response.getEntity(); if (reschedules) { @@ -1012,8 +1014,26 @@ public Response patchApplication( return response; } + private static final String APP_CONFIGURATION_FIELD = "appConfiguration"; private static final Set SCHEDULE_OR_CONFIG_FIELDS = - Set.of("appSchedule", "appConfiguration"); + Set.of("appSchedule", APP_CONFIGURATION_FIELD); + + static boolean touchesConfiguration(JsonPatch patch) { + return JsonPatchUtils.replacesWholeDocument(patch) + || JsonUtils.extractPatchedFields(patch).contains(APP_CONFIGURATION_FIELD); + } + + /** Check the configuration a patch would store, before the patch is applied to the stored app. */ + private void validatePatchedConfiguration(App stored, JsonPatch patch) { + if (touchesConfiguration(patch)) { + validateConfigurationBeforeSave(JsonUtils.applyPatch(stored, patch, App.class)); + } + } + + private void validateConfigurationBeforeSave(App app) { + ApplicationHandler.getInstance() + .validateConfigurationForSave(app, Entity.getCollectionDAO(), searchRepository); + } /** * Whether a patch changes the schedule or configuration the app is installed with. A whole-document @@ -1067,6 +1087,7 @@ public Response patchApplication( if (reschedules) { authorizeAppOperation(securityContext, fqn, MetadataOperation.EDIT_ALL); } + validatePatchedConfiguration(app, patch); Response response = patchInternal(uriInfo, securityContext, fqn, patch); App updatedApp = (App) response.getEntity(); if (reschedules) { @@ -1117,6 +1138,7 @@ public Response createOrUpdate( : putResourceContext; authorizer.authorize( securityContext, new OperationContext(entityType, putOperation), authorizedContext); + validateConfigurationBeforeSave(app); AppScheduler.getInstance().deleteScheduledApplication(app); if (SCHEDULED_TYPES.contains(app.getScheduleType())) { ApplicationHandler.getInstance() diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java new file mode 100644 index 000000000000..e0acf097c8c0 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.apps; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; + +import jakarta.ws.rs.core.Response; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.bundles.cache.CacheWarmupApp; +import org.openmetadata.service.apps.bundles.insights.DataInsightsReportApp; +import org.openmetadata.service.apps.bundles.rdf.RdfIndexApp; +import org.openmetadata.service.apps.bundles.searchIndex.SearchIndexApp; +import org.openmetadata.service.exception.AppException; +import org.openmetadata.service.jdbi3.CollectionDAO; + +class AppConfigurationCheckTest { + + private static final Map BAD_BATCH_SIZE = Map.of("batchSize", "many"); + + @Test + void defaultCheckAcceptsEveryConfiguration() { + AbstractNativeApplication app = new AbstractNativeApplication(null, null); + + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("anything", Map.of("at", "all")))); + } + + @Test + void searchIndexAppRefusesAStringBatchSize() { + SearchIndexApp app = new SearchIndexApp(null, null); + + AppException refused = + assertThrows(AppException.class, () -> app.validateConfigForSave(BAD_BATCH_SIZE)); + + assertRefusedWith("Invalid App Configuration: Cannot deserialize value of type", refused); + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("batchSize", 100))); + } + + @Test + void cacheWarmupAppRefusesAStringBatchSize() { + CacheWarmupApp app = new CacheWarmupApp(null, null); + + AppException refused = + assertThrows(AppException.class, () -> app.validateConfigForSave(BAD_BATCH_SIZE)); + + assertRefusedWith("Invalid App Configuration: Cannot deserialize value of type", refused); + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("batchSize", 100))); + } + + @Test + void rdfIndexAppRefusesAStringBatchSize() { + RdfIndexApp app = new RdfIndexApp(null, null); + + AppException refused = + assertThrows(AppException.class, () -> app.validateConfigForSave(BAD_BATCH_SIZE)); + + assertEquals("Invalid App Configuration", refused.getMessage()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), refused.getResponse().getStatus()); + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("batchSize", 100))); + } + + @Test + void dataInsightsReportAppRefusesAStringFlag() { + try (MockedStatic entity = mockStatic(Entity.class)) { + entity + .when(Entity::getCollectionDAO) + .thenReturn(mock(CollectionDAO.class, Answers.RETURNS_DEEP_STUBS)); + DataInsightsReportApp app = new DataInsightsReportApp(null, null); + + AppException refused = + assertThrows( + AppException.class, () -> app.validateConfigForSave(Map.of("sendToAdmins", "maybe"))); + + assertRefusedWith("Invalid DataInsightsReportAppConfig configuration: ", refused); + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("sendToAdmins", false))); + } + } + + private static void assertRefusedWith(String messagePrefix, AppException refused) { + assertTrue(refused.getMessage().startsWith(messagePrefix), refused.getMessage()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), refused.getResponse().getStatus()); + } +} From da1b666d004a709c1528dcbff83123efef18785a Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 10:32:01 -0800 Subject: [PATCH 146/203] apps: integration tests and a record for the configuration check --- ...-is-checked-before-the-server-stores-it.md | 45 ++++ .../it/tests/AppConfigurationIT.java | 232 +++++++++++++++++- 2 files changed, 275 insertions(+), 2 deletions(-) create mode 100644 docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md diff --git a/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md b/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md new file mode 100644 index 000000000000..593643dd242f --- /dev/null +++ b/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md @@ -0,0 +1,45 @@ +# An app's configuration is checked before the server stores it, by a method separate from the check before a run + +- **Status:** Accepted +- **Revisions:** v1 2026-12-01 (initial) +- **Deciders:** OpenMetadata maintainers +- **Guard:** `AppConfigurationCheckTest` (each shipped app refuses a configuration it cannot read, with its message, and accepts a good one; the default accepts every configuration), `AppConfigurationIT` (a refused configuration on POST, PUT, PATCH by id and PATCH by name answers 400 and leaves the stored app and its schedule as they were; an accepted one is stored and rescheduled) +- **Related:** none + +## Context + +An app's settings are its `appConfiguration`. The PATCH paths of `AppResource` stored the patched +app first, then deleted the scheduled job, and only then asked the app to install itself, so an app +that refused the new configuration answered 400 after the refused configuration was stored. A later +GET returned it, and every later reinstall (`/schedule`, `/restore`, `/deploy`) read it. The PUT path +deleted the scheduled job before it installed, so a refused PUT stored nothing but left the app +unscheduled. `SearchIndexApp`, `CacheWarmupApp`, `RdfIndexApp` and `DataInsightsReportApp` checked +their configuration only in `validateConfig`, which runs before a trigger, so a configuration they +could not read was stored and failed at the next run. + +## Decision + +- `AbstractNativeApplication#validateConfigForSave(Map)` checks the configuration + an app is about to store. It reads only the configuration and has no side effect. By default it + accepts every configuration. +- It is a separate method from `validateConfig`. An app may use `validateConfig` to refuse a run + because of the server's state rather than the configuration's content, and such an app must still be + able to save its settings. The four shipped apps move their parse into the new method, and their + `validateConfig` calls it, so the check before a trigger and its messages are unchanged. +- `AppResource` runs the check on POST, PUT, and both PATCH paths, after authorization and before + the store and before any scheduler change. For a PATCH the patch is applied to the stored app in + memory to get the configuration that would be stored, and a patch that does not touch + `appConfiguration` is not checked. A refused check answers 400 with the app's message. +- `ApplicationHandler#validateConfigurationForSave` reaches the method on an instance built by the + app's constructor alone. It does not call `init`, which registers the app in the application + context and, for some apps, parses the configuration, and it does not install, schedule or store + anything, and it changes no bot or role. A class that is not a native application, or that cannot + be found, has nothing to check. + +## Consequences + +- An app that shipped with a configuration its check now refuses is not changed by this record. The + check applies to the next write. +- A new app that validates its settings overrides `validateConfigForSave`, and its constructor must + stay free of side effects, because the server builds an instance for each write. +- Revisit if an app needs the stored app, not only the configuration, to decide. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java index 9cf118550b2b..2b8ed0fbd437 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java @@ -6,8 +6,10 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import com.fasterxml.jackson.databind.JsonNode; +import jakarta.ws.rs.core.Response; import java.time.Duration; import java.util.List; import java.util.Map; @@ -16,16 +18,19 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.teams.CreateUser; import org.openmetadata.schema.entity.app.App; import org.openmetadata.schema.entity.app.AppMarketPlaceDefinition; +import org.openmetadata.schema.entity.app.AppSchedule; import org.openmetadata.schema.entity.app.AppType; import org.openmetadata.schema.entity.app.CreateApp; import org.openmetadata.schema.entity.app.CreateAppMarketPlaceDefinitionReq; import org.openmetadata.schema.entity.app.NativeAppPermission; +import org.openmetadata.schema.entity.app.ScheduleTimeline; import org.openmetadata.schema.entity.app.ScheduleType; import org.openmetadata.schema.entity.app.ScheduledExecutionContext; import org.openmetadata.schema.entity.teams.User; @@ -36,8 +41,17 @@ import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.AbstractNativeApplication; +import org.openmetadata.service.apps.scheduler.AppScheduler; import org.openmetadata.service.audit.AuditLogRepository; +import org.openmetadata.service.exception.AppException; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.search.SearchRepository; +import org.quartz.CronTrigger; +import org.quartz.SchedulerException; +import org.quartz.TriggerKey; @Execution(ExecutionMode.CONCURRENT) @ExtendWith(TestNamespaceExtension.class) @@ -158,6 +172,215 @@ void existingAppRecordsUseTheCurrentProjection(TestNamespace ns) { assertTrue(entries.get(0).has("changeEvent")); } + @Test + void patchByIdWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> patch("/v1/apps/" + app.getId(), batchSizePatch("many"))); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void patchByNameWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + createCheckedApp(name, 100); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> patch("/v1/apps/name/" + name, batchSizePatch("many"))); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void putWithARefusedConfigurationStoresNothingAndKeepsTheSchedule(TestNamespace ns) + throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + createCheckedApp(name, 100); + try { + CreateApp replacement = + checkedRequest(name, "many").withAppSchedule(schedule(ScheduleTimeline.MONTHLY)); + + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.PUT, "/v1/apps", replacement, App.class)); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void postWithARefusedConfigurationStoresNoApp(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute( + HttpMethod.POST, "/v1/apps", checkedRequest(name, "many"), App.class)); + + assertRefused(refused); + OpenMetadataException missing = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.GET, "/v1/apps/name/" + name, null, App.class)); + assertEquals(404, missing.getStatusCode(), missing.getMessage()); + assertNull(scheduledTrigger(name)); + } finally { + uninstallIfPresent(name); + } + } + + @Test + void anAcceptedConfigurationIsStoredAndTheAppIsRescheduled(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + try { + patch( + "/v1/apps/" + app.getId(), + "[{\"op\":\"replace\",\"path\":\"/appConfiguration/batchSize\",\"value\":250}," + + "{\"op\":\"replace\",\"path\":\"/appSchedule/scheduleTimeline\"," + + "\"value\":\"Monthly\"}]"); + + App stored = getApp(name); + assertEquals(Map.of("batchSize", 250), stored.getAppConfiguration()); + assertEquals(ScheduleTimeline.MONTHLY, stored.getAppSchedule().getScheduleTimeline()); + assertEquals("0 0 0 1 * ?", scheduledTrigger(name).getCronExpression()); + } finally { + uninstall(name); + } + } + + private static void assumeEmbeddedServer() { + assumeFalse(OssTestServer.isExternalMode(), "Reads the scheduler inside the embedded server"); + } + + private String createCheckedDefinition(TestNamespace ns) { + return createDefinition(ns, CheckedConfigurationApp.class.getName(), ScheduleType.Scheduled); + } + + private static CreateApp checkedRequest(String name, Object batchSize) { + return new CreateApp() + .withName(name) + .withAppConfiguration(Map.of("batchSize", batchSize)) + .withAppSchedule(schedule(ScheduleTimeline.HOURLY)); + } + + private static AppSchedule schedule(ScheduleTimeline timeline) { + return new AppSchedule().withScheduleTimeline(timeline); + } + + private static App createCheckedApp(String name, Object batchSize) { + return SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.POST, "/v1/apps", checkedRequest(name, batchSize), App.class); + } + + private static String batchSizePatch(String value) { + return "[{\"op\":\"replace\",\"path\":\"/appConfiguration/batchSize\",\"value\":\"" + + value + + "\"}]"; + } + + private static void patch(String path, String body) { + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + path, + body, + RequestOptions.builder().header("Content-Type", "application/json-patch+json").build()); + } + + private static App getApp(String name) { + return SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.GET, "/v1/apps/name/" + name, null, App.class); + } + + private static void uninstall(String name) { + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.DELETE, "/v1/apps/name/" + name + "?hardDelete=true", null, Void.class); + } + + private static void uninstallIfPresent(String name) { + try { + uninstall(name); + } catch (OpenMetadataException absent) { + assertEquals(404, absent.getStatusCode(), absent.getMessage()); + } + } + + private static CronTrigger scheduledTrigger(String name) throws SchedulerException { + return (CronTrigger) + AppScheduler.getInstance() + .getScheduler() + .getTrigger(new TriggerKey(name, AppScheduler.APPS_TRIGGER_GROUP)); + } + + private static void assertRefused(OpenMetadataException refused) { + assertEquals(400, refused.getStatusCode(), refused.getMessage()); + assertTrue( + refused.getMessage().contains("Invalid checked configuration: batchSize must be a number"), + refused.getMessage()); + } + + private static void assertStoredUnchanged(String name) throws SchedulerException { + App stored = getApp(name); + assertEquals(Map.of("batchSize", 100), stored.getAppConfiguration()); + assertEquals(ScheduleTimeline.HOURLY, stored.getAppSchedule().getScheduleTimeline()); + assertEquals("0 0 * ? * *", scheduledTrigger(name).getCronExpression()); + } + + /** An app that reads {@code batchSize} as a number and refuses any other configuration. */ + public static final class CheckedConfigurationApp extends AbstractNativeApplication { + public CheckedConfigurationApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { + super(collectionDAO, searchRepository); + } + + @Override + public void validateConfigForSave(Map config) { + if (!(config.get("batchSize") instanceof Number)) { + throw AppException.byMessage( + Response.Status.BAD_REQUEST, + "Invalid checked configuration: batchSize must be a number"); + } + } + } + private User createOwner(TestNamespace ns) { String name = ns.shortPrefix() + "owner_" + UUID.randomUUID().toString().substring(0, 6); return ns.trackRoot( @@ -172,6 +395,11 @@ private User createOwner(TestNamespace ns) { } private String createDefinition(TestNamespace ns) { + return createDefinition( + ns, "org.openmetadata.service.apps.AbstractNativeApplication", ScheduleType.NoSchedule); + } + + private String createDefinition(TestNamespace ns, String className, ScheduleType scheduleType) { String name = ns.shortPrefix() + "Config" + UUID.randomUUID().toString().substring(0, 6); AppMarketPlaceDefinition definition = SdkClients.adminClient() @@ -188,9 +416,9 @@ private String createDefinition(TestNamespace ns) { .withDeveloperUrl("https://www.example.com") .withPrivacyPolicyUrl("https://www.example.com/privacy") .withSupportEmail("support@example.com") - .withClassName("org.openmetadata.service.apps.AbstractNativeApplication") + .withClassName(className) .withAppType(AppType.Internal) - .withScheduleType(ScheduleType.NoSchedule) + .withScheduleType(scheduleType) .withRuntime(new ScheduledExecutionContext().withEnabled(true)) .withAppConfiguration(Map.of()) .withPermission(NativeAppPermission.All), From dd304f52bde2dea078a2856018bd00c3def9406b Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 10:44:29 -0800 Subject: [PATCH 147/203] apps: serialize the tests that schedule apps in the job store --- .../java/org/openmetadata/it/tests/AppConfigurationIT.java | 7 +++++++ .../java/org/openmetadata/it/util/SharedResourceLocks.java | 3 +++ 2 files changed, 10 insertions(+) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java index 2b8ed0fbd437..3fd70ddbdc1c 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java @@ -18,8 +18,10 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.teams.CreateUser; @@ -173,6 +175,7 @@ void existingAppRecordsUseTheCurrentProjection(TestNamespace ns) { } @Test + @ResourceLock(SharedResourceLocks.APP_SCHEDULES) void patchByIdWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { assumeEmbeddedServer(); String name = createCheckedDefinition(ns); @@ -191,6 +194,7 @@ void patchByIdWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Ex } @Test + @ResourceLock(SharedResourceLocks.APP_SCHEDULES) void patchByNameWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { assumeEmbeddedServer(); String name = createCheckedDefinition(ns); @@ -209,6 +213,7 @@ void patchByNameWithARefusedConfigurationStoresNothing(TestNamespace ns) throws } @Test + @ResourceLock(SharedResourceLocks.APP_SCHEDULES) void putWithARefusedConfigurationStoresNothingAndKeepsTheSchedule(TestNamespace ns) throws Exception { assumeEmbeddedServer(); @@ -234,6 +239,7 @@ void putWithARefusedConfigurationStoresNothingAndKeepsTheSchedule(TestNamespace } @Test + @ResourceLock(SharedResourceLocks.APP_SCHEDULES) void postWithARefusedConfigurationStoresNoApp(TestNamespace ns) throws Exception { assumeEmbeddedServer(); String name = createCheckedDefinition(ns); @@ -263,6 +269,7 @@ void postWithARefusedConfigurationStoresNoApp(TestNamespace ns) throws Exception } @Test + @ResourceLock(SharedResourceLocks.APP_SCHEDULES) void anAcceptedConfigurationIsStoredAndTheAppIsRescheduled(TestNamespace ns) throws Exception { assumeEmbeddedServer(); String name = createCheckedDefinition(ns); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java index 3242bce7caad..efef4c47c27a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java @@ -1,6 +1,9 @@ package org.openmetadata.it.util; public final class SharedResourceLocks { + /** Tests that schedule and unschedule apps in the Postgres-backed job store one at a time. */ + public static final String APP_SCHEDULES = "appSchedules"; + public static final String APP_RUN_RECORDS = "appRunRecords"; public static final String GLOSSARY_TERM_RELATION_SETTINGS = "glossaryTermRelationSettings"; public static final String OPEN_LINEAGE_SETTINGS = "openLineageSettings"; From 3c81ac6ffdec952a38f3e5e87a0a383386b9b949 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 14:14:28 -0800 Subject: [PATCH 148/203] Test that a resolution comment's author is the resolver, and tidy the record's revisions and wrapping --- ...11-26-a-suggestion-task-can-carry-a-table-constraint.md | 7 ++++--- .../it/tests/TaskTableConstraintSuggestionIT.java | 3 +++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md index 42eb8a55057f..277a011f7277 100644 --- a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -1,7 +1,7 @@ # A suggestion task can carry a table constraint, and approving it adds the constraint as the approver - **Status:** Accepted -- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type); v7 2026-11-30 (the key rule names the keys a configured workflow writes; the resolution's payload holds the constraint added; an approval's comment names that constraint; the task tab sends only declared keys; the suggestion lists skip types they cannot show); v8 2026-11-30 (the comment is posted after the change is applied; the constraint added is read from the resolution's payload only when it carries one; the lists leave out a constraint suggestion only on the pages they fetched); v9 2026-11-30 (the record says what a failed apply does for each task type, and the order of the comment and the resolution) +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type); v7 2026-11-30 (the key rule names the keys a configured workflow writes; the resolution's payload holds the constraint added; an approval's comment names that constraint; the task tab sends only declared keys; the suggestion lists skip types they cannot show); v8 2026-11-30 (the comment is posted after the change is applied; the constraint added is read from the resolution's payload only when it carries one; the lists leave out a constraint suggestion only on the pages they fetched); v9 2026-11-30 (the record says what a failed apply does for each task type, and the order of the comment and the resolution); v10 2026-12-01 (a description update task is named among the task types whose failed apply still resolves with its comment) - **Deciders:** OpenMetadata maintainers - **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply, a new value under a value field outside the schema, a stored key that does not stop a rejection, the comment an approval leaves), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing by POST or PUT, patching, resolving and voting, a vote refused without storing its key, a patch that changes the type of a task; a task that carries every declared key; the comment of an approval whose payload carries another constraint; an approval whose apply fails leaves no comment) - **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type @@ -59,8 +59,9 @@ declined. before the change, and the comment is posted only after the change returns, and before the task is resolved. A change that throws therefore leaves no comment and the task stays open. That covers a table constraint suggestion whose apply fails, and a memory conflict decision or a - metadata completion check that refuses. A suggestion of another type, or another task type such as a - description update, logs a failed apply and resolves with its comment, as before. Another user can change the table between the read and the + metadata completion check that refuses. A suggestion of another type, or another task type such + as a description update, logs a failed apply and resolves with its comment, as before. Another + user can change the table between the read and the apply, and then the comment can say "Added" for a constraint the other user added, or "already has" for one this approval added. A comment that cannot be written does not fail a resolution that was applied. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java index 0ee42b9f70f0..8fc78547db58 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -817,6 +817,9 @@ void approvingWithAnotherConstraintInThePayloadAddsItAndTheCommentNamesIt(TestNa assertEquals( List.of("Added table constraint: PRIMARY_KEY on [id]"), stored.getComments().stream().map(comment -> comment.getMessage()).toList()); + assertEquals( + List.of("admin"), + stored.getComments().stream().map(comment -> comment.getAuthor().getName()).toList()); } @Test From dd96f5eccf386468ac0b834f502e4cc6c195aaab Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 17:33:25 -0800 Subject: [PATCH 149/203] apps: run the configuration check tests in a class of their own The tests install and remove apps in the shared job store, which a concurrent install of another app can break. They now live in an isolated class, like the other app tests that change the job store. --- .../it/tests/AppConfigurationIT.java | 239 +------------- .../it/tests/AppConfigurationSaveCheckIT.java | 301 ++++++++++++++++++ .../it/util/SharedResourceLocks.java | 3 - 3 files changed, 303 insertions(+), 240 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java index 3fd70ddbdc1c..9cf118550b2b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationIT.java @@ -6,10 +6,8 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; import com.fasterxml.jackson.databind.JsonNode; -import jakarta.ws.rs.core.Response; import java.time.Duration; import java.util.List; import java.util.Map; @@ -18,21 +16,16 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.api.parallel.ResourceLock; -import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.SdkClients; -import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.teams.CreateUser; import org.openmetadata.schema.entity.app.App; import org.openmetadata.schema.entity.app.AppMarketPlaceDefinition; -import org.openmetadata.schema.entity.app.AppSchedule; import org.openmetadata.schema.entity.app.AppType; import org.openmetadata.schema.entity.app.CreateApp; import org.openmetadata.schema.entity.app.CreateAppMarketPlaceDefinitionReq; import org.openmetadata.schema.entity.app.NativeAppPermission; -import org.openmetadata.schema.entity.app.ScheduleTimeline; import org.openmetadata.schema.entity.app.ScheduleType; import org.openmetadata.schema.entity.app.ScheduledExecutionContext; import org.openmetadata.schema.entity.teams.User; @@ -43,17 +36,8 @@ import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.network.HttpMethod; -import org.openmetadata.sdk.network.RequestOptions; import org.openmetadata.service.Entity; -import org.openmetadata.service.apps.AbstractNativeApplication; -import org.openmetadata.service.apps.scheduler.AppScheduler; import org.openmetadata.service.audit.AuditLogRepository; -import org.openmetadata.service.exception.AppException; -import org.openmetadata.service.jdbi3.CollectionDAO; -import org.openmetadata.service.search.SearchRepository; -import org.quartz.CronTrigger; -import org.quartz.SchedulerException; -import org.quartz.TriggerKey; @Execution(ExecutionMode.CONCURRENT) @ExtendWith(TestNamespaceExtension.class) @@ -174,220 +158,6 @@ void existingAppRecordsUseTheCurrentProjection(TestNamespace ns) { assertTrue(entries.get(0).has("changeEvent")); } - @Test - @ResourceLock(SharedResourceLocks.APP_SCHEDULES) - void patchByIdWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { - assumeEmbeddedServer(); - String name = createCheckedDefinition(ns); - App app = createCheckedApp(name, 100); - try { - OpenMetadataException refused = - assertThrows( - OpenMetadataException.class, - () -> patch("/v1/apps/" + app.getId(), batchSizePatch("many"))); - - assertRefused(refused); - assertStoredUnchanged(name); - } finally { - uninstall(name); - } - } - - @Test - @ResourceLock(SharedResourceLocks.APP_SCHEDULES) - void patchByNameWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { - assumeEmbeddedServer(); - String name = createCheckedDefinition(ns); - createCheckedApp(name, 100); - try { - OpenMetadataException refused = - assertThrows( - OpenMetadataException.class, - () -> patch("/v1/apps/name/" + name, batchSizePatch("many"))); - - assertRefused(refused); - assertStoredUnchanged(name); - } finally { - uninstall(name); - } - } - - @Test - @ResourceLock(SharedResourceLocks.APP_SCHEDULES) - void putWithARefusedConfigurationStoresNothingAndKeepsTheSchedule(TestNamespace ns) - throws Exception { - assumeEmbeddedServer(); - String name = createCheckedDefinition(ns); - createCheckedApp(name, 100); - try { - CreateApp replacement = - checkedRequest(name, "many").withAppSchedule(schedule(ScheduleTimeline.MONTHLY)); - - OpenMetadataException refused = - assertThrows( - OpenMetadataException.class, - () -> - SdkClients.adminClient() - .getHttpClient() - .execute(HttpMethod.PUT, "/v1/apps", replacement, App.class)); - - assertRefused(refused); - assertStoredUnchanged(name); - } finally { - uninstall(name); - } - } - - @Test - @ResourceLock(SharedResourceLocks.APP_SCHEDULES) - void postWithARefusedConfigurationStoresNoApp(TestNamespace ns) throws Exception { - assumeEmbeddedServer(); - String name = createCheckedDefinition(ns); - try { - OpenMetadataException refused = - assertThrows( - OpenMetadataException.class, - () -> - SdkClients.adminClient() - .getHttpClient() - .execute( - HttpMethod.POST, "/v1/apps", checkedRequest(name, "many"), App.class)); - - assertRefused(refused); - OpenMetadataException missing = - assertThrows( - OpenMetadataException.class, - () -> - SdkClients.adminClient() - .getHttpClient() - .execute(HttpMethod.GET, "/v1/apps/name/" + name, null, App.class)); - assertEquals(404, missing.getStatusCode(), missing.getMessage()); - assertNull(scheduledTrigger(name)); - } finally { - uninstallIfPresent(name); - } - } - - @Test - @ResourceLock(SharedResourceLocks.APP_SCHEDULES) - void anAcceptedConfigurationIsStoredAndTheAppIsRescheduled(TestNamespace ns) throws Exception { - assumeEmbeddedServer(); - String name = createCheckedDefinition(ns); - App app = createCheckedApp(name, 100); - try { - patch( - "/v1/apps/" + app.getId(), - "[{\"op\":\"replace\",\"path\":\"/appConfiguration/batchSize\",\"value\":250}," - + "{\"op\":\"replace\",\"path\":\"/appSchedule/scheduleTimeline\"," - + "\"value\":\"Monthly\"}]"); - - App stored = getApp(name); - assertEquals(Map.of("batchSize", 250), stored.getAppConfiguration()); - assertEquals(ScheduleTimeline.MONTHLY, stored.getAppSchedule().getScheduleTimeline()); - assertEquals("0 0 0 1 * ?", scheduledTrigger(name).getCronExpression()); - } finally { - uninstall(name); - } - } - - private static void assumeEmbeddedServer() { - assumeFalse(OssTestServer.isExternalMode(), "Reads the scheduler inside the embedded server"); - } - - private String createCheckedDefinition(TestNamespace ns) { - return createDefinition(ns, CheckedConfigurationApp.class.getName(), ScheduleType.Scheduled); - } - - private static CreateApp checkedRequest(String name, Object batchSize) { - return new CreateApp() - .withName(name) - .withAppConfiguration(Map.of("batchSize", batchSize)) - .withAppSchedule(schedule(ScheduleTimeline.HOURLY)); - } - - private static AppSchedule schedule(ScheduleTimeline timeline) { - return new AppSchedule().withScheduleTimeline(timeline); - } - - private static App createCheckedApp(String name, Object batchSize) { - return SdkClients.adminClient() - .getHttpClient() - .execute(HttpMethod.POST, "/v1/apps", checkedRequest(name, batchSize), App.class); - } - - private static String batchSizePatch(String value) { - return "[{\"op\":\"replace\",\"path\":\"/appConfiguration/batchSize\",\"value\":\"" - + value - + "\"}]"; - } - - private static void patch(String path, String body) { - SdkClients.adminClient() - .getHttpClient() - .executeForString( - HttpMethod.PATCH, - path, - body, - RequestOptions.builder().header("Content-Type", "application/json-patch+json").build()); - } - - private static App getApp(String name) { - return SdkClients.adminClient() - .getHttpClient() - .execute(HttpMethod.GET, "/v1/apps/name/" + name, null, App.class); - } - - private static void uninstall(String name) { - SdkClients.adminClient() - .getHttpClient() - .execute(HttpMethod.DELETE, "/v1/apps/name/" + name + "?hardDelete=true", null, Void.class); - } - - private static void uninstallIfPresent(String name) { - try { - uninstall(name); - } catch (OpenMetadataException absent) { - assertEquals(404, absent.getStatusCode(), absent.getMessage()); - } - } - - private static CronTrigger scheduledTrigger(String name) throws SchedulerException { - return (CronTrigger) - AppScheduler.getInstance() - .getScheduler() - .getTrigger(new TriggerKey(name, AppScheduler.APPS_TRIGGER_GROUP)); - } - - private static void assertRefused(OpenMetadataException refused) { - assertEquals(400, refused.getStatusCode(), refused.getMessage()); - assertTrue( - refused.getMessage().contains("Invalid checked configuration: batchSize must be a number"), - refused.getMessage()); - } - - private static void assertStoredUnchanged(String name) throws SchedulerException { - App stored = getApp(name); - assertEquals(Map.of("batchSize", 100), stored.getAppConfiguration()); - assertEquals(ScheduleTimeline.HOURLY, stored.getAppSchedule().getScheduleTimeline()); - assertEquals("0 0 * ? * *", scheduledTrigger(name).getCronExpression()); - } - - /** An app that reads {@code batchSize} as a number and refuses any other configuration. */ - public static final class CheckedConfigurationApp extends AbstractNativeApplication { - public CheckedConfigurationApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { - super(collectionDAO, searchRepository); - } - - @Override - public void validateConfigForSave(Map config) { - if (!(config.get("batchSize") instanceof Number)) { - throw AppException.byMessage( - Response.Status.BAD_REQUEST, - "Invalid checked configuration: batchSize must be a number"); - } - } - } - private User createOwner(TestNamespace ns) { String name = ns.shortPrefix() + "owner_" + UUID.randomUUID().toString().substring(0, 6); return ns.trackRoot( @@ -402,11 +172,6 @@ private User createOwner(TestNamespace ns) { } private String createDefinition(TestNamespace ns) { - return createDefinition( - ns, "org.openmetadata.service.apps.AbstractNativeApplication", ScheduleType.NoSchedule); - } - - private String createDefinition(TestNamespace ns, String className, ScheduleType scheduleType) { String name = ns.shortPrefix() + "Config" + UUID.randomUUID().toString().substring(0, 6); AppMarketPlaceDefinition definition = SdkClients.adminClient() @@ -423,9 +188,9 @@ private String createDefinition(TestNamespace ns, String className, ScheduleType .withDeveloperUrl("https://www.example.com") .withPrivacyPolicyUrl("https://www.example.com/privacy") .withSupportEmail("support@example.com") - .withClassName(className) + .withClassName("org.openmetadata.service.apps.AbstractNativeApplication") .withAppType(AppType.Internal) - .withScheduleType(scheduleType) + .withScheduleType(ScheduleType.NoSchedule) .withRuntime(new ScheduledExecutionContext().withEnabled(true)) .withAppConfiguration(Map.of()) .withPermission(NativeAppPermission.All), diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java new file mode 100644 index 000000000000..c7e40efa10f4 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java @@ -0,0 +1,301 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import jakarta.ws.rs.core.Response; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.OssTestServer; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.app.App; +import org.openmetadata.schema.entity.app.AppMarketPlaceDefinition; +import org.openmetadata.schema.entity.app.AppSchedule; +import org.openmetadata.schema.entity.app.AppType; +import org.openmetadata.schema.entity.app.CreateApp; +import org.openmetadata.schema.entity.app.CreateAppMarketPlaceDefinitionReq; +import org.openmetadata.schema.entity.app.NativeAppPermission; +import org.openmetadata.schema.entity.app.ScheduleTimeline; +import org.openmetadata.schema.entity.app.ScheduleType; +import org.openmetadata.schema.entity.app.ScheduledExecutionContext; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.AbstractNativeApplication; +import org.openmetadata.service.apps.scheduler.AppScheduler; +import org.openmetadata.service.exception.AppException; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.search.SearchRepository; +import org.quartz.CronTrigger; +import org.quartz.SchedulerException; +import org.quartz.TriggerKey; + +/** + * Installing and removing an app changes the job store shared by every app, so this class runs + * alone, as {@link AppsResourceIT} does. + */ +@Execution(ExecutionMode.SAME_THREAD) +@Isolated +@ExtendWith(TestNamespaceExtension.class) +public class AppConfigurationSaveCheckIT { + @Test + void patchByIdWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + patch( + SdkClients.adminClient(), "/v1/apps/" + app.getId(), batchSizePatch("many"))); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void patchByNameWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + createCheckedApp(name, 100); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + patch(SdkClients.adminClient(), "/v1/apps/name/" + name, batchSizePatch("many"))); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void putWithARefusedConfigurationStoresNothingAndKeepsTheSchedule(TestNamespace ns) + throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + createCheckedApp(name, 100); + try { + CreateApp replacement = + checkedRequest(name, "many").withAppSchedule(schedule(ScheduleTimeline.MONTHLY)); + + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.PUT, "/v1/apps", replacement, App.class)); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void postWithARefusedConfigurationStoresNoApp(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute( + HttpMethod.POST, "/v1/apps", checkedRequest(name, "many"), App.class)); + + assertRefused(refused); + OpenMetadataException missing = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.GET, "/v1/apps/name/" + name, null, App.class)); + assertEquals(404, missing.getStatusCode(), missing.getMessage()); + assertNull(scheduledTrigger(name)); + } finally { + uninstallIfPresent(name); + } + } + + @Test + void anAcceptedConfigurationIsStoredAndTheAppIsRescheduled(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + try { + patch( + SdkClients.adminClient(), + "/v1/apps/" + app.getId(), + "[{\"op\":\"replace\",\"path\":\"/appConfiguration/batchSize\",\"value\":250}," + + "{\"op\":\"replace\",\"path\":\"/appSchedule/scheduleTimeline\"," + + "\"value\":\"Monthly\"}]"); + + App stored = getApp(name); + assertEquals(Map.of("batchSize", 250), stored.getAppConfiguration()); + assertEquals(ScheduleTimeline.MONTHLY, stored.getAppSchedule().getScheduleTimeline()); + assertEquals("0 0 0 1 * ?", scheduledTrigger(name).getCronExpression()); + } finally { + uninstall(name); + } + } + + private static void assumeEmbeddedServer() { + assumeFalse(OssTestServer.isExternalMode(), "Reads the scheduler inside the embedded server"); + } + + private static String createCheckedDefinition(TestNamespace ns) { + String name = ns.shortPrefix() + "Config" + UUID.randomUUID().toString().substring(0, 6); + AppMarketPlaceDefinition definition = + SdkClients.adminClient() + .getHttpClient() + .execute( + HttpMethod.POST, + "/v1/apps/marketplace", + new CreateAppMarketPlaceDefinitionReq() + .withName(name) + .withDisplayName("Configuration Test") + .withDescription("Configuration check before save") + .withFeatures("configuration") + .withDeveloper("Test Developer") + .withDeveloperUrl("https://www.example.com") + .withPrivacyPolicyUrl("https://www.example.com/privacy") + .withSupportEmail("support@example.com") + .withClassName(CheckedConfigurationApp.class.getName()) + .withAppType(AppType.Internal) + .withScheduleType(ScheduleType.Scheduled) + .withRuntime(new ScheduledExecutionContext().withEnabled(true)) + .withAppConfiguration(Map.of()) + .withPermission(NativeAppPermission.All), + AppMarketPlaceDefinition.class); + ns.trackRoot(Entity.APP_MARKET_PLACE_DEF, definition); + return name; + } + + private static CreateApp checkedRequest(String name, Object batchSize) { + return new CreateApp() + .withName(name) + .withAppConfiguration(Map.of("batchSize", batchSize)) + .withAppSchedule(schedule(ScheduleTimeline.HOURLY)); + } + + private static AppSchedule schedule(ScheduleTimeline timeline) { + return new AppSchedule().withScheduleTimeline(timeline); + } + + private static App createCheckedApp(String name, Object batchSize) { + return SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.POST, "/v1/apps", checkedRequest(name, batchSize), App.class); + } + + private static String batchSizePatch(String value) { + return "[{\"op\":\"replace\",\"path\":\"/appConfiguration/batchSize\",\"value\":\"" + + value + + "\"}]"; + } + + private static void patch(OpenMetadataClient client, String path, String body) { + client + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + path, + body, + RequestOptions.builder().header("Content-Type", "application/json-patch+json").build()); + } + + private static App getApp(String name) { + return SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.GET, "/v1/apps/name/" + name, null, App.class); + } + + private static void uninstall(String name) { + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.DELETE, "/v1/apps/name/" + name + "?hardDelete=true", null, Void.class); + } + + private static void uninstallIfPresent(String name) { + try { + uninstall(name); + } catch (OpenMetadataException absent) { + assertEquals(404, absent.getStatusCode(), absent.getMessage()); + } + } + + private static CronTrigger scheduledTrigger(String name) throws SchedulerException { + return (CronTrigger) + AppScheduler.getInstance() + .getScheduler() + .getTrigger(new TriggerKey(name, AppScheduler.APPS_TRIGGER_GROUP)); + } + + private static void assertRefused(OpenMetadataException refused) { + assertEquals(400, refused.getStatusCode(), refused.getMessage()); + assertTrue( + refused.getMessage().contains("Invalid checked configuration: batchSize must be a number"), + refused.getMessage()); + } + + private static void assertStoredUnchanged(String name) throws SchedulerException { + App stored = getApp(name); + assertEquals(Map.of("batchSize", 100), stored.getAppConfiguration()); + assertEquals(ScheduleTimeline.HOURLY, stored.getAppSchedule().getScheduleTimeline()); + assertEquals("0 0 * ? * *", scheduledTrigger(name).getCronExpression()); + } + + /** An app that reads {@code batchSize} as a number and refuses any other configuration. */ + public static final class CheckedConfigurationApp extends AbstractNativeApplication { + public CheckedConfigurationApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { + super(collectionDAO, searchRepository); + } + + @Override + public void validateConfigForSave(Map config) { + if (!(config.get("batchSize") instanceof Number)) { + throw AppException.byMessage( + Response.Status.BAD_REQUEST, + "Invalid checked configuration: batchSize must be a number"); + } + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java index efef4c47c27a..3242bce7caad 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java @@ -1,9 +1,6 @@ package org.openmetadata.it.util; public final class SharedResourceLocks { - /** Tests that schedule and unschedule apps in the Postgres-backed job store one at a time. */ - public static final String APP_SCHEDULES = "appSchedules"; - public static final String APP_RUN_RECORDS = "appRunRecords"; public static final String GLOSSARY_TERM_RELATION_SETTINGS = "glossaryTermRelationSettings"; public static final String OPEN_LINEAGE_SETTINGS = "openLineageSettings"; From 04677c78b427bd723cc1ad6746dd96e38b2cb6ce Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 17:44:04 -0800 Subject: [PATCH 150/203] apps: test a move out of the configuration and a caller without edit rights A move out of appConfiguration is refused and stores nothing. A caller without edit rights gets 403 before the configuration is checked. --- .../it/tests/AppConfigurationSaveCheckIT.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java index c7e40efa10f4..3c390517ff7e 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.factories.UserTestFactory; import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; @@ -101,6 +102,51 @@ void patchByNameWithARefusedConfigurationStoresNothing(TestNamespace ns) throws } } + @Test + void moveOutOfTheConfigurationIsChecked(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + try { + String move = + "[{\"op\":\"move\",\"from\":\"/appConfiguration/batchSize\",\"path\":\"/description\"}]"; + + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> patch(SdkClients.adminClient(), "/v1/apps/" + app.getId(), move)); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void aCallerWithoutEditRightsIsRefusedBeforeTheConfigurationIsChecked(TestNamespace ns) + throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + UserTestFactory.getDataConsumer(ns); + try { + OpenMetadataException forbidden = + assertThrows( + OpenMetadataException.class, + () -> + patch( + SdkClients.dataConsumerClient(), + "/v1/apps/" + app.getId(), + batchSizePatch("many"))); + + assertEquals(403, forbidden.getStatusCode(), forbidden.getMessage()); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + @Test void putWithARefusedConfigurationStoresNothingAndKeepsTheSchedule(TestNamespace ns) throws Exception { From 8baf95d2feec853a330421a2ba26935204a2953e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 17:46:19 -0800 Subject: [PATCH 151/203] apps: build an app for the save check only when it declares its own check An app that inherits the default check accepts every configuration, so building it only risked a failure in its constructor. The record now states this and corrects its account of the apps that parsed the configuration late. --- ...-is-checked-before-the-server-stores-it.md | 18 ++++--- .../service/apps/ApplicationHandler.java | 16 +++++- .../apps/AppConfigurationCheckTest.java | 52 +++++++++++++++++++ 3 files changed, 78 insertions(+), 8 deletions(-) diff --git a/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md b/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md index 593643dd242f..7d394f73d215 100644 --- a/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md +++ b/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-12-01 (initial) - **Deciders:** OpenMetadata maintainers -- **Guard:** `AppConfigurationCheckTest` (each shipped app refuses a configuration it cannot read, with its message, and accepts a good one; the default accepts every configuration), `AppConfigurationIT` (a refused configuration on POST, PUT, PATCH by id and PATCH by name answers 400 and leaves the stored app and its schedule as they were; an accepted one is stored and rescheduled) +- **Guard:** `AppConfigurationCheckTest` (each shipped app refuses a configuration it cannot read, with its message, and accepts a good one; the default accepts every configuration; an app that inherits the default is not built), `AppConfigurationSaveCheckIT` (a refused configuration on POST, PUT, PATCH by id and PATCH by name, or a `move` out of the configuration, answers 400 and leaves the stored app and its schedule as they were; a caller without edit rights gets 403 before the check; an accepted configuration is stored and rescheduled) - **Related:** none ## Context @@ -14,8 +14,9 @@ that refused the new configuration answered 400 after the refused configuration GET returned it, and every later reinstall (`/schedule`, `/restore`, `/deploy`) read it. The PUT path deleted the scheduled job before it installed, so a refused PUT stored nothing but left the app unscheduled. `SearchIndexApp`, `CacheWarmupApp`, `RdfIndexApp` and `DataInsightsReportApp` checked -their configuration only in `validateConfig`, which runs before a trigger, so a configuration they -could not read was stored and failed at the next run. +their configuration with a message only in `validateConfig`, before a trigger. Three of them also +parse it in `init` at install, which a PATCH reached only after the store. So a configuration they +could not read was stored, and failed at the reinstall or at the next run. ## Decision @@ -33,13 +34,18 @@ could not read was stored and failed at the next run. - `ApplicationHandler#validateConfigurationForSave` reaches the method on an instance built by the app's constructor alone. It does not call `init`, which registers the app in the application context and, for some apps, parses the configuration, and it does not install, schedule or store - anything, and it changes no bot or role. A class that is not a native application, or that cannot - be found, has nothing to check. + anything, and it changes no bot or role. The handler builds an instance only for an app whose + class declares its own check, meaning the `validateConfigForSave` the class resolves is not the one + `AbstractNativeApplication` declares. An app that inherits the default is not built, because the + default accepts every configuration. A class that is not a native application, or that cannot be + found, has nothing to check. ## Consequences - An app that shipped with a configuration its check now refuses is not changed by this record. The check applies to the next write. - A new app that validates its settings overrides `validateConfigForSave`, and its constructor must - stay free of side effects, because the server builds an instance for each write. + not write anything, because the server builds an instance for each write of its configuration. + `DataInsightsReportApp`'s constructor builds a repository that registers itself in `Entity`; the + save path already did that through `AppRepository.prepare`. - Revisit if an app needs the stored app, not only the configuration, to decide. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java index 0c67fc7e1d9a..026a8b8a55e4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java @@ -189,13 +189,16 @@ public AbstractNativeApplication initializeApplicationForTrigger( /** * Ask the application to check the configuration that is about to be stored. The instance comes * from its constructor alone: {@code init} registers the app in the application context and the - * install steps schedule it, and neither must happen for a configuration that may be refused. + * install steps schedule it, and neither must happen for a configuration that may be refused. An + * application that inherits the default check is not built, because that check accepts every + * configuration. */ public void validateConfigurationForSave( App app, CollectionDAO daoCollection, SearchRepository searchRepository) { try { Optional> nativeClass = - findNativeApplicationClass(app.getClassName()); + findNativeApplicationClass(app.getClassName()) + .filter(ApplicationHandler::declaresOwnSaveCheck); if (nativeClass.isPresent()) { nativeClass .get() @@ -225,6 +228,15 @@ private static Optional> findNativeAp } } + private static boolean declaresOwnSaveCheck(Class clz) { + try { + return clz.getMethod("validateConfigForSave", Map.class).getDeclaringClass() + != AbstractNativeApplication.class; + } catch (NoSuchMethodException e) { + throw new IllegalStateException(e); + } + } + private static Map configurationAsMap(App app) { Map configuration = JsonUtils.getMap(app.getAppConfiguration()); return configuration == null ? new HashMap<>() : configuration; diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java index e0acf097c8c0..b4ab557c760a 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java @@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; @@ -24,6 +25,7 @@ import org.junit.jupiter.api.Test; import org.mockito.Answers; import org.mockito.MockedStatic; +import org.openmetadata.schema.entity.app.App; import org.openmetadata.service.Entity; import org.openmetadata.service.apps.bundles.cache.CacheWarmupApp; import org.openmetadata.service.apps.bundles.insights.DataInsightsReportApp; @@ -31,6 +33,7 @@ import org.openmetadata.service.apps.bundles.searchIndex.SearchIndexApp; import org.openmetadata.service.exception.AppException; import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.search.SearchRepository; class AppConfigurationCheckTest { @@ -94,6 +97,55 @@ void dataInsightsReportAppRefusesAStringFlag() { } } + @Test + void anAppThatInheritsTheDefaultCheckIsNotBuilt() { + App app = + new App().withName("inheriting").withClassName(ThrowingConstructorApp.class.getName()); + + assertDoesNotThrow(() -> handler().validateConfigurationForSave(app, null, null)); + } + + @Test + void anAppWithItsOwnCheckIsBuiltAndChecked() { + App app = + new App() + .withName("declaring") + .withClassName(DeclaringApp.class.getName()) + .withAppConfiguration(Map.of("batchSize", "many")); + + AppException refused = + assertThrows( + AppException.class, () -> handler().validateConfigurationForSave(app, null, null)); + + assertRefusedWith("Invalid declared configuration", refused); + app.setAppConfiguration(Map.of("batchSize", 100)); + assertDoesNotThrow(() -> handler().validateConfigurationForSave(app, null, null)); + } + + private static ApplicationHandler handler() { + return mock(ApplicationHandler.class, CALLS_REAL_METHODS); + } + + public static class ThrowingConstructorApp extends AbstractNativeApplication { + public ThrowingConstructorApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { + super(collectionDAO, searchRepository); + throw new IllegalStateException("constructor must not run"); + } + } + + public static class DeclaringApp extends AbstractNativeApplication { + public DeclaringApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { + super(collectionDAO, searchRepository); + } + + @Override + public void validateConfigForSave(Map config) { + if (!(config.get("batchSize") instanceof Number)) { + throw AppException.byMessage(Response.Status.BAD_REQUEST, "Invalid declared configuration"); + } + } + } + private static void assertRefusedWith(String messagePrefix, AppException refused) { assertTrue(refused.getMessage().startsWith(messagePrefix), refused.getMessage()); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), refused.getResponse().getStatus()); From cf38c1a2f48040d606db83d1f6cb4e122b8ca06f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 20:23:13 -0800 Subject: [PATCH 152/203] A shape check reaches its table as a proposed test, kept in step with the release and the bindings --- ...ck-reaches-its-table-as-a-proposed-test.md | 127 ++++ .../service/jdbi3/DataContractRepository.java | 84 ++- .../openmetadata/service/jdbi3/FeedDAOs.java | 12 + .../service/jdbi3/GeneratedTestScope.java | 90 +++ .../jdbi3/TaskFormSchemaRepository.java | 1 + .../service/jdbi3/TaskRepository.java | 6 + .../service/jdbi3/TestCaseRepository.java | 34 + .../service/jdbi3/TimeSeriesDAOs.java | 9 + .../ontology/OntologyBindingAccess.java | 40 +- .../ontology/OntologyCheckReconcileQueue.java | 145 ++++ .../ontology/OntologyCheckReconciler.java | 642 ++++++++++++++++++ .../ontology/OntologyCheckReconciliation.java | 209 ++++++ .../OntologyConceptBindingService.java | 34 +- .../ontology/OntologyShapeCheckAnswer.java | 36 + .../resources/ontology/OntologyResource.java | 18 +- .../tasks/TableConstraintSuggestion.java | 36 +- .../service/tasks/TaskWorkflowHandler.java | 47 +- .../service/tasks/TestCaseSuggestion.java | 258 +++++++ .../taskFormSchemas/TestCaseSuggestion.json | 31 + .../service/jdbi3/GeneratedTestScopeTest.java | 131 ++++ .../OntologyCheckReconciliationTest.java | 267 ++++++++ .../service/tasks/TestCaseSuggestionTest.java | 403 +++++++++++ .../schema/api/data/ontologyShapeChecks.json | 36 + .../resources/json/schema/tests/testCase.json | 68 ++ .../json/schema/type/suggestionPayload.json | 6 +- .../json/schema/type/testCaseProposal.json | 24 + 26 files changed, 2737 insertions(+), 57 deletions(-) create mode 100644 docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java create mode 100644 openmetadata-service/src/main/resources/json/data/taskFormSchemas/TestCaseSuggestion.json create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java create mode 100644 openmetadata-spec/src/main/resources/json/schema/type/testCaseProposal.json diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md new file mode 100644 index 000000000000..366acc5b365b --- /dev/null +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -0,0 +1,127 @@ +# A shape check reaches its table as a proposed test, and the server keeps the proposals and the accepted tests in step + +- **Status:** Accepted +- **Revisions:** v1 2026-12-01 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, on MySQL and Postgres) +- **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) + +## Context + +The compile of a class's shapes (`GET /v1/ontologyConcepts/{id}/shapeChecks`) says which data quality +tests would count the records that break a part of a constraint, and creates nothing. A test on a +table runs on a schedule, reads every row, costs the owner of the warehouse money and can fail a +pipeline, so it must not appear on a table because a shape was released. The person who owns the +table decides. + +A test also goes stale. The statement of a check depends on the release (a bound of a constraint) and +on the table bindings (a row filter, a bound column). Someone who changes either would otherwise have +to find every test they made and change it by hand. + +## Decision + +**A check is proposed before it is a test.** The server files one suggestion task for each check +(`suggestionType` `TestCase`, `fieldPath` `testCases`), about the table the check belongs to. +Approving it creates the test case as the approver, so the approver needs `CreateTests` on the table, +as a request to create a test case does. Rejecting creates nothing. The task is assigned to the +owners of the table, else the owners of the ontology, else nobody, and a user who lacks the right on +the table is left out. Its source is `Ingestion`, because a deterministic compile of a shape wrote it, +and no agent or model did. + +**A test is not kept in a review state.** The runner reads every test case of a suite and no status of +it, so a test that waits for a decision would run. The proposal is the task and the test does not +exist until it is approved. + +**What a proposal holds.** The suggested value is a `testCaseProposal` written as JSON: the test case +to create in the shape of a request to create one (the test `tableCustomSQLQuery` on the table's +entity link with the four parameters `sqlExpression`, `strategy` `COUNT`, `operator` `<=` and +`threshold` `0`), the statement that lists the keys of the records in violation, and `generatedBy`. +The statement of the count is passed through as the compile wrote it, with each colon written as a +backslash and a colon. The statement that lists the keys is stored as the test case's +`inspectionQuery`, never passed through a parameter binder, and no runner executes it. A proposal sets +no partition expression and leaves the computation of passed and failed rows off. + +**Identity and content.** The identity of a check is the digest the compile gives it. It holds no +test definition and no value of the constraint, so a changed bound keeps it, and a check that once +was offered as another test keeps it too. The content digest is the lowercase hex SHA-256 of the +canonical JSON of the test definition, the entity link and the parameter values, with sorted keys and +the parameters in their order. It decides whether the content changed. `generatedBy` holds the +identity, the shape, the constraint id, the part, the class, the table bindings the check was built +from with their revisions, and the content digest. Only a suggestion that creates the test and the +reconcile set it. + +**The reconcile.** A background job compiles the checks of each class in scope, for no caller, so it +reads every shape, property and table and masks nothing (the answer a person gets is a masked view of +the same compile, and a step that creates tests must never read a hidden constraint as absent). For +each check it does the first of these: + +| A test case with the identity exists | The test is updated in place when its content digest or its bindings changed, else left alone | +|---|---| +| else an open task with the identity exists | Its suggested value is replaced when the content or the bindings changed, else left alone | +| else a rejected task, or a test a person deleted, has the identity and the same content digest | Nothing | +| else | A new task | + +A test whose identity no longer appears is deleted, as a soft delete a person can see. An open task +whose identity no longer appears is closed as `Cancelled` with the reason as its comment. A part that +is now held by the mapping, not mapped or not enforceable counts as not appearing. A second open task +of one identity, or an open task of a check that has a test, is closed too. A rejected task of other +content, or a deleted test of other content, is proposed again. + +**A refused compile changes nothing.** The compile of a class can refuse, for example when the walk +up its ancestors passes the bound, or when the bindings change while it reads. The reconcile then +writes nothing for that class, deletes no test and cancels no task, logs the refusal with the class id, +and the next trigger tries again. A refusal is never read as "no checks". + +**When it runs.** After the commit of an activation, an older release included, for every class of the +ontology that a shape of the active release targets and every class that has a generated test or an +open proposal. After a write that moves the binding revision of a class, for that class and for every +class whose tests or proposals list a binding of it. A job runs one at a time for each ontology. A +request that arrives while one runs is merged with the others that wait and runs after it. + +**Running it twice writes nothing.** Every write follows from a difference between the compile and +what exists, so the state a run leaves has no difference. The reconcile counts its writes and a test +asserts that the second count is zero. + +**Read-only.** A test case with `generatedBy` refuses a change to its test definition, entity link, +parameter values or `generatedBy` by anyone but the reconcile, with a 400 that says the test comes +from a shape. A create or a patch that sends `generatedBy` is a 400. Its description, owners and tags +stay editable and a person may delete it. A deleted test is not brought back unless the content +changes. + +**What a test costs and reads.** The test is added to the basic test suite of its table, created if +the table has none. A suite with no pipeline gets one that runs daily at midnight, and the deployment +is best-effort, as for a data contract. Creating the test and the pipeline happens in the repositories, +so the limits that a resource enforces on a request, which a deployment can set per feature, do not +apply to them. OpenMetadata has no way to read the most frequent schedule a deployment allows, so the +schedule stays daily at midnight. A check reads every row of its tables: the runner executes the +statement of a `tableCustomSQLQuery` test with `COUNT` as written, on its own session, and never +through the sampled data set that built-in tests read, whatever sample the table, its schema, its +database or the pipeline sets. + +**What a caller reads.** Each check of `GET /v1/ontologyConcepts/{id}/shapeChecks` has a `proposal`: +`none`, `proposed` with the task, `rejected` with the task, or `accepted` with the test case and the +status and time of its latest result. A caller who may not view the task or the test case gets the +state without the reference. The proposals do not show in the lists of suggestions that a page of +descriptions and tags reads, because those lists leave out a suggestion type they cannot show. + +## Consequences + +- A table owner sees a check as a task and accepts or rejects it with the rights they have on the + table. Nobody has to pass a test to a person who may not create one. +- A bound that changes keeps the test, its id and its results. A check whose statement changes, such + as one whose row filter changed, is updated without an activation. +- The queue is in memory. A trigger lost with the server is made good by the next one for the + ontology, because each run derives its writes from the state it reads. A crash in the middle of a + run leaves some writes made, each complete, and the next run finishes the rest. Two servers can run + two jobs of one ontology, which can file two open tasks of one check, and the next run closes one. +- The compile reads three things after its check of the binding revisions: the holders of the inverse + of a relation, the classes that share a filtered table, and the tables themselves. A change to + them that moves no revision listed by a check is not triggered by itself. The holders of an inverse + only choose between two reasons that are both "no check", so they change no check. A new subclass + that binds the table of a class a `class` part names, or a change to a table's declared keys or + columns, is seen by the next activation, the next write to a class of the check, or the next write + to a class whose checks list the class. +- A check still can abort at run time. A pattern check, on the `Postgres` service type only, can stop + with `regular expression is too complex`, which the runner reports as a failed run of the test. +- Revisit the queue if more than one server runs the reconcile at once, or if a deployment needs a + proposal to survive a restart that lost it before it ran. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java index cf66301eb361..d712710eb74c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java @@ -366,32 +366,48 @@ private void postCreateOrUpdate(DataContract dataContract) { } // Create the ingestion pipeline only if needed if (testSuite != null && nullOrEmpty(testSuite.getPipelines())) { - IngestionPipeline pipeline = createIngestionPipeline(testSuite); - EntityReference pipelineRef = - Entity.getEntityReference( - new EntityReference().withId(pipeline.getId()).withType(Entity.INGESTION_PIPELINE), - Include.NON_DELETED); - testSuite.setPipelines(List.of(pipelineRef)); - TestSuiteRepository testSuiteRepository = - (TestSuiteRepository) Entity.getEntityRepository(Entity.TEST_SUITE); - testSuiteRepository.createOrUpdate(null, testSuite, ADMIN_USER_NAME); - if (!pipeline.getDeployed()) { - // Deploy is best-effort at creation time: a pipeline-service outage or misconfiguration - // must not block contract creation nor lose the reverse relationship written above. - // The user can re-deploy via /validate later. - try { - prepareAndDeployIngestionPipeline(pipeline, testSuite); - } catch (RuntimeException e) { - // Narrow to RuntimeException: deployPipeline throws - // IngestionPipelineDeploymentException (WebServiceException) on transport failures - // and NPE when the pipeline client is not wired (test harness). Both are recoverable - // at /validate time. Checked exceptions still propagate. - LOG.warn( - "Failed to deploy DQ pipeline for data contract {}: {}", - dataContract.getFullyQualifiedName(), - e.getMessage()); - } - } + attachPipeline(testSuite, new AirflowConfig(), dataContract.getFullyQualifiedName()); + } + } + } + + /** + * Gives a test suite that has no pipeline one that runs on {@code scheduleInterval}, a cron + * expression, and deploys it. Deploying is best-effort, as for a data contract, and this path + * runs in the repository, so the limits that a resource enforces on a request to create a + * pipeline do not apply to it. A suite that has a pipeline is left as it is. + */ + public void ensureScheduledPipeline(TestSuite testSuite, String scheduleInterval) { + if (nullOrEmpty(testSuite.getPipelines())) { + attachPipeline( + testSuite, + new AirflowConfig().withScheduleInterval(scheduleInterval), + testSuite.getFullyQualifiedName()); + } + } + + private void attachPipeline(TestSuite testSuite, AirflowConfig schedule, String owner) { + IngestionPipeline pipeline = createIngestionPipeline(testSuite, schedule); + EntityReference pipelineRef = + Entity.getEntityReference( + new EntityReference().withId(pipeline.getId()).withType(Entity.INGESTION_PIPELINE), + Include.NON_DELETED); + testSuite.setPipelines(List.of(pipelineRef)); + TestSuiteRepository testSuiteRepository = + (TestSuiteRepository) Entity.getEntityRepository(Entity.TEST_SUITE); + testSuiteRepository.createOrUpdate(null, testSuite, ADMIN_USER_NAME); + if (!pipeline.getDeployed()) { + // Deploy is best-effort at creation time: a pipeline-service outage or misconfiguration + // must not block the write that asked for the pipeline, nor lose the reverse relationship + // a data contract wrote before it. A data contract can re-deploy via /validate later. + try { + prepareAndDeployIngestionPipeline(pipeline, testSuite); + } catch (RuntimeException e) { + // Narrow to RuntimeException: deployPipeline throws + // IngestionPipelineDeploymentException (WebServiceException) on transport failures + // and NPE when the pipeline client is not wired (test harness). Both are recoverable + // at /validate time. Checked exceptions still propagate. + LOG.warn("Failed to deploy DQ pipeline for {}: {}", owner, e.getMessage()); } } } @@ -1003,8 +1019,18 @@ private Boolean contractHasTestSuite(DataContract dataContract) { return dataContract.getTestSuite() != null; } + /** A basic suite tests one entity, which its pipeline names. */ + private static TestSuitePipeline testSuitePipeline(TestSuite testSuite) { + TestSuitePipeline config = new TestSuitePipeline(); + if (Boolean.TRUE.equals(testSuite.getBasic()) && testSuite.getBasicEntityReference() != null) { + config.setEntityFullyQualifiedName( + testSuite.getBasicEntityReference().getFullyQualifiedName()); + } + return config; + } + // Prepare the Ingestion Pipeline from the test suite that will handle the execution - private IngestionPipeline createIngestionPipeline(TestSuite testSuite) { + private IngestionPipeline createIngestionPipeline(TestSuite testSuite, AirflowConfig schedule) { IngestionPipelineRepository pipelineRepository = (IngestionPipelineRepository) Entity.getEntityRepository(Entity.INGESTION_PIPELINE); @@ -1015,9 +1041,9 @@ private IngestionPipeline createIngestionPipeline(TestSuite testSuite) { .withPipelineType(PipelineType.TEST_SUITE) .withService( new EntityReference().withId(testSuite.getId()).withType(Entity.TEST_SUITE)) - .withSourceConfig(new SourceConfig().withConfig(new TestSuitePipeline())) + .withSourceConfig(new SourceConfig().withConfig(testSuitePipeline(testSuite))) .withLoggerLevel(LogLevels.INFO) - .withAirflowConfig(new AirflowConfig()); + .withAirflowConfig(schedule); IngestionPipeline pipeline = ingestionPipelineMapper.createToEntity(createPipeline, ADMIN_USER_NAME); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java index c08984f794f7..71ef36c5c13f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java @@ -144,6 +144,18 @@ default void insert(org.openmetadata.schema.EntityInterface entity, String fq insertTask(task.getId().toString(), JsonUtils.pojoToJson(task), task.getFullyQualifiedName()); } + /** The ids of the suggestion tasks that propose a test case, closed ones included. */ + @ConnectionAwareSqlQuery( + value = + "SELECT id FROM task_entity WHERE " + + "JSON_UNQUOTE(JSON_EXTRACT(json, '$.payload.suggestionType')) = 'TestCase'", + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = + "SELECT id FROM task_entity WHERE json -> 'payload' ->> 'suggestionType' = 'TestCase'", + connectionType = POSTGRES) + List findTestCaseSuggestionIds(); + @ConnectionAwareSqlUpdate( value = "UPDATE task_entity SET json = :json WHERE id = :id", connectionType = MYSQL) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java new file mode 100644 index 000000000000..9c54c21f7bae --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java @@ -0,0 +1,90 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.jdbi3; + +import java.util.Objects; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.service.exception.BadRequestException; + +/** + * Marks the code that may write the {@code generatedBy} of a test case and the fields that + * {@code generatedBy} freezes: a suggestion that creates such a test and the reconcile that keeps + * it in step with its shape (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + * Any other write that sets {@code generatedBy}, or changes the test definition, the entity link or + * the parameter values of a test that has it, is a 400. + */ +public final class GeneratedTestScope { + static final String SET_BY_SERVER = + "generatedBy is set by the server when a suggestion creates a test from a shape, and cannot be sent or changed"; + static final String FROM_A_SHAPE = + "This test comes from a shape: its test definition, entity link and parameter values change" + + " only when the shape or the table bindings change. Its description, owners and tags" + + " can be edited, and it can be deleted"; + + private static final ThreadLocal ACTIVE = ThreadLocal.withInitial(() -> Boolean.FALSE); + + private GeneratedTestScope() {} + + /** True when the calling thread is inside the scope of a write that may set the fields. */ + public static boolean isActive() { + return Boolean.TRUE.equals(ACTIVE.get()); + } + + /** Enters the scope. Close the returned handle to restore the previous state. */ + public static Handle enter() { + final boolean previous = ACTIVE.get(); + ACTIVE.set(Boolean.TRUE); + return () -> ACTIVE.set(previous); + } + + @FunctionalInterface + public interface Handle extends AutoCloseable { + @Override + void close(); + } + + /** Refuses a create that carries {@code generatedBy} outside the scope. */ + static void requireUnsetOnCreate(final TestCase test) { + if (test.getGeneratedBy() != null && !isActive()) { + throw BadRequestException.of(SET_BY_SERVER); + } + } + + /** Refuses a change to {@code generatedBy} or to what it freezes outside the scope. */ + static void requireUnchanged(final TestCase original, final TestCase updated) { + if (isActive()) { + return; + } + if (!Objects.equals(original.getGeneratedBy(), updated.getGeneratedBy())) { + throw BadRequestException.of(SET_BY_SERVER); + } + if (original.getGeneratedBy() != null && frozenFieldsChanged(original, updated)) { + throw BadRequestException.of(FROM_A_SHAPE); + } + } + + private static boolean frozenFieldsChanged(final TestCase original, final TestCase updated) { + return !Objects.equals(original.getEntityLink(), updated.getEntityLink()) + || !Objects.equals(original.getParameterValues(), updated.getParameterValues()) + || !sameDefinition(original, updated); + } + + private static boolean sameDefinition(final TestCase original, final TestCase updated) { + return original.getTestDefinition() == null + ? updated.getTestDefinition() == null + : updated.getTestDefinition() != null + && Objects.equals( + original.getTestDefinition().getId(), updated.getTestDefinition().getId()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java index 303d9abb4907..d687089a3d2b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java @@ -395,6 +395,7 @@ private Optional mapSuggestionTypeToSchema(String suggestionType) { case "description" -> Optional.of("DescriptionSuggestion"); case "tag" -> Optional.of("TagSuggestion"); case "tableconstraint" -> Optional.of("TableConstraintSuggestion"); + case "testcase" -> Optional.of("TestCaseSuggestion"); default -> Optional.empty(); }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index 6c5bfff6a7bd..34553342dd96 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -100,6 +100,7 @@ import org.openmetadata.service.tasks.TaskWorkflowHandler; import org.openmetadata.service.tasks.TaskWorkflowLifecycleResolver; import org.openmetadata.service.tasks.TaskWorkflowLifecycleResolver.WorkflowStartVariables; +import org.openmetadata.service.tasks.TestCaseSuggestion; import org.openmetadata.service.util.EntityUtil; import org.openmetadata.service.util.EntityUtil.Fields; import org.openmetadata.service.util.EntityUtil.RelationIncludes; @@ -419,6 +420,7 @@ public void prepare(Task task, boolean update) { TaskFieldTarget.fillDefault(task); TaskFieldTarget.require(task); TableConstraintSuggestion.require(task); + TestCaseSuggestion.require(task); } validateNoDuplicateActiveDataAccessRequest(task); @@ -1463,6 +1465,9 @@ private MetadataOperation getOperationForTask(Task task) { if (TableConstraintSuggestion.isTableConstraint(task)) { return MetadataOperation.EDIT_ALL; } + if (TestCaseSuggestion.isTestCase(task)) { + return MetadataOperation.CREATE_TESTS; + } MetadataOperation schemaBoundOperation = TaskFormExecutionResolver.resolve(task).permissionOperation(); @@ -1516,6 +1521,7 @@ private MetadataOperation getOperationForSuggestion(Task task) { case CUSTOM_PROPERTY -> MetadataOperation.EDIT_CUSTOM_FIELDS; // No narrower operation covers tableConstraints: a PATCH of that field needs EditAll. case TABLE_CONSTRAINT -> MetadataOperation.EDIT_ALL; + case TEST_CASE -> MetadataOperation.CREATE_TESTS; }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index f8d40158b30d..171f0a8128aa 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -65,6 +65,7 @@ import org.openmetadata.schema.api.tests.CreateTestSuite; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; import org.openmetadata.schema.tests.TestCaseParameter; import org.openmetadata.schema.tests.TestCaseParameterValidationRule; import org.openmetadata.schema.tests.TestCaseParameterValue; @@ -874,6 +875,9 @@ public void setFullyQualifiedName(TestCase test) { @Override public void prepare(TestCase test, boolean update) { + if (!update) { + GeneratedTestScope.requireUnsetOnCreate(test); + } Table table = validateForWrite(test, update); // Create/resolve the basic test suite only after all validations pass. // This avoids creating side entities when request validation fails early. @@ -1990,6 +1994,32 @@ public TestCase addInspectionQuery(UriInfo uri, UUID testCaseId, String sql) { return updated; } + /** + * Rewrites what a test generated from a shape check holds, in place, so the test keeps its id and + * its results. Only the reconcile that keeps such tests in step with their shapes calls it. + */ + public TestCase updateGenerated( + UUID testCaseId, + String entityLink, + List parameterValues, + String inspectionQuery, + TestCaseGeneratedBy generatedBy, + String user) { + TestCase original = get(null, testCaseId, getFields("*")); + TestCase updated = + JsonUtils.readValue(JsonUtils.pojoToJson(original), TestCase.class) + .withEntityLink(entityLink) + .withParameterValues(parameterValues) + .withInspectionQuery(inspectionQuery) + .withGeneratedBy(generatedBy) + .withUpdatedBy(user) + .withUpdatedAt(System.currentTimeMillis()); + try (GeneratedTestScope.Handle ignored = GeneratedTestScope.enter()) { + getUpdater(original, updated, Operation.PATCH, null).update(); + } + return updated; + } + @Transaction public RestUtil.DeleteResponse deleteTestCaseFailedRowsSample(UUID id) { daoCollection.entityExtensionDAO().delete(id, FAILED_ROWS_SAMPLE_EXTENSION); @@ -2074,6 +2104,7 @@ protected boolean shouldCompare(String fieldName) { @Transaction @Override public void entitySpecificUpdate(boolean consolidatingChanges) { + GeneratedTestScope.requireUnchanged(original, updated); validateChangedConformance(); compareAndUpdate( "entity", @@ -2115,6 +2146,9 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { () -> recordChange( "inspectionQuery", original.getInspectionQuery(), updated.getInspectionQuery())); + compareAndUpdate( + "generatedBy", + () -> recordChange("generatedBy", original.getGeneratedBy(), updated.getGeneratedBy())); compareAndUpdate( "computePassedFailedRowCount", () -> diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java index 1eb8cee466de..2a6bdfedbee8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java @@ -840,6 +840,15 @@ int countOfTestCases( List findIdsByEntityFQN( @Bind("entityFQN") String entityFQN, @Bind("entityFQNPrefix") String entityFQNPrefix); + /** The ids of the test cases that a shape generated, deleted ones included. */ + @ConnectionAwareSqlQuery( + value = "SELECT id FROM test_case WHERE JSON_EXTRACT(json, '$.generatedBy') IS NOT NULL", + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = "SELECT id FROM test_case WHERE json -> 'generatedBy' IS NOT NULL", + connectionType = POSTGRES) + List findGeneratedIds(); + class TestCaseRecord { @Getter String json; @Getter Integer rank; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java index 8bf5d0cb0104..dbbb4b8f071e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java @@ -1,5 +1,6 @@ package org.openmetadata.service.ontology; +import jakarta.ws.rs.core.SecurityContext; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -25,6 +26,7 @@ import org.openmetadata.service.security.policyevaluator.BulkFieldHydrator; import org.openmetadata.service.security.policyevaluator.OperationContext; import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; import org.openmetadata.service.util.EntityUtil.Fields; /** @@ -37,11 +39,39 @@ final class OntologyBindingAccess { Set.of("tableConstraints", "tablePartition", "tableProfilerConfig"); private final Authorizer authorizer; private final Function> repositories; + private final boolean unrestricted; OntologyBindingAccess( final Authorizer authorizer, final Function> repositories) { + this(authorizer, repositories, false); + } + + private OntologyBindingAccess( + final Authorizer authorizer, + final Function> repositories, + final boolean unrestricted) { this.authorizer = authorizer; this.repositories = repositories; + this.unrestricted = unrestricted; + } + + /** + * An access that sees every definition and table, for work the server does for no caller. What + * it reads is the same for everyone, and each person's rights apply where a result is shown or + * acted on. + */ + static OntologyBindingAccess unrestricted( + final Function> repositories) { + return new OntologyBindingAccess(null, repositories, true); + } + + private void permit( + final SecurityContext securityContext, + final OperationContext operation, + final ResourceContextInterface resource) { + if (!unrestricted) { + authorizer.authorize(securityContext, operation, resource); + } } /** The live entity, or an authorization or not-found failure for the caller. */ @@ -167,7 +197,7 @@ private > T hydratedAndAuthorized( final MetadataOperation operation) { final T entity = repository.getEntityClass().cast(released); repository.setFieldsInBulk(ResourceContext.authorizationFields(repository), List.of(entity)); - authorizer.authorize( + permit( access.securityContext(), new OperationContext(repository.getEntityType(), operation), new ResourceContext<>(repository.getEntityType(), entity, repository)); @@ -184,7 +214,7 @@ private > Map> authorizedB final Map> viewable = new HashMap<>(); for (final T entity : batch) { try { - authorizer.authorize( + permit( access.securityContext(), new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), new ResourceContext<>(repository.getEntityType(), entity, repository)); @@ -218,7 +248,7 @@ private > List viewableAmong( final List viewable = new ArrayList<>(); for (final T entity : entities) { try { - authorizer.authorize( + permit( access.securityContext(), new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), new ResourceContext<>(repository.getEntityType(), entity, repository, tags)); @@ -240,7 +270,7 @@ private > T authorized( final MetadataOperation operation, final Include include) { final T entity = repository.get(access.uriInfo(), id, fields(repository), include, false); - authorizer.authorize( + permit( access.securityContext(), new OperationContext(repository.getEntityType(), operation), new ResourceContext<>(repository.getEntityType(), entity, repository)); @@ -252,7 +282,7 @@ private > void require( final EntityRepository repository, final EntityInterface entity, final MetadataOperation operation) { - authorizer.authorize( + permit( access.securityContext(), new OperationContext(repository.getEntityType(), operation), new ResourceContext<>( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java new file mode 100644 index 000000000000..bd8736bfc860 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java @@ -0,0 +1,145 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Outcome; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Scope; + +/** + * Runs the reconcile of shape checks after the commit that asked for it, one job at a time for each + * ontology (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). A request that + * arrives while a job of its ontology runs is merged with the others that wait and runs after that + * job, so a write that lands during a run is always read by a later one. The queue is in memory: + * a request lost with the server is made good by the next one for the ontology, because every run + * derives its writes from the state it reads. + */ +@Slf4j +public final class OntologyCheckReconcileQueue { + private static final int THREADS = 2; + private static volatile OntologyCheckReconcileQueue instance; + + private final OntologyCheckReconciler reconciler; + private final ExecutorService executor; + private final Map pending = new HashMap<>(); + private final Set running = new HashSet<>(); + private final Map writes = new HashMap<>(); + + private record Pending(Scope scope, String user) { + Pending merge(final Pending later) { + return new Pending(scope.merge(later.scope), later.user); + } + } + + OntologyCheckReconcileQueue(final OntologyCheckReconciler reconciler) { + this.reconciler = reconciler; + this.executor = + Executors.newFixedThreadPool( + THREADS, + task -> { + final Thread thread = new Thread(task, "ontology-check-reconcile"); + thread.setDaemon(true); + return thread; + }); + } + + /** The queue of this server. */ + public static OntologyCheckReconcileQueue instance() { + OntologyCheckReconcileQueue current = instance; + if (current == null) { + synchronized (OntologyCheckReconcileQueue.class) { + if (instance == null) { + instance = + new OntologyCheckReconcileQueue( + new OntologyCheckReconciler(Entity.getCollectionDAO(), Entity.getAuthorizer())); + } + current = instance; + } + } + return current; + } + + /** A release was activated, an older one included: every class of the ontology is looked at. */ + public void afterActivation(final UUID ontologyId, final String user) { + submit(ontologyId, new Pending(Scope.everything(), user)); + } + + /** A write moved the binding revision of a class. */ + public void afterBindingWrite(final UUID ontologyId, final UUID conceptId, final String user) { + submit(ontologyId, new Pending(Scope.of(Set.of(conceptId)), user)); + } + + private synchronized void submit(final UUID ontologyId, final Pending request) { + pending.merge(ontologyId, request, Pending::merge); + if (running.add(ontologyId)) { + executor.execute(() -> drain(ontologyId)); + } + } + + private void drain(final UUID ontologyId) { + while (true) { + final Pending next; + synchronized (this) { + next = pending.remove(ontologyId); + if (next == null) { + running.remove(ontologyId); + notifyAll(); + return; + } + } + run(ontologyId, next); + } + } + + private void run(final UUID ontologyId, final Pending request) { + try { + final Outcome outcome = reconciler.run(ontologyId, request.scope(), request.user()); + synchronized (this) { + writes.merge(ontologyId, outcome.writes(), Integer::sum); + } + LOG.info("[OntologyChecks] Reconciled ontology {}: {}", ontologyId, outcome); + } catch (final RuntimeException failed) { + LOG.warn("[OntologyChecks] The reconcile of ontology {} failed", ontologyId, failed); + } + } + + /** The writes that the jobs of an ontology have made on this server so far. */ + public synchronized int writesMade(final UUID ontologyId) { + return writes.getOrDefault(ontologyId, 0); + } + + /** Waits until no job runs or waits, and says whether that happened within the time. */ + public boolean awaitIdle(final long timeout, final TimeUnit unit) throws InterruptedException { + final long deadline = System.nanoTime() + unit.toNanos(timeout); + synchronized (this) { + while (!running.isEmpty()) { + final long left = deadline - System.nanoTime(); + if (left <= 0) { + return false; + } + TimeUnit.NANOSECONDS.timedWait(this, left); + } + return true; + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java new file mode 100644 index 000000000000..bb45c57df4a5 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java @@ -0,0 +1,642 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import jakarta.ws.rs.WebApplicationException; +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.tests.CreateTestCase; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.entity.teams.Team; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.TestCaseGeneratedByBinding; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.type.SuggestionPayload; +import org.openmetadata.schema.type.TaskCategory; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TestCaseProposal; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.jdbi3.TaskRepository; +import org.openmetadata.service.jdbi3.TestCaseRepository; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Binding; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.CancelTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Checks; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Compiled; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.CreateTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.DeleteTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Held; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Proposed; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Refused; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.ReplaceTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TaskState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.UpdateTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Wanted; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Write; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Generated; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Asked; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Read; +import org.openmetadata.service.ontology.OntologyVersion.Release; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.ChangeActor; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.tasks.TestCaseSuggestion; +import org.openmetadata.service.util.EntityUtil.Fields; +import org.openmetadata.service.util.FreshReadScope; + +/** + * Brings the tests of shape checks, and the suggestions that propose them, in line with the active + * release and the table bindings (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + * + *

    It compiles the checks of each class in scope once, for no caller: the compile is the same for + * everyone, so it reads every shape, property and table and masks nothing. {@link + * OntologyCheckReconciliation} turns what it found, the test cases that carry {@code generatedBy} + * and the suggestion tasks of type {@code TestCase} into the writes, and this class makes them. A + * class whose compile refuses is left as it is. + */ +@Slf4j +public final class OntologyCheckReconciler { + private static final String REASONING = + "The records of the class break a constraint of a shape that targets it"; + private static final int ID_CHUNK = 500; + private static final Access NO_CALLER = new Access(null, null); + private static final String NAME_PREFIX = "shapeCheck_"; + private static final int NAME_IDENTITY_LENGTH = 16; + private static final int NAME_SUFFIX_LENGTH = 8; + + private final CollectionDAO dao; + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess catalog; + private final OntologyShapeCheckReader reader; + private final Authorizer authorizer; + + public OntologyCheckReconciler(final CollectionDAO dao, final Authorizer authorizer) { + this.dao = dao; + this.store = + new OntologyConceptBindingStore(dao, OntologyConceptBindingStore.registeredAssetTables()); + this.catalog = OntologyBindingAccess.unrestricted(Entity::getEntityRepository); + this.reader = new OntologyShapeCheckReader(store, catalog); + this.authorizer = authorizer; + } + + /** + * What a run covers: every class of the ontology that a shape targets or that has a generated + * test or an open proposal, or the named classes with every class whose checks list a binding of + * one of them. + */ + record Scope(boolean all, Set classes) { + static Scope everything() { + return new Scope(true, Set.of()); + } + + static Scope of(final Set classes) { + return new Scope(false, Set.copyOf(classes)); + } + + Scope merge(final Scope other) { + if (all || other.all) { + return everything(); + } + final Set merged = new LinkedHashSet<>(classes); + merged.addAll(other.classes); + return of(merged); + } + } + + /** The writes a run made, by kind. */ + public record Outcome( + int created, int replaced, int cancelled, int updated, int deleted, int refused) { + public int writes() { + return created + replaced + cancelled + updated + deleted; + } + } + + /** What one class compiled to, with what a task or a test needs to be written from it. */ + private record Planned( + Wanted wanted, + Generated generated, + EntityReference classReference, + EntityReference shapeReference, + URI classIri) {} + + private record Found(Compiled decision, Map byIdentity) {} + + Outcome run(final UUID ontologyId, final Scope scope, final String user) { + try (FreshReadScope.Handle ignored = FreshReadScope.enter()) { + final Optional active = activeRelease(ontologyId); + if (active.isEmpty()) { + return new Outcome(0, 0, 0, 0, 0, 0); + } + final Map tests = generatedTests(); + final Map tasks = suggestions(); + final Set classes = classesOf(ontologyId, active.get(), scope, tests, tasks); + final Map found = new LinkedHashMap<>(); + classes.forEach(id -> found.put(id, compile(ontologyId, active.get(), id))); + final Map decisions = new LinkedHashMap<>(); + found.forEach((id, one) -> decisions.put(id, one.decision())); + final List writes = + OntologyCheckReconciliation.decide( + decisions, List.copyOf(tests.values()), List.copyOf(tasks.values())); + return execute(ontologyId, user, writes, found, tests, tasks); + } + } + + private Optional activeRelease(final UUID ontologyId) { + final var state = dao.ontologyStateDAO().get(ontologyId); + if (state == null || state.getActiveReleaseId() == null) { + return Optional.empty(); + } + final var ontology = dao.ontologyEntityDAO().findEntityById(ontologyId); + if (Boolean.TRUE.equals(ontology.getDeleted())) { + return Optional.empty(); + } + return Optional.of((Release) OntologyVersion.release(dao, ontology.getEntityReference())); + } + + // ---- what exists ------------------------------------------------------------------------- + + private Map generatedTests() { + final TestCaseRepository repository = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + final List ids = + dao.testCaseDAO().findGeneratedIds().stream().map(UUID::fromString).toList(); + final Map held = new LinkedHashMap<>(); + for (final List chunk : chunks(ids)) { + for (final TestCase test : repository.get(null, chunk, Fields.EMPTY_FIELDS, Include.ALL)) { + final TestCaseGeneratedBy by = test.getGeneratedBy(); + held.put( + test.getId(), + new Held( + test.getId(), + by.getClass_().getId(), + by.getIdentity(), + by.getContentDigest(), + bindings(by.getReadBindings()), + Boolean.TRUE.equals(test.getDeleted()))); + } + } + return held; + } + + private Map suggestions() { + final TaskRepository repository = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final List ids = + dao.taskDAO().findTestCaseSuggestionIds().stream().map(UUID::fromString).toList(); + final Map proposed = new LinkedHashMap<>(); + for (final List chunk : chunks(ids)) { + for (final Task task : repository.get(null, chunk, Fields.EMPTY_FIELDS, Include.ALL)) { + proposalOf(task) + .ifPresent( + proposal -> { + final TestCaseGeneratedBy by = proposal.getGeneratedBy(); + proposed.put( + task.getId(), + new Proposed( + task.getId(), + by.getClass_().getId(), + by.getIdentity(), + by.getContentDigest(), + bindings(by.getReadBindings()), + stateOf(task))); + }); + } + } + return proposed; + } + + private static Optional proposalOf(final Task task) { + try { + return Optional.of(TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload()))); + } catch (RuntimeException unreadable) { + LOG.warn("[OntologyChecks] Task {} holds no readable test case proposal", task.getId()); + return Optional.empty(); + } + } + + private static TaskState stateOf(final Task task) { + return switch (task.getStatus()) { + case Open, InProgress, Pending -> TaskState.OPEN; + case Rejected -> TaskState.REJECTED; + default -> TaskState.OTHER; + }; + } + + private static List bindings(final List read) { + return listOrEmpty(read).stream() + .map(b -> new Binding(b.getConceptId(), b.getAssetId(), b.getRevision())) + .toList(); + } + + private static List> chunks(final List all) { + final List> chunks = new ArrayList<>(); + for (int from = 0; from < all.size(); from += ID_CHUNK) { + chunks.add(all.subList(from, Math.min(all.size(), from + ID_CHUNK))); + } + return chunks; + } + + // ---- which classes ----------------------------------------------------------------------- + + private Set classesOf( + final UUID ontologyId, + final Release active, + final Scope scope, + final Map tests, + final Map tasks) { + final Set classes = new LinkedHashSet<>(); + if (scope.all()) { + classes.addAll(shapeTargets(ontologyId, active)); + tests.values().forEach(test -> classes.add(test.classId())); + tasks.values().forEach(task -> classes.add(task.classId())); + return inOntology(ontologyId, classes); + } + classes.addAll(scope.classes()); + tests.values().stream() + .filter(test -> mentions(test.readBindings(), scope.classes())) + .forEach(test -> classes.add(test.classId())); + tasks.values().stream() + .filter(task -> mentions(task.readBindings(), scope.classes())) + .forEach(task -> classes.add(task.classId())); + return inOntology(ontologyId, classes); + } + + private static boolean mentions(final List bindings, final Set classes) { + return bindings.stream().anyMatch(binding -> classes.contains(binding.conceptId())); + } + + /** The classes of the ontology that a shape of the active release targets. */ + private Set shapeTargets(final UUID ontologyId, final Release active) { + final Set targets = new LinkedHashSet<>(); + String after = ""; + List page; + do { + page = + dao.ontologyReleaseDAO() + .listMembers( + active.release().getId(), + MemberKind.SHAPE.value(), + after, + OntologyVersion.SHAPE_MEMBERS_READ); + for (final var member : page) { + final OntologyShape shape = + (OntologyShape) OntologyReleaseReader.definition(active.release(), member); + if (shape.getTargetConcept() != null) { + targets.add(shape.getTargetConcept()); + } + after = member.getMemberId().toString(); + } + } while (page.size() == OntologyVersion.SHAPE_MEMBERS_READ); + return targets.isEmpty() + ? Set.of() + : active.classesNamed(store, ontologyId, targets).stream() + .map(OntologyConcept::getId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** A class of another ontology is not this run's to reconcile. A class that is gone stays in. */ + private Set inOntology(final UUID ontologyId, final Set classes) { + final Set kept = new LinkedHashSet<>(classes); + final List ids = List.copyOf(classes); + for (final List chunk : chunks(ids)) { + for (final OntologyConcept row : + dao.ontologyConceptDAO().findEntitiesByIds(chunk, Include.ALL)) { + if (!ontologyId.equals(row.getOntology().getId())) { + kept.remove(row.getId()); + } + } + } + return kept; + } + + // ---- the compile ------------------------------------------------------------------------- + + private Found compile(final UUID ontologyId, final Release active, final UUID classId) { + try { + return compiled(ontologyId, active, classId); + } catch (final WebApplicationException refusal) { + LOG.warn( + "[OntologyChecks] The compile of class {} was refused, so nothing changes for it: {}", + classId, + refusal.getMessage()); + return new Found(new Refused(String.valueOf(refusal.getMessage())), Map.of()); + } catch (final RuntimeException failed) { + LOG.warn( + "[OntologyChecks] The compile of class {} failed, so nothing changes for it", + classId, + failed); + return new Found(new Refused(String.valueOf(failed.getMessage())), Map.of()); + } + } + + private Found compiled(final UUID ontologyId, final Release active, final UUID classId) { + final Optional declared = declared(active, classId); + if (declared.isEmpty()) { + return new Found(new Checks(List.of()), Map.of()); + } + final OntologyConcept type = declared.get(); + final Read read = + reader.read(NO_CALLER, new Asked(type.getId(), type.getIri(), ontologyId, active)); + final List generated = + OntologyShapeCheckAnswer.generated(read.facts(), read.shapes()); + final EntityReference classReference = type.getEntityReference(); + final Map byIdentity = new LinkedHashMap<>(); + final List wanted = new ArrayList<>(); + for (final Generated one : generated) { + final OntologyShapeCheck check = one.check(); + final Wanted want = + new Wanted( + check.getIdentity(), + TestCaseSuggestion.digest( + check.getTestDefinition(), check.getEntityLink(), check.getParameterValues()), + check.getReadBindings().stream() + .map(b -> new Binding(b.getConceptId(), b.getAssetId(), b.getRevision())) + .toList()); + if (byIdentity.putIfAbsent(want.identity(), plan(want, one, classReference, type)) == null) { + wanted.add(want); + } + } + return new Found(new Checks(wanted), byIdentity); + } + + private static Planned plan( + final Wanted wanted, + final Generated one, + final EntityReference classReference, + final OntologyConcept type) { + return new Planned( + wanted, one, classReference, one.shape().getEntityReference(), type.getIri()); + } + + /** The class as the active release declares it, empty when the release lacks it. */ + private Optional declared(final Release active, final UUID classId) { + try { + catalog.working(NO_CALLER, Entity.ONTOLOGY_CONCEPT, classId); + } catch (final org.openmetadata.service.exception.EntityNotFoundException gone) { + return Optional.empty(); + } + return active.member(MemberKind.CONCEPT, classId).map(OntologyConcept.class::cast); + } + + // ---- the writes -------------------------------------------------------------------------- + + private Outcome execute( + final UUID ontologyId, + final String user, + final List writes, + final Map found, + final Map tests, + final Map tasks) { + final int[] counts = new int[6]; + for (final Write write : writes) { + try { + switch (write) { + case CreateTask create -> { + createTask(ontologyId, user, planned(found, create.classId(), create.identity())); + counts[0]++; + } + case ReplaceTask replace -> { + replaceTask( + user, replace.taskId(), planned(found, replace.classId(), replace.identity())); + counts[1]++; + } + case CancelTask cancel -> { + cancelTask(user, cancel); + counts[2]++; + } + case UpdateTest update -> { + updateTest(user, update.testId(), planned(found, update.classId(), update.identity())); + counts[3]++; + } + case DeleteTest delete -> { + deleteTest(user, delete.testId()); + counts[4]++; + } + } + } catch (final RuntimeException failed) { + counts[5]++; + LOG.warn("[OntologyChecks] A write of the reconcile failed: {}", write, failed); + } + } + found.values().stream() + .filter(one -> one.decision() instanceof Refused) + .forEach(one -> counts[5]++); + return new Outcome(counts[0], counts[1], counts[2], counts[3], counts[4], counts[5]); + } + + private static Planned planned( + final Map found, final UUID classId, final String identity) { + return found.get(classId).byIdentity().get(identity); + } + + private TestCaseProposal proposal(final Planned planned, final String name) { + final OntologyShapeCheck check = planned.generated().check(); + final CreateTestCase create = + new CreateTestCase() + .withName(name) + .withDescription(describe(planned)) + .withTestDefinition(check.getTestDefinition()) + .withEntityLink(check.getEntityLink()) + .withParameterValues(check.getParameterValues()); + final TestCaseGeneratedBy by = + new TestCaseGeneratedBy() + .withIdentity(check.getIdentity()) + .withShape(planned.shapeReference()) + .withConstraintId(planned.generated().constraintId()) + .withPart(planned.generated().part().value()) + .withClass(planned.classReference()) + .withReadBindings( + check.getReadBindings().stream().map(OntologyCheckReconciler::generatedBy).toList()) + .withContentDigest(planned.wanted().digest()); + return new TestCaseProposal() + .withTestCase(create) + .withInspectionQuery(check.getInspectionQuery()) + .withGeneratedBy(by); + } + + private static TestCaseGeneratedByBinding generatedBy(final OntologyShapeCheckBinding binding) { + return new TestCaseGeneratedByBinding() + .withConceptId(binding.getConceptId()) + .withAssetId(binding.getAssetId()) + .withRevision(binding.getRevision()); + } + + private static String describe(final Planned planned) { + return "Counts the records of class %s that break the %s of constraint %s of shape %s. A record can span several rows of the table, so the count is of records, not rows." + .formatted( + planned.classIri(), + planned.generated().part().value(), + planned.generated().constraintId(), + planned.generated().shape().getName()); + } + + private static String newName(final String identity) { + return NAME_PREFIX + + identity.substring(0, NAME_IDENTITY_LENGTH) + + "_" + + UUID.randomUUID().toString().replace("-", "").substring(0, NAME_SUFFIX_LENGTH); + } + + private void createTask(final UUID ontologyId, final String user, final Planned planned) { + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final OntologyShapeCheck check = planned.generated().check(); + final TestCaseProposal proposal = proposal(planned, newName(check.getIdentity())); + final Table table = Entity.getEntity(check.getTable(), "owners", Include.NON_DELETED); + final long now = System.currentTimeMillis(); + final Task task = + new Task() + .withId(UUID.randomUUID()) + .withName(proposal.getTestCase().getName()) + .withDescription(proposal.getTestCase().getDescription()) + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.Suggestion) + .withStatus(TaskEntityStatus.Open) + .withAbout(table.getEntityReference()) + .withPayload(suggestion(proposal)) + .withAssignees(assignees(ontologyId, table)) + .withUseEntityOwnerFallback(false) + .withCreatedBy(Entity.getEntityReferenceByName(Entity.USER, user, Include.NON_DELETED)) + .withCreatedAt(now) + .withUpdatedBy(user) + .withUpdatedAt(now); + tasks.create(null, task); + } + + private static SuggestionPayload suggestion(final TestCaseProposal proposal) { + return new SuggestionPayload() + .withSuggestionType(SuggestionPayload.SuggestionType.TEST_CASE) + .withFieldPath(TestCaseSuggestion.FIELD_PATH) + .withSuggestedValue(JsonUtils.pojoToJson(proposal)) + .withSource(SuggestionPayload.Source.INGESTION) + .withReasoning(REASONING); + } + + private void replaceTask(final String user, final UUID taskId, final Planned planned) { + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final Task task = tasks.get(null, taskId, tasks.getFields("*")); + final String name = + TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload())) + .getTestCase() + .getName(); + task.setPayload(suggestion(proposal(planned, name))); + task.setDescription(describe(planned)); + task.setUpdatedBy(user); + task.setUpdatedAt(System.currentTimeMillis()); + tasks.createOrUpdate(null, task, user); + } + + private void cancelTask(final String user, final CancelTask cancel) { + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + tasks.closeTaskAndCancelWorkflowRun( + tasks.get(null, cancel.taskId(), tasks.getFields("*")), user, cancel.reason()); + } + + private void updateTest(final String user, final UUID testId, final Planned planned) { + final TestCaseRepository tests = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + final OntologyShapeCheck check = planned.generated().check(); + final TestCaseProposal proposal = proposal(planned, "unused"); + tests.updateGenerated( + testId, + check.getEntityLink(), + check.getParameterValues(), + proposal.getInspectionQuery(), + proposal.getGeneratedBy(), + user); + } + + private void deleteTest(final String user, final UUID testId) { + final TestCaseRepository tests = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + tests.delete(user, testId, false, false); + } + + // ---- who is asked ------------------------------------------------------------------------ + + /** + * The owners of the table, else the owners of the ontology, as the users who may create tests on + * the table. A team stands for its users, and a user who lacks the right is left out. + */ + private List assignees(final UUID ontologyId, final Table table) { + List owners = listOrEmpty(table.getOwners()); + if (owners.isEmpty()) { + final Ontology ontology = + Entity.getEntity(Entity.ONTOLOGY, ontologyId, "owners", Include.NON_DELETED); + owners = listOrEmpty(ontology.getOwners()); + } + final Map users = new LinkedHashMap<>(); + for (final EntityReference owner : owners) { + for (final EntityReference user : usersOf(owner)) { + if (mayCreateTests(user, table)) { + users.putIfAbsent(user.getId(), user); + } + } + } + return List.copyOf(users.values()); + } + + private static List usersOf(final EntityReference owner) { + if (Entity.USER.equals(owner.getType())) { + return List.of(owner); + } + final Team team = Entity.getEntity(owner, "users", Include.NON_DELETED); + return listOrEmpty(team.getUsers()); + } + + private boolean mayCreateTests(final EntityReference user, final Table table) { + final String name = user.getName(); + if (nullOrEmpty(name)) { + return false; + } + final ChangeActor actor = ChangeActor.user(name, null); + final ResourceContext resource = new ResourceContext<>(Entity.TABLE, table.getId(), null); + for (final MetadataOperation operation : + List.of(MetadataOperation.CREATE_TESTS, MetadataOperation.EDIT_ALL)) { + try { + authorizer.authorizeActor(actor, new OperationContext(Entity.TABLE, operation), resource); + return true; + } catch (final AuthorizationException denied) { + LOG.debug("[OntologyChecks] {} may not {} on {}", name, operation, table.getId()); + } + } + return false; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java new file mode 100644 index 000000000000..7611aa6c2aa1 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java @@ -0,0 +1,209 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * The decision of the reconcile that keeps the tests of shape checks in step with the active + * release and the table bindings (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + * It is a function from what the compile says, what test cases exist and what suggestion tasks + * exist to the list of writes that bring them in line. It reads and writes nothing, so a second + * run over the state that the first one wrote is an empty list. + */ +final class OntologyCheckReconciliation { + /** What closes an open task whose check no longer appears. */ + static final String NO_LONGER_CHECKED = "The shape no longer asks for this check"; + + /** What closes an open task whose check already has a test. */ + static final String ALREADY_TESTED = "A test of this check exists"; + + /** What closes a second open task of one check. */ + static final String ANOTHER_OPEN = "Another open suggestion proposes this check"; + + private OntologyCheckReconciliation() {} + + /** One table binding a check was built from. */ + record Binding(UUID conceptId, UUID assetId, long revision) {} + + /** One check the compile of a class produced. */ + record Wanted(String identity, String digest, List readBindings) {} + + /** What the compile of one class answered. */ + sealed interface Compiled permits Checks, Refused {} + + /** The compile answered with these checks, none included. */ + record Checks(List checks) implements Compiled {} + + /** The compile refused, so nothing can be said about the class. */ + record Refused(String reason) implements Compiled {} + + /** A test case that was generated from a check. */ + record Held( + UUID id, + UUID classId, + String identity, + String digest, + List readBindings, + boolean deleted) {} + + /** Where a suggestion task of a check stands. */ + enum TaskState { + OPEN, + REJECTED, + OTHER + } + + /** A suggestion task that proposes a check. */ + record Proposed( + UUID id, + UUID classId, + String identity, + String digest, + List readBindings, + TaskState state) {} + + /** One write the reconcile makes. */ + sealed interface Write permits UpdateTest, DeleteTest, ReplaceTask, CancelTask, CreateTask {} + + record UpdateTest(UUID testId, UUID classId, String identity) implements Write {} + + record DeleteTest(UUID testId) implements Write {} + + record ReplaceTask(UUID taskId, UUID classId, String identity) implements Write {} + + record CancelTask(UUID taskId, String reason) implements Write {} + + record CreateTask(UUID classId, String identity) implements Write {} + + /** + * The writes that bring the tests and the tasks of each class in line with its checks. A class + * whose compile was refused is left as it is, and so are the tests and tasks of a class that is + * not named. + */ + static List decide( + final Map classes, final List tests, final List tasks) { + final List writes = new ArrayList<>(); + classes.forEach( + (classId, compiled) -> { + if (compiled instanceof Checks checks) { + writes.addAll( + decide(classId, checks.checks(), of(tests, classId), ofTasks(tasks, classId))); + } + }); + return List.copyOf(writes); + } + + private static List of(final List tests, final UUID classId) { + return tests.stream().filter(test -> classId.equals(test.classId())).toList(); + } + + private static List ofTasks(final List tasks, final UUID classId) { + return tasks.stream().filter(task -> classId.equals(task.classId())).toList(); + } + + private static List decide( + final UUID classId, + final List checks, + final List tests, + final List tasks) { + final List writes = new ArrayList<>(); + final Set wanted = new HashSet<>(); + final Set claimed = new HashSet<>(); + for (final Wanted check : checks) { + if (wanted.add(check.identity())) { + writes.addAll(forCheck(classId, check, tests, tasks, claimed)); + } + } + tests.stream() + .filter(test -> !test.deleted() && !wanted.contains(test.identity())) + .forEach(test -> writes.add(new DeleteTest(test.id()))); + tasks.stream() + .filter(task -> task.state() == TaskState.OPEN && !claimed.contains(task.id())) + .forEach(task -> writes.add(new CancelTask(task.id(), reasonFor(task, wanted, tests)))); + return writes; + } + + private static String reasonFor( + final Proposed task, final Set wanted, final List tests) { + if (!wanted.contains(task.identity())) { + return NO_LONGER_CHECKED; + } + final boolean tested = + tests.stream().anyMatch(test -> !test.deleted() && test.identity().equals(task.identity())); + return tested ? ALREADY_TESTED : ANOTHER_OPEN; + } + + private static List forCheck( + final UUID classId, + final Wanted check, + final List tests, + final List tasks, + final Set claimed) { + final List mine = + tests.stream().filter(test -> test.identity().equals(check.identity())).toList(); + final List live = mine.stream().filter(test -> !test.deleted()).toList(); + if (!live.isEmpty()) { + return changed(check, live.getFirst().digest(), live.getFirst().readBindings()) + ? List.of(new UpdateTest(live.getFirst().id(), classId, check.identity())) + : List.of(); + } + final List open = + tasks.stream() + .filter(task -> task.identity().equals(check.identity())) + .filter(task -> task.state() == TaskState.OPEN) + .toList(); + if (!open.isEmpty()) { + claimed.add(open.getFirst().id()); + return changed(check, open.getFirst().digest(), open.getFirst().readBindings()) + ? List.of(new ReplaceTask(open.getFirst().id(), classId, check.identity())) + : List.of(); + } + return alreadyAnswered(check, mine, tasks) + ? List.of() + : List.of(new CreateTask(classId, check.identity())); + } + + /** A person rejected this content, or deleted the test generated from it. */ + private static boolean alreadyAnswered( + final Wanted check, final List mine, final List tasks) { + return mine.stream().anyMatch(test -> test.deleted() && test.digest().equals(check.digest())) + || tasks.stream() + .anyMatch( + task -> + task.identity().equals(check.identity()) + && task.state() == TaskState.REJECTED + && task.digest().equals(check.digest())); + } + + private static boolean changed( + final Wanted check, final String digest, final List bindings) { + return !check.digest().equals(digest) || !sameBindings(check.readBindings(), bindings); + } + + private static boolean sameBindings(final List left, final List right) { + return new HashSet<>(left).equals(new HashSet<>(right)); + } + + /** Keeps the order the classes were named in. */ + static Map ordered() { + return new LinkedHashMap<>(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java index 6d955db9a6af..cf7e4d2bebc5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java @@ -38,11 +38,13 @@ import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore.Mutation; import org.openmetadata.service.ontology.OntologyTableBindingChecks.Write; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.util.FreshReadScope; import org.openmetadata.service.util.FullyQualifiedName; +import org.openmetadata.service.util.PostCommitActionQueue; import org.openmetadata.service.util.RestUtil; @Slf4j @@ -180,7 +182,8 @@ private OntologyConcept write( final Access access, final UUID conceptId, final Replacement replacement) { OntologyBindingRules.validate(replacement.asset()); final var concept = concept(access, conceptId, MetadataOperation.EDIT_ALL); - store.update( + update( + access, concept, (lockedConcept, locked, current) -> replace(access, lockedConcept, locked, current, replacement)); @@ -196,7 +199,8 @@ public OntologyConceptBindingsResponse remove( OntologyBindingRules.requireRevision(expectedRevision); final var type = assetType(assetType); final var concept = concept(access, conceptId, MetadataOperation.EDIT_ALL); - store.update( + update( + access, concept, (lockedConcept, locked, current) -> { concept(access, lockedConcept.getId(), MetadataOperation.EDIT_ALL); @@ -212,6 +216,32 @@ public OntologyConceptBindingsResponse remove( return firstPage(access, concept); } + /** + * Writes under the ontology lock, and when the write moves the binding revision of the class asks + * for the reconcile of its checks once the outermost transaction has committed. + */ + private void update(final Access access, final OntologyConcept concept, final Mutation mutation) { + final boolean[] moved = {false}; + store.update( + concept, + (lockedConcept, locked, current) -> { + final long next = mutation.apply(lockedConcept, locked, current); + moved[0] = next != current; + return next; + }); + if (moved[0]) { + final UUID ontologyId = concept.getOntology().getId(); + final String user = + access.securityContext() == null + ? Entity.ADMIN_USER_NAME + : access.securityContext().getUserPrincipal().getName(); + PostCommitActionQueue.runOrDefer( + () -> + OntologyCheckReconcileQueue.instance() + .afterBindingWrite(ontologyId, concept.getId(), user)); + } + } + private long replace( final Access access, final OntologyConcept concept, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java index bca08f070599..cc106894e7b5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java @@ -14,6 +14,7 @@ package org.openmetadata.service.ontology; import java.net.URI; +import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; @@ -90,6 +91,41 @@ private OntologyShapeCheckAnswer(final OntologyShapeCheckFacts facts, final Hidd */ record Hidden(Set tables, Set paths, Set classes) {} + /** One generated check with the shape, the constraint and the part it comes from. */ + record Generated( + OntologyShape shape, String constraintId, OntologyShapePart part, OntologyShapeCheck check) {} + + /** + * Every check of the compile, for no caller: nothing is masked. A caller's answer is a view of + * this list, and a step that creates tests reads this one, so it never reads a hidden check as + * absent. + */ + static List generated( + final OntologyShapeCheckFacts facts, final List shapes) { + final OntologyShapeCheckAnswer answer = + new OntologyShapeCheckAnswer(facts, new Hidden(Set.of(), Set.of(), Set.of())); + final List found = new ArrayList<>(); + for (final CompiledShape shape : OntologyShapeCheckCompiler.compile(facts, shapes)) { + for (final CompiledConstraint constraint : shape.constraints()) { + for (final CompiledPart part : constraint.parts()) { + if (part.outcome() instanceof Check checks) { + final Named named = + new Named(shape.shape().getId(), constraint.constraint().getId(), part.part()); + for (final TableCheck test : checks.checks()) { + found.add( + new Generated( + shape.shape(), + named.constraintId(), + named.part(), + answer.check(named, test))); + } + } + } + } + } + return List.copyOf(found); + } + /** The part of one constraint of one shape that a test checks. */ private record Named(UUID shapeId, String constraintId, OntologyShapePart part) {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java index 9225b5f5320a..7f306addf9f0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java @@ -100,6 +100,7 @@ import org.openmetadata.service.ontology.NativeOntologyDataGraphService; import org.openmetadata.service.ontology.NativeOntologyDataGraphService.Query; import org.openmetadata.service.ontology.NativeOntologyTopologyCursorCodec; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; import org.openmetadata.service.ontology.OntologyConceptBindingService; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.ontology.OntologyDraftQuery; @@ -286,13 +287,16 @@ public OntologyState activateRelease( securityContext, new OperationContext(Entity.ONTOLOGY, MetadataOperation.EDIT_ALL), getResourceContextById(id)); - return releaseActivation.activate( - id, - request, - new OntologyReleaseActivation.Access( - user(securityContext), - definition -> - OntologyResourceAccess.requireView(authorizer, securityContext, definition))); + final OntologyState state = + releaseActivation.activate( + id, + request, + new OntologyReleaseActivation.Access( + user(securityContext), + definition -> + OntologyResourceAccess.requireView(authorizer, securityContext, definition))); + OntologyCheckReconcileQueue.instance().afterActivation(id, user(securityContext)); + return state; } @POST diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java index 77258c31c185..1ef61b1cc266 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java @@ -87,6 +87,11 @@ private static Set declaredKeys() { * compared exactly, so {@code SuggestedValue} is not {@code suggestedValue}. */ public static void requireDeclaredKeys(JsonNode payload) { + requireDeclaredKeys(payload, "A table constraint suggestion"); + } + + /** The same refusal for a suggestion type that names itself in the message. */ + static void requireDeclaredKeys(JsonNode payload, String subject) { Set undeclared = new TreeSet<>(); payload .fieldNames() @@ -98,18 +103,33 @@ public static void requireDeclaredKeys(JsonNode payload) { }); if (!undeclared.isEmpty()) { throw BadRequestException.of( - "A table constraint suggestion carries only the keys of the suggestion payload (%s); not allowed: %s" - .formatted(String.join(", ", DECLARED_KEYS), String.join(", ", undeclared))); + "%s carries only the keys of the suggestion payload (%s); not allowed: %s" + .formatted(subject, String.join(", ", DECLARED_KEYS), String.join(", ", undeclared))); } } /** Refuses a payload of a table constraint suggestion that has a key the schema does not declare. */ public static void requireDeclaredKeys(Task task) { - if (isTableConstraint(task)) { - requireDeclaredKeys(JsonUtils.valueToTree(task.getPayload())); + if (isKeyRestricted(task)) { + requireDeclaredKeys(JsonUtils.valueToTree(task.getPayload()), subjectOf(task)); } } + /** A suggestion type whose payload holds only the declared keys and keeps its type. */ + static boolean isKeyRestricted(Task task) { + return isTableConstraint(task) || TestCaseSuggestion.isTestCase(task); + } + + private static boolean isRestricted(String suggestionType) { + return TYPE.equals(suggestionType) || TestCaseSuggestion.TYPE.equals(suggestionType); + } + + private static String subjectOf(Task task) { + return TestCaseSuggestion.isTestCase(task) + ? "A test case suggestion" + : "A table constraint suggestion"; + } + /** * Refuses a resolution that would write a key the suggestion payload does not declare into a * table constraint suggestion, whatever the resolution is: a key of the request's payload, or the @@ -117,7 +137,7 @@ public static void requireDeclaredKeys(Task task) { * the resolution's, so it does not refuse a resolution that adds no key. */ public static void requireNoNewKeys(Task task, Object requestPayload, String newValue) { - if (!isTableConstraint(task)) { + if (!isKeyRestricted(task)) { return; } ObjectNode added = JsonUtils.getObjectNode(); @@ -130,7 +150,7 @@ public static void requireNoNewKeys(Task task, Object requestPayload, String new if (newValue != null && valueField != null) { added.put(valueField, newValue); } - requireDeclaredKeys(added); + requireDeclaredKeys(added, subjectOf(task)); } public static boolean isTableConstraint(Task task) { @@ -155,10 +175,10 @@ public static void requireSameSuggestionType(Task task, Object requestPayload) { String stored = suggestionTypeOf(task.getPayload()); String requested = suggestionTypeOf(requestPayload); boolean changed = !requested.isEmpty() && !requested.equals(stored); - if (changed && (TYPE.equals(stored) || TYPE.equals(requested))) { + if (changed && (isRestricted(stored) || isRestricted(requested))) { throw BadRequestException.of( "A resolution cannot change the suggestion type of a task to or from %s: the task is '%s', the resolution says '%s'" - .formatted(TYPE, stored, requested)); + .formatted(isRestricted(stored) ? stored : requested, stored, requested)); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 37d528fa0ce6..c1304b014ccc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -45,6 +45,8 @@ import org.openmetadata.schema.entity.tasks.Task; import org.openmetadata.schema.governance.workflows.WorkflowDefinition; import org.openmetadata.schema.governance.workflows.elements.EdgeDefinition; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestSuite; import org.openmetadata.schema.type.ChangeEvent; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EventType; @@ -59,6 +61,7 @@ import org.openmetadata.schema.type.TaskResolutionType; import org.openmetadata.schema.type.TaskReviewVote; import org.openmetadata.schema.type.TaskReviewVoteDecision; +import org.openmetadata.schema.type.TestCaseProposal; import org.openmetadata.schema.type.change.ChangeSource; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -77,8 +80,11 @@ import org.openmetadata.service.governance.workflows.WorkflowHandler; import org.openmetadata.service.governance.workflows.WorkflowHandler.TaskResolutionOutcome; import org.openmetadata.service.governance.workflows.metadata.MetadataCollectionService; +import org.openmetadata.service.jdbi3.DataContractRepository; import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.GeneratedTestScope; import org.openmetadata.service.jdbi3.TaskRepository; +import org.openmetadata.service.jdbi3.TestCaseRepository; import org.openmetadata.service.jdbi3.WorkflowInstanceRepository; import org.openmetadata.service.resources.tags.TagLabelUtil; import org.openmetadata.service.tasks.TaskFormExecutionResolver.TaskExecutionAction; @@ -204,6 +210,7 @@ public Task resolveTask( if (isPositiveResolution(effectiveResolutionType)) { TableConstraintSuggestion.requireSameSuggestionType(task, resolvedPayload); TableConstraintSuggestion.requireToApply(task, resolvedPayload, newValue); + TestCaseSuggestion.requireToApply(task, resolvedPayload, newValue); } ReviewOutcome outcome = @@ -793,6 +800,9 @@ static Optional resolutionComment( if (approved && TableConstraintSuggestion.isTableConstraint(task)) { commentMessage = Optional.of(TableConstraintSuggestion.resolutionComment(task, resolvedPayload, newValue)); + } else if (approved && TestCaseSuggestion.isTestCase(task)) { + commentMessage = + Optional.of(TestCaseSuggestion.resolutionComment(task, resolvedPayload, newValue)); } else if (approved && newValue != null && !newValue.isEmpty()) { commentMessage = providesNewValue(task, newValue) @@ -866,7 +876,7 @@ private void applyEntityChanges( // No task form changes what approving a table constraint does: it adds the constraint and // nothing else, and rejecting it writes nothing, whatever handler and actions the form names. - if (TableConstraintSuggestion.isTableConstraint(task)) { + if (TableConstraintSuggestion.isKeyRestricted(task)) { if (approved) { applySuggestion(task, effectivePayload, entity, repository, user); } @@ -889,7 +899,7 @@ private void applyEntityChanges( } catch (Exception e) { LOG.error( "[TaskWorkflowHandler] Failed to apply entity changes for task '{}'", task.getId(), e); - if (TableConstraintSuggestion.isTableConstraint(task)) { + if (TableConstraintSuggestion.isKeyRestricted(task)) { // The task stays open: approving it must not report a constraint that was not added. throw e; } @@ -1434,12 +1444,15 @@ private void applySuggestion( } else if (TableConstraintSuggestion.isTableConstraint(task) && TableConstraintSuggestion.TYPE.equals(suggestionType)) { applyTableConstraint(payloadNode, entity, repository, user); + } else if (TestCaseSuggestion.isTestCase(task) + && TestCaseSuggestion.TYPE.equals(suggestionType)) { + applyTestCase(payloadNode, (Table) entity, user); } else { LOG.debug("[TaskWorkflowHandler] Unknown suggestion type: {}", suggestionType); } } catch (Exception e) { LOG.error("[TaskWorkflowHandler] Failed to apply Suggestion", e); - if (TableConstraintSuggestion.isTableConstraint(task)) { + if (TableConstraintSuggestion.isKeyRestricted(task)) { throw e; } } @@ -1473,6 +1486,34 @@ private void applyTableConstraint( table.getFullyQualifiedName()); } + /** + * Creates the proposed test case as the approver, in the basic test suite of its table. A test + * the table has already is left as it is. The suite gets a pipeline that runs daily at midnight + * when it has none. + */ + private void applyTestCase(JsonNode payloadNode, Table table, String user) { + TestCaseProposal proposal = TestCaseSuggestion.proposalOf(payloadNode); + if (TestCaseSuggestion.exists(table, proposal.getTestCase())) { + LOG.info( + "[TaskWorkflowHandler] Table '{}' already has the suggested test case", + table.getFullyQualifiedName()); + return; + } + TestCaseRepository tests = (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + TestCase created; + try (GeneratedTestScope.Handle ignored = GeneratedTestScope.enter()) { + created = tests.create(null, TestCaseSuggestion.testCaseOf(proposal, user)); + } + TestSuite suite = Entity.getEntity(created.getTestSuite(), "*", Include.NON_DELETED); + DataContractRepository contracts = + (DataContractRepository) Entity.getEntityRepository(Entity.DATA_CONTRACT); + contracts.ensureScheduledPipeline(suite, TestCaseSuggestion.DAILY_AT_MIDNIGHT); + LOG.info( + "[TaskWorkflowHandler] Created test case '{}' on table '{}'", + created.getName(), + table.getFullyQualifiedName()); + } + private void applyEntityLevelTags( EntityInterface entity, EntityRepository repository, String user, List tags) { String before = JsonUtils.pojoToJson(entity); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java new file mode 100644 index 000000000000..396be985cbfd --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java @@ -0,0 +1,258 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.tasks; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.schema.api.tests.CreateTestCase; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TestCaseProposal; +import org.openmetadata.schema.utils.EntityInterfaceUtil; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * A suggestion task of type {@code TestCase} proposes one test case for the table it is about. Its + * {@code suggestedValue} is a {@link TestCaseProposal} written as JSON, and its field path is + * {@code testCases}. Approving it creates the test case, and rejecting it creates nothing + * (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + * + *

    A proposal is refused when it is filed, and again when it is approved with the resolver's + * payload laid over it, unless it is the test {@code tableCustomSQLQuery} on the table the task is + * about, with the four parameters a shape check has and a content digest that matches them. Like a + * table constraint suggestion, its payload holds only the keys that the suggestion payload + * declares. + */ +public final class TestCaseSuggestion { + public static final String TYPE = "TestCase"; + public static final String FIELD_PATH = "testCases"; + public static final String DAILY_AT_MIDNIGHT = "0 0 * * *"; + public static final String CUSTOM_SQL = "tableCustomSQLQuery"; + public static final String SQL_EXPRESSION = "sqlExpression"; + public static final String STRATEGY = "strategy"; + public static final String OPERATOR = "operator"; + public static final String THRESHOLD = "threshold"; + private static final List PARAMETERS = + List.of(SQL_EXPRESSION, STRATEGY, OPERATOR, THRESHOLD); + private static final String SUGGESTION_TYPE = "suggestionType"; + private static final ObjectMapper CANONICAL = + new ObjectMapper().configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); + + private TestCaseSuggestion() {} + + public static boolean isTestCase(Task task) { + return task != null + && task.getType() == TaskEntityType.Suggestion + && TYPE.equals( + task.getPayload() == null + ? "" + : JsonUtils.valueToTree(task.getPayload()).path(SUGGESTION_TYPE).asText("")); + } + + /** + * Lowercase hex SHA-256 of the canonical JSON of the test definition, the entity link and the + * parameter values. The keys are sorted and the parameters keep their order. + */ + public static String digest( + String testDefinition, String entityLink, List parameters) { + Map content = new TreeMap<>(); + content.put("testDefinition", testDefinition); + content.put("entityLink", entityLink); + List> values = new ArrayList<>(); + for (TestCaseParameterValue parameter : listOrEmpty(parameters)) { + Map value = new TreeMap<>(); + value.put("name", parameter.getName()); + value.put("value", parameter.getValue()); + values.add(value); + } + content.put("parameterValues", values); + try { + return DigestUtils.sha256Hex(CANONICAL.writeValueAsString(content)); + } catch (JsonProcessingException e) { + throw new IllegalStateException("A test case digest is always serializable", e); + } + } + + /** The proposal a task's {@code suggestedValue} carries. */ + public static TestCaseProposal proposalOf(JsonNode payload) { + String suggestedValue = payload.path("suggestedValue").asText(""); + try { + TestCaseProposal proposal = JsonUtils.readValue(suggestedValue, TestCaseProposal.class); + if (proposal == null || proposal.getTestCase() == null) { + throw BadRequestException.of("Suggested value is not a test case proposal: no testCase"); + } + return proposal; + } catch (BadRequestException e) { + throw e; + } catch (RuntimeException e) { + throw BadRequestException.of("Suggested value is not a test case proposal"); + } + } + + /** Refuses filing a test case suggestion that is not a valid proposal for its table. */ + public static void require(Task task) { + if (isTestCase(task)) { + TableConstraintSuggestion.requireDeclaredKeys(task); + validate(task, JsonUtils.valueToTree(task.getPayload())); + } + } + + /** Refuses approving a suggestion that, with the resolver's payload laid over it, is not valid. */ + public static void requireToApply(Task task, Object requestPayload, String newValue) { + if (isTestCase(task)) { + JsonNode merged = + JsonUtils.valueToTree( + TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + TableConstraintSuggestion.requireDeclaredKeys(merged, "A test case suggestion"); + validate(task, merged); + } + } + + /** + * The comment an approval leaves: the test case it creates and its table, or the test case the + * table already has. A new value is not named, because it never changes the test. + */ + public static String resolutionComment(Task task, Object requestPayload, String newValue) { + JsonNode merged = + JsonUtils.valueToTree( + TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + CreateTestCase create = proposalOf(merged).getTestCase(); + Table table = loadTable(task); + String prefix = exists(table, create) ? "Test case already exists" : "Created test case"; + return "%s %s on table %s".formatted(prefix, create.getName(), table.getFullyQualifiedName()); + } + + /** True when a test case of that name is on the table already, deleted or not. */ + public static boolean exists(Table table, CreateTestCase create) { + String fqn = + FullyQualifiedName.add( + table.getFullyQualifiedName(), EntityInterfaceUtil.quoteName(create.getName())); + try { + Entity.getEntityByName(Entity.TEST_CASE, fqn, "", Include.ALL); + return true; + } catch (EntityNotFoundException e) { + return false; + } + } + + /** The table a task is about, which a test case suggestion must name. */ + public static Table loadTable(Task task) { + if (task.getAbout() == null || !Entity.TABLE.equals(task.getAbout().getType())) { + throw BadRequestException.of( + "A test case suggestion must be about a table, not %s" + .formatted(task.getAbout() == null ? "nothing" : task.getAbout().getType())); + } + return Entity.getEntity(task.getAbout(), "", Include.NON_DELETED); + } + + private static void validate(Task task, JsonNode payload) { + String fieldPath = payload.path("fieldPath").asText(null); + if (!FIELD_PATH.equals(fieldPath)) { + throw BadRequestException.of( + "Field path of a test case suggestion must be '%s', not '%s'" + .formatted(FIELD_PATH, fieldPath)); + } + Table table = loadTable(task); + TestCaseProposal proposal = proposalOf(payload); + CreateTestCase create = proposal.getTestCase(); + requireTableTest(table, create); + requireParameters(create); + requireGenerated(proposal); + } + + private static void requireTableTest(Table table, CreateTestCase create) { + if (!CUSTOM_SQL.equals(create.getTestDefinition())) { + throw BadRequestException.of( + "A test case suggestion proposes the test %s, not %s" + .formatted(CUSTOM_SQL, create.getTestDefinition())); + } + EntityLink link = EntityLink.parse(create.getEntityLink()); + if (!Entity.TABLE.equals(link.getEntityType()) + || link.getFieldName() != null + || !table.getFullyQualifiedName().equals(link.getEntityFQN())) { + throw BadRequestException.of( + "A test case suggestion proposes a test of the table it is about, %s, not %s" + .formatted(table.getFullyQualifiedName(), create.getEntityLink())); + } + if (nullOrEmpty(create.getName())) { + throw BadRequestException.of("A test case suggestion proposes a test with a name"); + } + if (Boolean.TRUE.equals(create.getComputePassedFailedRowCount())) { + throw BadRequestException.of( + "A test case suggestion proposes a test that does not compute passed and failed rows"); + } + } + + private static void requireParameters(CreateTestCase create) { + List values = listOrEmpty(create.getParameterValues()); + List names = values.stream().map(TestCaseParameterValue::getName).toList(); + if (!PARAMETERS.equals(names)) { + throw BadRequestException.of( + "A test case suggestion proposes the parameters %s in that order, not %s" + .formatted(PARAMETERS, names)); + } + if (nullOrEmpty(values.get(0).getValue()) + || !"COUNT".equals(values.get(1).getValue()) + || !"<=".equals(values.get(2).getValue()) + || !"0".equals(values.get(3).getValue())) { + throw BadRequestException.of( + "A test case suggestion counts the records in violation: strategy COUNT, operator <= and" + + " threshold 0, with a statement"); + } + } + + private static void requireGenerated(TestCaseProposal proposal) { + TestCaseGeneratedBy generatedBy = proposal.getGeneratedBy(); + CreateTestCase create = proposal.getTestCase(); + if (nullOrEmpty(proposal.getInspectionQuery())) { + throw BadRequestException.of("A test case suggestion carries the inspection query"); + } + String digest = + digest(create.getTestDefinition(), create.getEntityLink(), create.getParameterValues()); + if (generatedBy == null || !digest.equals(generatedBy.getContentDigest())) { + throw BadRequestException.of( + "The content digest of a test case suggestion must be that of its test definition, entity" + + " link and parameter values: %s".formatted(digest)); + } + } + + /** The test case to create: the proposal's values with the approver as its creator. */ + public static TestCase testCaseOf(TestCaseProposal proposal, String approver) { + CreateTestCase create = proposal.getTestCase(); + return new org.openmetadata.service.resources.dqtests.TestCaseMapper() + .createToEntity(create, approver) + .withInspectionQuery(proposal.getInspectionQuery()) + .withGeneratedBy(proposal.getGeneratedBy()); + } +} diff --git a/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TestCaseSuggestion.json b/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TestCaseSuggestion.json new file mode 100644 index 000000000000..bd86cdd38b57 --- /dev/null +++ b/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TestCaseSuggestion.json @@ -0,0 +1,31 @@ +{ + "name": "TestCaseSuggestion", + "displayName": "Test Case Suggestion", + "taskType": "Suggestion", + "taskCategory": "MetadataUpdate", + "formSchema": { + "type": "object", + "required": [ + "suggestedValue" + ], + "properties": { + "suggestedValue": { + "type": "string", + "title": "Suggested Test Case (JSON)" + }, + "reasoning": { + "type": "string", + "title": "Reason for suggestion" + } + } + }, + "uiSchema": { + "suggestedValue": { + "ui:widget": "textarea" + }, + "reasoning": { + "ui:widget": "textarea" + } + }, + "fullyQualifiedName": "TestCaseSuggestion" +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java new file mode 100644 index 000000000000..b75d74921ee4 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java @@ -0,0 +1,131 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.jdbi3; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.service.exception.BadRequestException; + +class GeneratedTestScopeTest { + private static final String SET_BY_SERVER = + "generatedBy is set by the server when a suggestion creates a test from a shape, and cannot be sent or changed"; + + @Test + void aCreateThatSendsGeneratedByIsRefused() { + BadRequestException e = + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnsetOnCreate(generated(UUID.randomUUID(), "a = 1"))); + assertEquals(SET_BY_SERVER, e.getMessage()); + } + + @Test + void aCreateInsideTheScopeIsAccepted() { + try (GeneratedTestScope.Handle ignored = GeneratedTestScope.enter()) { + assertTrue(GeneratedTestScope.isActive()); + assertDoesNotThrow( + () -> GeneratedTestScope.requireUnsetOnCreate(generated(UUID.randomUUID(), "a = 1"))); + } + assertFalse(GeneratedTestScope.isActive()); + } + + @Test + void aPersonsTestMayCarryNoGeneratedByAndMayChangeFreely() { + TestCase original = plain(UUID.randomUUID(), "a = 1"); + TestCase updated = plain(original.getTestDefinition().getId(), "a = 2"); + assertDoesNotThrow(() -> GeneratedTestScope.requireUnchanged(original, updated)); + } + + @Test + void aPatchThatAddsOrChangesGeneratedByIsRefused() { + UUID definition = UUID.randomUUID(); + assertEquals( + SET_BY_SERVER, + assertThrows( + BadRequestException.class, + () -> + GeneratedTestScope.requireUnchanged( + plain(definition, "a = 1"), generated(definition, "a = 1"))) + .getMessage()); + TestCase other = generated(definition, "a = 1"); + other.getGeneratedBy().setIdentity("b".repeat(64)); + assertEquals( + SET_BY_SERVER, + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnchanged(generated(definition, "a = 1"), other)) + .getMessage()); + } + + @Test + void aChangeToWhatAGeneratedTestFreezesIsRefused() { + UUID definition = UUID.randomUUID(); + TestCase original = generated(definition, "a = 1"); + assertEquals( + GeneratedTestScope.FROM_A_SHAPE, + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnchanged(original, generated(definition, "a = 2"))) + .getMessage()); + TestCase otherLink = generated(definition, "a = 1").withEntityLink("<#E::table::x.y.z.t>"); + assertThrows( + BadRequestException.class, () -> GeneratedTestScope.requireUnchanged(original, otherLink)); + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnchanged(original, generated(UUID.randomUUID(), "a = 1"))); + } + + @Test + void aChangeToDescriptionOnlyIsAccepted() { + UUID definition = UUID.randomUUID(); + TestCase updated = generated(definition, "a = 1").withDescription("now with words"); + assertDoesNotThrow( + () -> GeneratedTestScope.requireUnchanged(generated(definition, "a = 1"), updated)); + } + + @Test + void theReconcileMayChangeWhatIsFrozenInsideTheScope() { + UUID definition = UUID.randomUUID(); + try (GeneratedTestScope.Handle ignored = GeneratedTestScope.enter()) { + assertDoesNotThrow( + () -> + GeneratedTestScope.requireUnchanged( + generated(definition, "a = 1"), generated(definition, "a = 2"))); + } + } + + private static TestCase plain(final UUID definition, final String statement) { + return new TestCase() + .withEntityLink("<#E::table::svc.db.schema.t>") + .withTestDefinition(new EntityReference().withId(definition).withType("testDefinition")) + .withParameterValues( + List.of(new TestCaseParameterValue().withName("sqlExpression").withValue(statement))); + } + + private static TestCase generated(final UUID definition, final String statement) { + return plain(definition, statement) + .withGeneratedBy(new TestCaseGeneratedBy().withIdentity("a".repeat(64))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java new file mode 100644 index 000000000000..8bba888e508c --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java @@ -0,0 +1,267 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Binding; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.CancelTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Checks; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Compiled; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.CreateTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.DeleteTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Held; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Proposed; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Refused; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.ReplaceTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TaskState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.UpdateTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Wanted; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Write; + +class OntologyCheckReconciliationTest { + private static final UUID CLASS = UUID.fromString("00000000-0000-0000-0000-0000000000c1"); + private static final UUID OTHER_CLASS = UUID.fromString("00000000-0000-0000-0000-0000000000c2"); + private static final UUID ASSET = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); + private static final UUID ID_1 = UUID.fromString("00000000-0000-0000-0000-000000000001"); + private static final UUID ID_2 = UUID.fromString("00000000-0000-0000-0000-000000000002"); + private static final List REV_3 = List.of(new Binding(CLASS, ASSET, 3)); + private static final List REV_4 = List.of(new Binding(CLASS, ASSET, 4)); + + private static Wanted check(final String identity, final String digest, final List b) { + return new Wanted(identity, digest, b); + } + + private static Held test( + final UUID id, final String identity, final String digest, final boolean deleted) { + return new Held(id, CLASS, identity, digest, REV_3, deleted); + } + + private static Proposed task( + final UUID id, final String identity, final String digest, final TaskState state) { + return new Proposed(id, CLASS, identity, digest, REV_3, state); + } + + private static List decide( + final Compiled compiled, final List tests, final List tasks) { + final Map classes = new LinkedHashMap<>(); + classes.put(CLASS, compiled); + return OntologyCheckReconciliation.decide(classes, tests, tasks); + } + + @Test + void aCheckWithNoTestAndNoTaskGetsANewTask() { + final List writes = + decide(new Checks(List.of(check("a", "d1", REV_3))), List.of(), List.of()); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void aTestWhoseDigestChangedIsUpdatedInPlace() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(test(ID_1, "a", "d1", false)), + List.of()); + assertEquals(List.of(new UpdateTest(ID_1, CLASS, "a")), writes); + } + + @Test + void aTestWhoseReadBindingsChangedIsUpdatedInPlace() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_4))), + List.of(test(ID_1, "a", "d1", false)), + List.of()); + assertEquals(List.of(new UpdateTest(ID_1, CLASS, "a")), writes); + } + + @Test + void aTestWithTheSameDigestAndBindingsIsLeftAlone() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_1, "a", "d1", false)), + List.of()); + assertEquals(List.of(), writes); + } + + @Test + void aTestMakesTheOpenTaskOfTheSameCheckWait() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(test(ID_1, "a", "d1", false)), + List.of(task(ID_2, "a", "d1", TaskState.OPEN))); + assertEquals( + List.of( + new UpdateTest(ID_1, CLASS, "a"), new CancelTask(ID_2, "A test of this check exists")), + writes); + } + + @Test + void anOpenTaskWhoseContentChangedGetsItsValueReplaced() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.OPEN))); + assertEquals(List.of(new ReplaceTask(ID_2, CLASS, "a")), writes); + } + + @Test + void anOpenTaskWithTheSameContentIsLeftAlone() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.OPEN))); + assertEquals(List.of(), writes); + } + + @Test + void aRejectedTaskOfTheSameContentProposesNothing() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.REJECTED))); + assertEquals(List.of(), writes); + } + + @Test + void aRejectedTaskOfOtherContentIsProposedAgain() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.REJECTED))); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void aTestAPersonDeletedWithTheSameDigestProposesNothing() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_1, "a", "d1", true)), + List.of()); + assertEquals(List.of(), writes); + } + + @Test + void aTestAPersonDeletedWithOtherContentIsProposedAgain() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(test(ID_1, "a", "d1", true)), + List.of()); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void aTestWhoseCheckNoLongerAppearsIsDeletedAndItsOpenTaskCancelled() { + final List writes = + decide( + new Checks(List.of()), + List.of(test(ID_1, "a", "d1", false)), + List.of(task(ID_2, "b", "d1", TaskState.OPEN))); + assertEquals( + List.of( + new DeleteTest(ID_1), + new CancelTask(ID_2, OntologyCheckReconciliation.NO_LONGER_CHECKED)), + writes); + } + + @Test + void aTestAlreadyDeletedOrATaskAlreadyClosedWhoseCheckVanishedIsNotTouched() { + final List writes = + decide( + new Checks(List.of()), + List.of(test(ID_1, "a", "d1", true)), + List.of( + task(ID_2, "b", "d1", TaskState.REJECTED), + task(UUID.randomUUID(), "c", "d1", TaskState.OTHER))); + assertEquals(List.of(), writes); + } + + @Test + void aRefusedCompileChangesNothingForItsClassAndStillReconcilesAnother() { + final Map classes = new LinkedHashMap<>(); + classes.put(CLASS, new Refused("Binding property inheritance exceeds the 10000 axiom limit")); + classes.put(OTHER_CLASS, new Checks(List.of())); + final Held kept = test(ID_1, "a", "d1", false); + final Held goes = new Held(ID_2, OTHER_CLASS, "z", "d1", REV_3, false); + final Proposed openTask = task(UUID.randomUUID(), "b", "d1", TaskState.OPEN); + final List writes = + OntologyCheckReconciliation.decide(classes, List.of(kept, goes), List.of(openTask)); + assertEquals(List.of(new DeleteTest(ID_2)), writes); + } + + @Test + void anEmptyRunWritesNothing() { + assertEquals(List.of(), OntologyCheckReconciliation.decide(Map.of(), List.of(), List.of())); + assertEquals(List.of(), decide(new Checks(List.of()), List.of(), List.of())); + } + + @Test + void aSecondRunOverTheStateTheFirstRunWroteWritesNothing() { + final Wanted created = check("a", "d2", REV_4); + final Wanted replaced = check("b", "d2", REV_4); + final Wanted fresh = check("c", "d1", REV_3); + final List tests = List.of(test(ID_1, "a", "d1", false)); + final List tasks = List.of(task(ID_2, "b", "d1", TaskState.OPEN)); + final List first = decide(new Checks(List.of(created, replaced, fresh)), tests, tasks); + assertEquals( + List.of( + new UpdateTest(ID_1, CLASS, "a"), + new ReplaceTask(ID_2, CLASS, "b"), + new CreateTask(CLASS, "c")), + first); + final List testsAfter = List.of(new Held(ID_1, CLASS, "a", "d2", REV_4, false)); + final List tasksAfter = + List.of( + new Proposed(ID_2, CLASS, "b", "d2", REV_4, TaskState.OPEN), + new Proposed(UUID.randomUUID(), CLASS, "c", "d1", REV_3, TaskState.OPEN)); + assertEquals( + List.of(), decide(new Checks(List.of(created, replaced, fresh)), testsAfter, tasksAfter)); + } + + @Test + void twoOpenTasksOfOneCheckKeepOneAndCancelTheOther() { + final UUID duplicate = UUID.fromString("00000000-0000-0000-0000-000000000003"); + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(), + List.of( + task(ID_2, "a", "d1", TaskState.OPEN), task(duplicate, "a", "d1", TaskState.OPEN))); + assertEquals( + List.of(new CancelTask(duplicate, "Another open suggestion proposes this check")), writes); + } + + @Test + void theTestsOfAClassThatIsNotNamedAreNotTouched() { + final Held elsewhere = new Held(ID_1, OTHER_CLASS, "z", "d1", REV_3, false); + assertEquals( + List.of(), + OntologyCheckReconciliation.decide( + Map.of(CLASS, new Checks(List.of())), List.of(elsewhere), List.of())); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java new file mode 100644 index 000000000000..9745fa4429d9 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java @@ -0,0 +1,403 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.tasks; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.openmetadata.schema.api.tests.CreateTestCase; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.TestCaseGeneratedByBinding; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TestCaseProposal; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.TaskFormSchemaRepository; + +class TestCaseSuggestionTest { + private static final String ORDERS = "svc.db.schema.orders"; + private static final String LINK = "<#E::table::svc.db.schema.orders>"; + private static final String NAME = "shapeCheck_0123456789abcdef_89abcdef"; + private static final String STATEMENT = "SELECT COUNT(*) FROM t WHERE a \\: 1"; + private static final String DIGEST = + "eaeb9c3b192276e2837faaf6e15106f0a27ac7f3c958ca51a2b6ef18fcc7e2a0"; + private static final String IDENTITY = "a".repeat(64); + + private MockedStatic entity; + private Table orders; + private boolean testExists; + + @BeforeEach + void setUp() { + orders = + new Table().withId(UUID.randomUUID()).withName("orders").withFullyQualifiedName(ORDERS); + entity = mockStatic(Entity.class); + entity + .when(() -> Entity.getEntityRepository(Entity.TASK_FORM_SCHEMA)) + .thenAnswer(i -> mock(TaskFormSchemaRepository.class)); + entity + .when(() -> Entity.getEntity(any(EntityReference.class), anyString(), any(Include.class))) + .thenAnswer(invocation -> orders); + entity + .when(() -> Entity.getEntityByName(eq(Entity.TEST_CASE), anyString(), anyString(), any())) + .thenAnswer( + invocation -> { + if (testExists) { + return new org.openmetadata.schema.tests.TestCase().withName(NAME); + } + throw EntityNotFoundException.byName(invocation.getArgument(1)); + }); + } + + @AfterEach + void tearDown() { + entity.close(); + } + + @Test + void theDigestIsTheSha256OfTheCanonicalJsonOfTheTestEntityLinkAndParameters() { + assertEquals( + DIGEST, TestCaseSuggestion.digest("tableCustomSQLQuery", LINK, parameters(STATEMENT))); + } + + @Test + void theDigestChangesWithTheStatementAndWithTheOrderOfTheParameters() { + List reversed = new java.util.ArrayList<>(parameters(STATEMENT)); + java.util.Collections.reverse(reversed); + assertEquals( + false, DIGEST.equals(TestCaseSuggestion.digest("tableCustomSQLQuery", LINK, reversed))); + assertEquals( + false, + DIGEST.equals( + TestCaseSuggestion.digest( + "tableCustomSQLQuery", LINK, parameters(STATEMENT + " AND b = 2")))); + } + + @Test + void aProposalOfTheTableTheTaskIsAboutIsAccepted() { + assertDoesNotThrow(() -> TestCaseSuggestion.require(task(proposal()))); + } + + @Test + void aTaskOfAnotherSuggestionTypeIsNotChecked() { + Task other = task(proposal()); + ((Map) other.getPayload()).put("suggestionType", "Description"); + assertDoesNotThrow(() -> TestCaseSuggestion.require(other)); + } + + @Test + void aProposalAboutAnotherEntityTypeIsRefused() { + Task task = task(proposal()); + task.getAbout().setType(Entity.DASHBOARD); + assertEquals( + "A test case suggestion must be about a table, not dashboard", + refusal(() -> TestCaseSuggestion.require(task))); + } + + @Test + void aWrongFieldPathIsRefused() { + Task task = task(proposal()); + ((Map) task.getPayload()).put("fieldPath", "description"); + assertEquals( + "Field path of a test case suggestion must be 'testCases', not 'description'", + refusal(() -> TestCaseSuggestion.require(task))); + } + + @Test + void aTestOtherThanTheCustomStatementIsRefused() { + assertEquals( + "A test case suggestion proposes the test tableCustomSQLQuery, not columnValuesToBeNotNull", + refusal( + () -> + TestCaseSuggestion.require( + task( + with(p -> p.getTestCase().setTestDefinition("columnValuesToBeNotNull")))))); + } + + @Test + void aTestOfAnotherTableOrOfAColumnIsRefused() { + assertEquals( + "A test case suggestion proposes a test of the table it is about, svc.db.schema.orders, not <#E::table::svc.db.schema.items>", + refusal( + () -> + TestCaseSuggestion.require( + task( + with( + p -> + p.getTestCase() + .setEntityLink("<#E::table::svc.db.schema.items>")))))); + assertEquals( + "A test case suggestion proposes a test of the table it is about, svc.db.schema.orders, not <#E::table::svc.db.schema.orders::columns::id>", + refusal( + () -> + TestCaseSuggestion.require( + task( + with( + p -> + p.getTestCase() + .setEntityLink( + "<#E::table::svc.db.schema.orders::columns::id>")))))); + } + + @Test + void parametersOtherThanTheFourInTheirOrderAreRefused() { + assertEquals( + "A test case suggestion proposes the parameters [sqlExpression, strategy, operator, threshold] in that order, not [sqlExpression, strategy, operator, threshold, partitionExpression]", + refusal( + () -> + TestCaseSuggestion.require( + task( + with( + p -> { + List five = + new java.util.ArrayList<>(p.getTestCase().getParameterValues()); + five.add( + new TestCaseParameterValue() + .withName("partitionExpression") + .withValue("a = 1")); + p.getTestCase().setParameterValues(five); + }))))); + } + + @Test + void aStrategyOperatorOrThresholdThatDoesNotCountViolationsIsRefused() { + String message = + "A test case suggestion counts the records in violation: strategy COUNT, operator <= and threshold 0, with a statement"; + assertEquals( + message, + refusal( + () -> + TestCaseSuggestion.require( + task( + with(p -> p.getTestCase().getParameterValues().get(1).setValue("ROWS")))))); + assertEquals( + message, + refusal( + () -> + TestCaseSuggestion.require( + task(with(p -> p.getTestCase().getParameterValues().get(3).setValue("5")))))); + } + + @Test + void aTestThatComputesPassedAndFailedRowsIsRefused() { + assertEquals( + "A test case suggestion proposes a test that does not compute passed and failed rows", + refusal( + () -> + TestCaseSuggestion.require( + task(with(p -> p.getTestCase().setComputePassedFailedRowCount(true)))))); + } + + @Test + void aDigestThatIsNotTheDigestOfTheContentIsRefused() { + String message = + refusal( + () -> + TestCaseSuggestion.require( + task( + with( + p -> + p.getTestCase() + .getParameterValues() + .get(0) + .setValue(STATEMENT + " OR 1 = 1"))))); + assertEquals( + true, + message.startsWith( + "The content digest of a test case suggestion must be that of its test definition," + + " entity link and parameter values: ")); + } + + @Test + void aProposalWithNoInspectionQueryIsRefused() { + assertEquals( + "A test case suggestion carries the inspection query", + refusal(() -> TestCaseSuggestion.require(task(with(p -> p.setInspectionQuery(null)))))); + } + + @Test + void aValueThatIsNotAProposalIsRefused() { + Task task = task(proposal()); + ((Map) task.getPayload()).put("suggestedValue", "not json"); + assertEquals( + "Suggested value is not a test case proposal", + refusal(() -> TestCaseSuggestion.require(task))); + } + + @Test + void aKeyTheSuggestionPayloadDoesNotDeclareIsRefusedWhenFiling() { + Task task = task(proposal()); + ((Map) task.getPayload()).put("comment", "hello"); + String message = refusal(() -> TestCaseSuggestion.require(task)); + assertEquals( + true, + message.startsWith("A test case suggestion carries only the keys") + && message.endsWith("not allowed: comment")); + } + + @Test + void aResolutionCannotChangeTheSuggestionTypeToOrFromATestCase() { + Task task = task(proposal()); + BadRequestException toDescription = + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + task, Map.of("suggestionType", "Description"))); + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TestCase: the task is 'TestCase', the resolution says 'Description'", + toDescription.getMessage()); + Task description = task(proposal()); + ((Map) description.getPayload()).put("suggestionType", "Description"); + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TestCase: the task is 'Description', the resolution says 'TestCase'", + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + description, Map.of("suggestionType", "TestCase"))) + .getMessage()); + } + + @Test + void aResolutionCannotAddAKeyToATestCaseSuggestion() { + BadRequestException e = + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireNoNewKeys( + task(proposal()), Map.of("comment", "x"), null)); + assertEquals(true, e.getMessage().startsWith("A test case suggestion carries only the keys")); + } + + @Test + void anApprovalsCommentNamesTheTestAndItsTableAndNeverTheNewValue() { + Task task = task(proposal()); + assertEquals( + Optional.of("Created test case " + NAME + " on table " + ORDERS), + TaskWorkflowHandler.resolutionComment(task, true, null, null)); + assertEquals( + Optional.of("Created test case " + NAME + " on table " + ORDERS), + TaskWorkflowHandler.resolutionComment(task, true, null, "something the approver typed")); + } + + @Test + void anApprovalsCommentSaysSoWhenTheTableHasTheTest() { + testExists = true; + assertEquals( + Optional.of("Test case already exists " + NAME + " on table " + ORDERS), + TaskWorkflowHandler.resolutionComment(task(proposal()), true, null, null)); + } + + @Test + void aRejectionLeavesNoComment() { + assertEquals( + Optional.empty(), + TaskWorkflowHandler.resolutionComment(task(proposal()), false, null, null)); + } + + @Test + void theTestToCreateIsTheProposalWithItsInspectionQueryAndWhereItComesFrom() { + TestCaseProposal proposal = proposal(); + CreateTestCase create = proposal.getTestCase(); + assertEquals("tableCustomSQLQuery", create.getTestDefinition()); + assertEquals(LINK, create.getEntityLink()); + assertEquals("SELECT k FROM t", proposal.getInspectionQuery()); + assertEquals(DIGEST, proposal.getGeneratedBy().getContentDigest()); + assertEquals(IDENTITY, proposal.getGeneratedBy().getIdentity()); + } + + private static String refusal(final Runnable filing) { + return assertThrows(BadRequestException.class, filing::run).getMessage(); + } + + private static List parameters(final String statement) { + return List.of( + new TestCaseParameterValue().withName("sqlExpression").withValue(statement), + new TestCaseParameterValue().withName("strategy").withValue("COUNT"), + new TestCaseParameterValue().withName("operator").withValue("<="), + new TestCaseParameterValue().withName("threshold").withValue("0")); + } + + private static TestCaseProposal proposal() { + return new TestCaseProposal() + .withTestCase( + new CreateTestCase() + .withName(NAME) + .withTestDefinition("tableCustomSQLQuery") + .withEntityLink(LINK) + .withParameterValues(new java.util.ArrayList<>(parameters(STATEMENT)))) + .withInspectionQuery("SELECT k FROM t") + .withGeneratedBy( + new TestCaseGeneratedBy() + .withIdentity(IDENTITY) + .withShape( + new EntityReference().withId(UUID.randomUUID()).withType("ontologyShape")) + .withConstraintId("c1") + .withPart("minCount") + .withClass( + new EntityReference().withId(UUID.randomUUID()).withType("ontologyConcept")) + .withReadBindings( + List.of( + new TestCaseGeneratedByBinding() + .withConceptId(UUID.randomUUID()) + .withAssetId(UUID.randomUUID()) + .withRevision(3L))) + .withContentDigest(DIGEST)); + } + + private static TestCaseProposal with(final java.util.function.Consumer change) { + TestCaseProposal proposal = proposal(); + change.accept(proposal); + return proposal; + } + + private Task task(final TestCaseProposal proposal) { + Map payload = new LinkedHashMap<>(); + payload.put("suggestionType", "TestCase"); + payload.put("fieldPath", "testCases"); + payload.put("suggestedValue", JsonUtils.pojoToJson(proposal)); + return new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withAbout( + new EntityReference() + .withId(orders.getId()) + .withType(Entity.TABLE) + .withFullyQualifiedName(ORDERS)) + .withPayload(payload); + } +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json index 7b71568ec90f..e2a262eeb1a0 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json @@ -67,6 +67,38 @@ "required": ["conceptId", "assetId", "revision"], "additionalProperties": false }, + "proposalState": { + "description": "Whether a check has reached its table as a test case. `none`: no proposal exists. `proposed`: a suggestion task is open. `rejected`: a person rejected the suggestion of the current content. `accepted`: the test case exists.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckProposalState", + "enum": ["none", "proposed", "rejected", "accepted"] + }, + "proposal": { + "description": "How a check stands as a test on its table. A reference is left out when the caller may not view the task or the test case.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckProposal", + "properties": { + "state": { "$ref": "#/definitions/proposalState" }, + "task": { + "description": "The suggestion task. Present for `proposed` and `rejected` when the caller may view it.", + "$ref": "../../type/entityReference.json" + }, + "testCase": { + "description": "The test case. Present for `accepted` when the caller may view it.", + "$ref": "../../type/entityReference.json" + }, + "latestResultStatus": { + "description": "Status of the latest result of the test case. Absent when it has no result or the caller may not view the test case.", + "$ref": "../../tests/basic.json#/definitions/testCaseStatus" + }, + "latestResultTimestamp": { + "description": "Time of the latest result of the test case.", + "$ref": "../../type/basic.json#/definitions/timestamp" + } + }, + "required": ["state"], + "additionalProperties": false + }, "check": { "description": "One data quality test on one table: the test `tableCustomSQLQuery` with a statement written for the part. `testDefinition`, `entityLink` and `parameterValues` are what a request to create a test case takes. The result of the test is 0 violations exactly when every record of the class satisfies the part.", "type": "object", @@ -110,6 +142,10 @@ "type": "array", "items": { "$ref": "#/definitions/readBinding" }, "default": [] + }, + "proposal": { + "description": "How the check stands as a test on its table.", + "$ref": "#/definitions/proposal" } }, "required": [ diff --git a/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json b/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json index 191c33d82b0d..30c423d142dd 100644 --- a/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json +++ b/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json @@ -7,6 +7,70 @@ "javaType": "org.openmetadata.schema.tests.TestCase", "javaInterfaces": ["org.openmetadata.schema.EntityInterface"], "definitions": { + "generatedByBinding": { + "type": "object", + "javaType": "org.openmetadata.schema.tests.TestCaseGeneratedByBinding", + "description": "One table binding that the statement of a generated test was built from, with the binding revision of its class.", + "properties": { + "conceptId": { + "description": "Id of the class that binds the table.", + "$ref": "../type/basic.json#/definitions/uuid" + }, + "assetId": { + "description": "Id of the bound table.", + "$ref": "../type/basic.json#/definitions/uuid" + }, + "revision": { + "description": "Revision of the bindings of the class when the test was generated.", + "type": "integer", + "minimum": 0, + "existingJavaType": "java.lang.Long" + } + }, + "required": ["conceptId", "assetId", "revision"], + "additionalProperties": false + }, + "generatedBy": { + "type": "object", + "javaType": "org.openmetadata.schema.tests.TestCaseGeneratedBy", + "description": "Where a generated test comes from: the part of a shape constraint it checks on one table. Only a suggestion that creates the test and the server's own reconcile set it, and the test definition, the entity link and the parameter values of such a test cannot be edited.", + "properties": { + "identity": { + "description": "Lowercase hex SHA-256 that names the check. It holds no test definition and no value of the constraint, so a changed bound keeps it.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "shape": { + "description": "The shape whose constraint the test checks.", + "$ref": "../type/entityReference.json" + }, + "constraintId": { + "description": "Id of the constraint within its shape.", + "type": "string" + }, + "part": { + "description": "The part of the constraint the test checks: minCount, maxCount, class, datatype, range, in or pattern.", + "type": "string" + }, + "class": { + "description": "The class whose records the test counts violations of.", + "$ref": "../type/entityReference.json" + }, + "readBindings": { + "description": "Every table binding the statement was built from.", + "type": "array", + "items": { "$ref": "#/definitions/generatedByBinding" }, + "default": [] + }, + "contentDigest": { + "description": "Lowercase hex SHA-256 of the canonical JSON of the test definition, the entity link and the parameter values.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + }, + "required": ["identity", "shape", "constraintId", "part", "class", "readBindings", "contentDigest"], + "additionalProperties": false + }, "testCaseParameterValue": { "type": "object", "javaType": "org.openmetadata.schema.tests.TestCaseParameterValue", @@ -148,6 +212,10 @@ "description": "SQL query to retrieve the failed rows for this test case.", "$ref": "../type/basic.json#/definitions/sqlQuery" }, + "generatedBy": { + "description": "Present when the server generated this test from a shape constraint. A create or a patch that sends it is refused, and so is a change to the test definition, the entity link or the parameter values of such a test.", + "$ref": "#/definitions/generatedBy" + }, "domains" : { "description": "Domains the test case belongs to. When not set, the test case inherits the domain from the table it belongs to.", "$ref": "../type/entityReferenceList.json" diff --git a/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json b/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json index 60cec9b9ee71..a13c9166ee8e 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json @@ -9,10 +9,10 @@ "suggestionType": { "description": "Type of suggestion.", "type": "string", - "enum": ["Description", "Tag", "Owner", "Tier", "Domain", "CustomProperty", "TableConstraint"] + "enum": ["Description", "Tag", "Owner", "Tier", "Domain", "CustomProperty", "TableConstraint", "TestCase"] }, "fieldPath": { - "description": "Path to the property being updated. For a Description or Tag suggestion it is written as .[....]., for example 'columns.customer_id.description', or 'description' / 'tags' alone for the entity itself. A TableConstraint suggestion's path is 'tableConstraints'.", + "description": "Path to the property being updated. For a Description or Tag suggestion it is written as .[....]., for example 'columns.customer_id.description', or 'description' / 'tags' alone for the entity itself. A TableConstraint suggestion's path is 'tableConstraints'. A TestCase suggestion's path is 'testCases'.", "type": "string" }, "currentValue": { @@ -20,7 +20,7 @@ "type": "string" }, "suggestedValue": { - "description": "Suggested new value for the field. For a TableConstraint suggestion it is one tableConstraint object written as JSON: its constraintType (PRIMARY_KEY, UNIQUE or FOREIGN_KEY), its columns, and for a foreign key its referredColumns as full column names and its relationshipType.", + "description": "Suggested new value for the field. For a TableConstraint suggestion it is one tableConstraint object written as JSON: its constraintType (PRIMARY_KEY, UNIQUE or FOREIGN_KEY), its columns, and for a foreign key its referredColumns as full column names and its relationshipType. For a TestCase suggestion it is a testCaseProposal written as JSON: the test case to create, with the statement that lists the records it counts and where it comes from.", "type": "string" }, "confidence": { diff --git a/openmetadata-spec/src/main/resources/json/schema/type/testCaseProposal.json b/openmetadata-spec/src/main/resources/json/schema/type/testCaseProposal.json new file mode 100644 index 000000000000..cd64efcfa04e --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/testCaseProposal.json @@ -0,0 +1,24 @@ +{ + "$id": "https://open-metadata.org/schema/type/testCaseProposal.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "TestCaseProposal", + "description": "The suggested value of a TestCase suggestion: the test case to create, the statement that lists the records it counts, and where it comes from. Approving the suggestion creates the test case with those values and nothing else.", + "type": "object", + "javaType": "org.openmetadata.schema.type.TestCaseProposal", + "properties": { + "testCase": { + "description": "The test case to create, in the shape a request to create a test case takes.", + "$ref": "../api/tests/createTestCase.json" + }, + "inspectionQuery": { + "description": "The statement that lists the keys of the records the test counts, for a person to read. It is stored on the test case as it is, and no test runner executes it.", + "$ref": "basic.json#/definitions/sqlQuery" + }, + "generatedBy": { + "description": "Where the test comes from. It carries the identity of the check, the table bindings it was built from and the digest of its content.", + "$ref": "../tests/testCase.json#/definitions/generatedBy" + } + }, + "required": ["testCase", "inspectionQuery", "generatedBy"], + "additionalProperties": false +} From 7ff8a6c3e2bf9b0b6458c25b726b44ee1ac3ddf7 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 20:40:34 -0800 Subject: [PATCH 153/203] A check's proposal state is readable per caller, and the proposal flow is covered end to end --- .../it/tests/OntologyShapeCheckAnswerIT.java | 4 + .../tests/OntologyShapeCheckProposalIT.java | 589 ++++++++++++++++++ .../it/tests/OntologyShapeCheckRightsIT.java | 7 +- .../ontology/OntologyCheckProposals.java | 172 +++++ .../ontology/OntologyStatementService.java | 13 +- .../ui/src/rest/suggestionsAPI.test.ts | 28 + 6 files changed, 811 insertions(+), 2 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java index e67e8ad44adc..fb4fa031e180 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java @@ -75,6 +75,8 @@ import org.openmetadata.schema.api.data.OntologyShapeCheck; import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposal; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; import org.openmetadata.schema.api.data.OntologyShapeCheckReason; import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.api.data.OntologyShapePart; @@ -151,6 +153,8 @@ OntologyShapeCheck test(final String column, final String count) { .withTable(reference(fixture, "accounts")) .withColumns(List.of(List.of(column))) .withReadBindings(List.of(binding())) + .withProposal( + new OntologyShapeCheckProposal().withState(OntologyShapeCheckProposalState.NONE)) .withTestDefinition(CUSTOM_SQL) .withEntityLink(TABLE_LINK.formatted(tableName())) .withParameterValues(countParameters(count)) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java new file mode 100644 index 000000000000..1c9636276599 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java @@ -0,0 +1,589 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertStatus; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declareKey; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.NOT_EQUALS; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.ActivateOntologyRelease; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * A shape check reaches its table as a suggestion task that a person with the right accepts, and + * the tests and the open suggestions follow the active release (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckProposalIT extends BaseOntologyApprovalIT { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + private static final long WAIT_SECONDS = 120; + + private static final Shape ACCOUNTS = + mapping( + "accounts", + List.of(table("accounts", List.of(integer("id"), text("email"), integer("age")))), + List.of("Account"), + List.of( + data("accountNo", "Account"), + data("accountEmail", "Account"), + data("accountAge", "Account")), + identityTable( + "Account", + "accounts", + List.of("id"), + null, + bound("accountNo", "id"), + bound("accountEmail", "email"), + bound("accountAge", "age"))); + + private static org.openmetadata.schema.type.OntologyShapeConstraint listed( + final OntologyShapeFixture fixture) { + return on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b")); + } + + private static org.openmetadata.schema.type.OntologyShapeConstraint ranged( + final OntologyShapeFixture fixture, final String upper) { + return on(fixture, "age-range", "accountAge") + .withDatatypeIri(URI.create(XSD + "integer")) + .withMinInclusive(limit("0")) + .withMaxInclusive(limit(upper)); + } + + private static void settle() { + try { + assertTrue( + OntologyCheckReconcileQueue.instance().awaitIdle(WAIT_SECONDS, TimeUnit.SECONDS), + "the reconcile did not finish"); + } catch (final InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + /** Captures the working draft, approves the release and makes it the active one. */ + private static void release(final TestNamespace ns, final Ontology ontology) { + final OntologyRelease release = capture(ontology); + final var task = submit(ns, Entity.ONTOLOGY_RELEASE, release.getFullyQualifiedName()); + SdkClients.user1Client() + .tasks() + .resolve(task.getId().toString(), decision(TaskResolutionType.Approved)); + final long revision = admin().ontologies().state(ontology.getId()).getActivationRevision(); + admin() + .ontologies() + .activate( + ontology.getId(), + new ActivateOntologyRelease() + .withReleaseId(release.getId()) + .withExpectedActivationRevision(revision)); + settle(); + } + + private static List checks(final OntologyConcept account) { + final OntologyShapeChecks answer = + admin() + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyConcepts/" + + account.getId() + + "/shapeChecks?version=" + + RELEASE.value(), + null, + OntologyShapeChecks.class); + final List found = new ArrayList<>(); + for (final OntologyCheckedShape shape : answer.getShapes()) { + for (final OntologyCheckedConstraint constraint : shape.getConstraints()) { + for (final OntologyCheckedPart part : constraint.getParts()) { + if (part.getChecks() != null) { + found.addAll(part.getChecks()); + } + } + } + } + return found; + } + + private static OntologyShapeCheck checkOf( + final List checks, final String column) { + return checks.stream() + .filter(check -> check.getColumns().getFirst().getFirst().equals(column)) + .findFirst() + .orElseThrow(); + } + + private static JsonNode testsOf(final String tableFqn) { + return JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testCases?entityLink=" + + java.net.URLEncoder.encode( + "<#E::table::" + tableFqn + ">", java.nio.charset.StandardCharsets.UTF_8) + + "&limit=100&fields=testSuite,testDefinition,inspectionQuery,generatedBy", + null)); + } + + private static int generatedTests(final String tableFqn) { + int count = 0; + for (final JsonNode test : testsOf(tableFqn).path("data")) { + if (test.has("generatedBy")) { + count++; + } + } + return count; + } + + private static OntologyShapeCheckProposalState stateOf( + final OntologyConcept account, final String column) { + return checkOf(checks(account), column).getProposal().getState(); + } + + @Test + void activationProposes(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "proposals"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + + final OntologyConcept account = fixture.type("Account"); + final List found = checks(account); + assertEquals(2, found.size()); + for (final OntologyShapeCheck check : found) { + assertEquals(OntologyShapeCheckProposalState.PROPOSED, check.getProposal().getState()); + final Task task = admin().tasks().get(check.getProposal().getTask().getId().toString()); + assertEquals(TaskEntityStatus.Open, task.getStatus()); + } + assertEquals(0, generatedTests(fixture.table("accounts").getFullyQualifiedName())); + } + } + + @Test + void acceptCreatesTest(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "accepted"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + final OntologyShapeCheck proposed = checkOf(checks(account), "email"); + + admin() + .tasks() + .resolve( + proposed.getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + final OntologyShapeCheck accepted = checkOf(checks(account), "email"); + assertEquals(OntologyShapeCheckProposalState.ACCEPTED, accepted.getProposal().getState()); + assertEquals(1, generatedTests(tableFqn)); + final JsonNode test = testsOf(tableFqn).path("data").get(0); + assertEquals(proposed.getInspectionQuery(), test.path("inspectionQuery").asText()); + assertEquals("tableCustomSQLQuery", test.path("testDefinition").path("name").asText()); + assertEquals(4, test.path("parameterValues").size()); + assertEquals( + proposed.getParameterValues().getFirst().getValue(), + test.path("parameterValues").get(0).path("value").asText()); + assertEquals(proposed.getIdentity(), test.path("generatedBy").path("identity").asText()); + final String suiteId = test.path("testSuite").path("id").asText(); + final JsonNode suite = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testSuites/" + suiteId + "?fields=pipelines", + null)); + assertEquals(1, suite.path("pipelines").size()); + final JsonNode pipeline = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/services/ingestionPipelines/" + + suite.path("pipelines").get(0).path("id").asText(), + null)); + assertEquals("0 0 * * *", pipeline.path("airflowConfig").path("scheduleInterval").asText()); + } + } + + @Test + void acceptNeedsRight(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "refused"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final OntologyShapeCheck proposed = checkOf(checks(account), "email"); + final String taskId = proposed.getProposal().getTask().getId().toString(); + + assertRefusedWithout( + () -> + SdkClients.dataConsumerClient() + .tasks() + .resolve( + taskId, new ResolveTask().withResolutionType(TaskResolutionType.Approved))); + + assertEquals(0, generatedTests(fixture.table("accounts").getFullyQualifiedName())); + assertEquals(TaskEntityStatus.Open, admin().tasks().get(taskId).getStatus()); + } + } + + @Test + void rejectedStays(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "rejected"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String taskId = + checkOf(checks(account), "email").getProposal().getTask().getId().toString(); + admin() + .tasks() + .resolve(taskId, new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + assertEquals(OntologyShapeCheckProposalState.REJECTED, stateOf(account, "email")); + final int before = taskCount(account); + + release(ns, ontology); + + assertEquals(OntologyShapeCheckProposalState.REJECTED, stateOf(account, "email")); + assertEquals(before, taskCount(account)); + assertEquals(0, generatedTests(fixture.table("accounts").getFullyQualifiedName())); + } + } + + private static void assertRefusedWithout(final Runnable resolve) { + final int status = + org.junit.jupiter.api.Assertions.assertThrows( + org.openmetadata.sdk.exceptions.OpenMetadataException.class, resolve::run) + .getStatusCode(); + assertTrue(status == 403 || status == 404, "status " + status); + } + + private static int taskCount(final OntologyConcept account) { + final JsonNode all = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString(HttpMethod.GET, "/v1/tasks?limit=1000&fields=payload", null)); + int count = 0; + for (final JsonNode task : all.path("data")) { + if ("TestCase".equals(task.path("payload").path("suggestionType").asText()) + && task.path("payload") + .path("suggestedValue") + .asText() + .contains(account.getId().toString())) { + count++; + } + } + return count; + } + + @Test + void boundChange(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "bound"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare( + ontology, + fixture, + "AccountShape", + "Account", + listed(fixture), + ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + final OntologyShapeCheck listed = checkOf(checks(account), "email"); + final OntologyShapeCheck ranged = checkOf(checks(account), "age"); + admin() + .tasks() + .resolve( + ranged.getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final String testId = + checkOf(checks(account), "age").getProposal().getTestCase().getId().toString(); + final String openTask = listed.getProposal().getTask().getId().toString(); + + admin() + .ontologyShapes() + .update( + shape.getId(), + admin() + .ontologyShapes() + .get(shape.getId().toString()) + .withConstraints( + List.of( + on(fixture, "email-listed", "accountEmail") + .withIn(literals("a", "b", "c")), + ranged(fixture, "100")))); + release(ns, ontology); + + final OntologyShapeCheck after = checkOf(checks(account), "age"); + assertEquals(testId, after.getProposal().getTestCase().getId().toString()); + assertEquals(1, generatedTests(tableFqn)); + final JsonNode test = testsOf(tableFqn).path("data").get(0); + assertTrue(test.path("parameterValues").get(0).path("value").asText().contains("100")); + assertEquals( + after.getParameterValues().getFirst().getValue(), + test.path("parameterValues").get(0).path("value").asText()); + final OntologyShapeCheck replaced = checkOf(checks(account), "email"); + assertEquals(openTask, replaced.getProposal().getTask().getId().toString()); + final JsonNode value = + JsonUtils.readTree( + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, "/v1/tasks/" + openTask + "?fields=payload", null)) + .path("payload") + .path("suggestedValue") + .asText()); + assertTrue( + value + .path("testCase") + .path("parameterValues") + .get(0) + .path("value") + .asText() + .contains("'c'")); + } + } + + @Test + void constraintGone(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "removed"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare( + ontology, + fixture, + "AccountShape", + "Account", + listed(fixture), + ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + admin() + .tasks() + .resolve( + checkOf(checks(account), "age").getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final String open = + checkOf(checks(account), "email").getProposal().getTask().getId().toString(); + assertEquals(1, generatedTests(tableFqn)); + + admin() + .ontologyShapes() + .update( + shape.getId(), + admin().ontologyShapes().get(shape.getId().toString()).withConstraints(List.of())); + release(ns, ontology); + + assertEquals(0, generatedTests(tableFqn)); + assertEquals(TaskEntityStatus.Cancelled, admin().tasks().get(open).getStatus()); + assertEquals(0, checks(account).size()); + } + } + + @Test + void readOnly(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "readonly"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + admin() + .tasks() + .resolve( + checkOf(checks(account), "email").getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final String testId = + checkOf(checks(account), "email").getProposal().getTestCase().getId().toString(); + final String path = "/v1/dataQuality/testCases/" + testId; + + assertStatus( + 400, + () -> + admin() + .getHttpClient() + .execute( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"replace\",\"path\":\"/parameterValues/0/value\"," + + "\"value\":\"SELECT 0\"}]"), + org.openmetadata.schema.tests.TestCase.class)); + + final org.openmetadata.schema.tests.TestCase described = + admin() + .getHttpClient() + .execute( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/description\",\"value\":\"looked at\"}]"), + org.openmetadata.schema.tests.TestCase.class); + assertEquals("looked at", described.getDescription()); + } + } + + @Test + void secondRunIdle(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "idempotent"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + admin() + .tasks() + .resolve( + checkOf(checks(account), "age").getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final OntologyCheckReconcileQueue queue = OntologyCheckReconcileQueue.instance(); + queue.afterActivation(ontology.getId(), "admin"); + settle(); + final int written = queue.writesMade(ontology.getId()); + final String before = JsonUtils.pojoToJson(checks(account)); + + queue.afterActivation(ontology.getId(), "admin"); + settle(); + + assertEquals(written, queue.writesMade(ontology.getId())); + assertEquals(before, JsonUtils.pojoToJson(checks(account))); + assertNotNull(checkOf(checks(account), "age").getProposal().getTestCase()); + assertNull(checkOf(checks(account), "age").getProposal().getTask()); + assertEquals(OntologyShapeCheckProposalState.PROPOSED, stateOf(account, "email")); + } + } + + @Test + void filterChange(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "filter"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + admin() + .tasks() + .resolve( + checkOf(checks(account), "email").getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final OntologyShapeCheck before = checkOf(checks(account), "email"); + + final BindingSpec spec = fixture.shape().bindings().getFirst(); + fixture.bind( + new BindingSpec( + spec.type(), + spec.table(), + spec.role(), + spec.key(), + new FilterSpec("email", NOT_EQUALS, "zz"), + spec.columns())); + settle(); + + final OntologyShapeCheck after = checkOf(checks(account), "email"); + assertEquals( + before.getProposal().getTestCase().getId(), after.getProposal().getTestCase().getId()); + assertNotEquals( + before.getParameterValues().getFirst().getValue(), + after.getParameterValues().getFirst().getValue()); + final JsonNode test = + testsOf(fixture.table("accounts").getFullyQualifiedName()).path("data").get(0); + assertEquals( + after.getParameterValues().getFirst().getValue(), + test.path("parameterValues").get(0).path("value").asText()); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java index 0a8972522619..cb2066b78194 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java @@ -57,6 +57,8 @@ import org.openmetadata.schema.api.data.OntologyCheckedShape; import org.openmetadata.schema.api.data.OntologyShapeCheck; import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposal; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.api.data.OntologyShapePart; import org.openmetadata.schema.api.data.OntologyStatementVersion; @@ -193,7 +195,10 @@ OntologyCheckedPart checked( "<#E::table::" + fixture.table(tableName).getFullyQualifiedName() + ">") .withParameterValues(countParameters(count)) .withInspectionQuery(keyList(count)) - .withReadBindings(read))); + .withReadBindings(read) + .withProposal( + new OntologyShapeCheckProposal() + .withState(OntologyShapeCheckProposalState.NONE)))); } List channelChecked() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java new file mode 100644 index 000000000000..6f2bab1fa99c --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java @@ -0,0 +1,172 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposal; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.type.TestCaseResult; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.TaskRepository; +import org.openmetadata.service.jdbi3.TestCaseRepository; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.tasks.TestCaseSuggestion; + +/** + * Sets how each check of a class stands as a test on its table: accepted when a test generated from + * it exists, proposed while a suggestion is open, rejected when the latest one was, else none. A + * reference is left out when the caller may not view the task or the test case, so the state alone + * never reveals what the caller cannot see (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + */ +final class OntologyCheckProposals { + private final CollectionDAO dao; + private final OntologyBindingAccess catalog; + + OntologyCheckProposals(final CollectionDAO dao, final OntologyBindingAccess catalog) { + this.dao = dao; + this.catalog = catalog; + } + + /** What exists for the checks of one class, keyed by check identity. */ + private record Held(Map tests, Map tasks) {} + + void mark(final Access access, final UUID classId, final List shapes) { + final Held held = held(classId); + for (final OntologyCheckedShape shape : shapes) { + for (final OntologyCheckedConstraint constraint : listOrEmpty(shape.getConstraints())) { + for (final OntologyCheckedPart part : listOrEmpty(constraint.getParts())) { + for (final OntologyShapeCheck check : listOrEmpty(part.getChecks())) { + check.setProposal(proposal(access, held, check.getIdentity())); + } + } + } + } + } + + private Held held(final UUID classId) { + final TestCaseRepository tests = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final Map liveTests = new HashMap<>(); + for (final String id : dao.testCaseDAO().findGeneratedIds()) { + final TestCase test = + Entity.getEntity(Entity.TEST_CASE, UUID.fromString(id), "", Include.ALL); + final TestCaseGeneratedBy by = test.getGeneratedBy(); + if (by != null + && classId.equals(by.getClass_().getId()) + && !Boolean.TRUE.equals(test.getDeleted())) { + liveTests.put(by.getIdentity(), test); + } + } + final Map byIdentity = new HashMap<>(); + for (final String id : dao.taskDAO().findTestCaseSuggestionIds()) { + final Task task = Entity.getEntity(Entity.TASK, UUID.fromString(id), "", Include.ALL); + final TestCaseGeneratedBy by = + TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload())).getGeneratedBy(); + if (classId.equals(by.getClass_().getId())) { + byIdentity.merge(by.getIdentity(), task, OntologyCheckProposals::stronger); + } + } + return new Held(liveTests, byIdentity); + } + + /** An open task outranks a closed one, and a later one an earlier one. */ + private static Task stronger(final Task left, final Task right) { + final boolean leftOpen = open(left); + final boolean rightOpen = open(right); + if (leftOpen != rightOpen) { + return leftOpen ? left : right; + } + return left.getUpdatedAt() >= right.getUpdatedAt() ? left : right; + } + + private static boolean open(final Task task) { + return task.getStatus() == TaskEntityStatus.Open + || task.getStatus() == TaskEntityStatus.InProgress + || task.getStatus() == TaskEntityStatus.Pending; + } + + private OntologyShapeCheckProposal proposal( + final Access access, final Held held, final String identity) { + final TestCase test = held.tests().get(identity); + if (test != null) { + return accepted(access, test); + } + final Task task = held.tasks().get(identity); + if (task != null && open(task)) { + return withTask(access, task, OntologyShapeCheckProposalState.PROPOSED); + } + if (task != null && task.getStatus() == TaskEntityStatus.Rejected) { + return withTask(access, task, OntologyShapeCheckProposalState.REJECTED); + } + return new OntologyShapeCheckProposal().withState(OntologyShapeCheckProposalState.NONE); + } + + private OntologyShapeCheckProposal withTask( + final Access access, final Task task, final OntologyShapeCheckProposalState state) { + final OntologyShapeCheckProposal proposal = new OntologyShapeCheckProposal().withState(state); + if (mayView(access, Entity.TASK, task.getId())) { + proposal.setTask(task.getEntityReference()); + } + return proposal; + } + + private OntologyShapeCheckProposal accepted(final Access access, final TestCase test) { + final OntologyShapeCheckProposal proposal = + new OntologyShapeCheckProposal().withState(OntologyShapeCheckProposalState.ACCEPTED); + if (!mayView(access, Entity.TEST_CASE, test.getId())) { + return proposal; + } + proposal.setTestCase(test.getEntityReference()); + final TestCaseResult latest = + Entity.getEntity( + Entity.TEST_CASE, test.getId(), "testCaseResult", Include.NON_DELETED) + .getTestCaseResult(); + if (latest != null) { + proposal.setLatestResultStatus(latest.getTestCaseStatus()); + proposal.setLatestResultTimestamp(latest.getTimestamp()); + } + return proposal; + } + + private boolean mayView(final Access access, final String type, final UUID id) { + try { + final EntityInterface entity = + catalog.authorized(access, type, id, MetadataOperation.VIEW_BASIC); + return entity != null; + } catch (final AuthorizationException | EntityNotFoundException denied) { + return false; + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java index 96afabd5a46d..042e9f88f9ba 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java @@ -29,6 +29,7 @@ import java.util.stream.Stream; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.api.data.OntologyAggregateStatementRequest; +import org.openmetadata.schema.api.data.OntologyCheckedShape; import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; import org.openmetadata.schema.api.data.OntologyFindStatementRequest; import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; @@ -105,6 +106,7 @@ public interface DraftGate { private final OntologyBindingAccess catalog; private final OntologyMappingReader mapping; private final OntologyShapeCheckReader shapes; + private final OntologyCheckProposals proposals; private final DraftGate draftGate; public OntologyStatementService( @@ -118,6 +120,7 @@ public OntologyStatementService( this.catalog = new OntologyBindingAccess(authorizer, repositories); this.mapping = new OntologyMappingReader(store, catalog); this.shapes = new OntologyShapeCheckReader(store, catalog); + this.proposals = new OntologyCheckProposals(dao, catalog); this.draftGate = draftGate; } @@ -271,10 +274,18 @@ public OntologyShapeChecks shapeChecks( .withConceptId(subject.id()) .withClassIri(subject.iri()) .withVersion(subject.version().read()) - .withShapes(OntologyShapeCheckAnswer.shapes(read.facts(), read.shapes(), read.hidden())); + .withShapes(marked(access, subject.id(), read)); } } + private List marked( + final Access access, final UUID classId, final Read read) { + final List answer = + OntologyShapeCheckAnswer.shapes(read.facts(), read.shapes(), read.hidden()); + proposals.mark(access, classId, answer); + return answer; + } + private OntologyStatementPlan count(final Access access, final Subject subject) { final Bindings bindings = mapping.bindings(List.of(subject.id()), List.of()); final Tables tables = mapping.tables(access, bindings.rows()); diff --git a/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts b/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts index 9fa00ae6af95..3ae1d8db9afd 100644 --- a/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/rest/suggestionsAPI.test.ts @@ -332,6 +332,34 @@ describe('suggestionsAPI', () => { }, }); + it('leaves a proposed test case out of the list and out of its total', async () => { + const testCaseTask = { + ...constraintTask, + id: 'task-test-case', + payload: { + fieldPath: 'testCases', + suggestionType: 'TestCase', + suggestedValue: '{"testCase":{"name":"shapeCheck_1"}}', + }, + }; + (APIClient.get as jest.Mock).mockResolvedValue({ + data: { + data: [ + testCaseTask, + makeTask('task-desc', 'columns.col_1.description', 'Description'), + ], + paging: { total: 2 }, + }, + }); + + const result = await getSuggestionsList(); + + expect(result.data.map((s) => [s.id, s.type])).toEqual([ + ['task-desc', SuggestionType.SuggestDescription], + ]); + expect(result.paging).toEqual({ total: 1 }); + }); + it('lists only the description and the tag suggestion, with a total of 2', async () => { (APIClient.get as jest.Mock).mockResolvedValue(mixed()); From 7ae456b6570f4979d525230fcbb8f14b87b965c0 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 21:15:25 -0800 Subject: [PATCH 154/203] Read the proposals of a class by its id, and keep the compile's read counts free of the proposals --- .../it/tests/OntologyShapeCheckAnswerIT.java | 5 +++- .../OntologyShapeCheckDefinitionRightsIT.java | 9 ++++--- .../it/tests/OntologyShapeCheckFixtures.java | 17 +++++++++++++ .../it/tests/OntologyShapeCheckReadsIT.java | 24 +++++++++++++++++++ .../it/tests/OntologyShapeCheckRightsIT.java | 5 ++-- .../openmetadata/service/jdbi3/FeedDAOs.java | 15 ++++++++++++ .../service/jdbi3/TimeSeriesDAOs.java | 12 ++++++++++ .../ontology/OntologyCheckProposals.java | 10 ++++---- 8 files changed, 86 insertions(+), 11 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java index fb4fa031e180..a0b60fd33321 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java @@ -574,7 +574,10 @@ void anAnswerReadsTheVersionThatItsRequestNames(final TestNamespace ns) { assertEquals( List.of(released.getId()), byDefault.getShapes().stream().map(OntologyCheckedShape::getId).toList()); - assertEquals(byDefault, checks(admin(), fixture.type("Member"), RELEASE)); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(byDefault), + OntologyShapeCheckFixtures.withoutProposals( + checks(admin(), fixture.type("Member"), RELEASE))); assertEquals(DRAFT, drafted.getVersion().getKind()); assertEquals( List.of("DraftedShape", "ReleasedShape"), diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java index 5407b9df2921..d4aa7cb70115 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java @@ -66,7 +66,6 @@ import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.OntologyShapeSeverity; -import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.service.Entity; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; @@ -216,7 +215,9 @@ void assertNamesNothingOf(final String body, final String property) { } private static void assertAnswer(final OntologyShapeChecks expected, final String body) { - assertEquals(JsonUtils.readTree(JsonUtils.pojoToJson(expected)), JsonUtils.readTree(body)); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(expected), + OntologyShapeCheckFixtures.withoutProposals(body)); } private static void owns(final OpenMetadataClient reader, final OntologyShape shape) { @@ -452,7 +453,9 @@ void aReaderWhoMayViewEverythingReadsTheBytesAnAdministratorReads(final TestName for (final OntologyStatementVersion version : VERSIONS) { final String body = answer(reader, scene.order(), version); - assertEquals(answer(admin(), scene.order(), version), body); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(answer(admin(), scene.order(), version)), + OntologyShapeCheckFixtures.withoutProposals(body)); assertTrue(body.contains(scene.orders().getId().toString()), body); assertTrue(body.contains(scene.lines().getId().toString()), body); PROPERTIES.forEach( diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java index 7dcabf63afc5..ad05386b82de 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java @@ -16,6 +16,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; @@ -54,6 +56,7 @@ import org.openmetadata.schema.type.OntologyShapeSeverity; import org.openmetadata.schema.type.OntologyShapeValue; import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; @@ -369,6 +372,20 @@ static OntologyShapeChecks checks( .execute(HttpMethod.GET, path(type, version), null, OntologyShapeChecks.class); } + /** + * The body of an answer without the {@code proposal} of each check. A proposal follows the + * reconcile that an activation starts, and these answers are compared for what the compile says. + */ + static JsonNode withoutProposals(final String body) { + final JsonNode tree = JsonUtils.readTree(body); + tree.findParents("proposal").forEach(parent -> ((ObjectNode) parent).remove("proposal")); + return tree; + } + + static JsonNode withoutProposals(final Object answer) { + return withoutProposals(JsonUtils.pojoToJson(answer)); + } + /** The body of the answer to {@link #checks}, as the server wrote it. */ static String answer( final OpenMetadataClient client, diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index 9629d68e07fb..3ceca9ab0c99 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -14,6 +14,7 @@ package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; @@ -74,6 +75,7 @@ import org.openmetadata.schema.type.RelationProvenance; import org.openmetadata.service.Entity; import org.openmetadata.service.monitoring.RequestLatencyContext; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; @@ -257,6 +259,7 @@ private record Issued(RequestLatencyContext.RequestContext request, String state /** Asks once to fill what the server caches between requests, then records the next request. */ private static Reads reads( final OntologyShapeFixture fixture, final OntologyStatementVersion version) { + settleReconcile(); checks(admin(), fixture.type("Order"), version); final List issued = Collections.synchronizedList(new ArrayList<>()); try (var ignored = @@ -289,9 +292,30 @@ private static List ofTheRequestThatReadTheBindings(final List i .filter(read -> read.request() == answering) .map(Issued::statement) .filter(statement -> statement.startsWith(SELECT) && !statement.contains(SETTINGS)) + .takeWhile(statement -> !readsProposals(statement)) .toList(); } + /** + * The first statement of the lookup of the tests and the suggestions of the checks. It comes + * after the compile and is what the rest of the request reads for each proposal it finds. + */ + private static boolean readsProposals(final String statement) { + return statement.contains(" from test_case ") || statement.contains(" from task_entity "); + } + + /** The reconcile that an activation starts reads the same rows, so a count waits for it. */ + private static void settleReconcile() { + try { + assertTrue( + OntologyCheckReconcileQueue.instance() + .awaitIdle(120, java.util.concurrent.TimeUnit.SECONDS)); + } catch (final InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + /** A statement in lower case, without the comment that names its method and on one line. */ private static String plain(final String rendered) { return rendered diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java index cb2066b78194..ec6b964961e6 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java @@ -72,7 +72,6 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyShapeSeverity; -import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.service.Entity; @@ -256,7 +255,9 @@ private static List hidden(final OntologyShapePart... parts /** The body is exactly the expected answer, and it names nothing of the hidden table. */ private static void assertAnswer( final OntologyShapeChecks expected, final String body, final Table... hidden) { - assertEquals(JsonUtils.readTree(JsonUtils.pojoToJson(expected)), JsonUtils.readTree(body)); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(expected), + OntologyShapeCheckFixtures.withoutProposals(body)); for (final Table table : hidden) { assertFalse(body.contains(table.getName()), body); assertFalse(body.contains(table.getId().toString()), body); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java index 71ef36c5c13f..0fbf2480d1c6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java @@ -156,6 +156,21 @@ default void insert(org.openmetadata.schema.EntityInterface entity, String fq connectionType = POSTGRES) List findTestCaseSuggestionIds(); + /** The ids of the suggestion tasks that propose a test case and name the class. */ + @ConnectionAwareSqlQuery( + value = + "SELECT id FROM task_entity WHERE " + + "JSON_UNQUOTE(JSON_EXTRACT(json, '$.payload.suggestionType')) = 'TestCase' " + + "AND JSON_UNQUOTE(JSON_EXTRACT(json, '$.payload.suggestedValue')) " + + "LIKE CONCAT('%', :classId, '%')", + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = + "SELECT id FROM task_entity WHERE json -> 'payload' ->> 'suggestionType' = 'TestCase' " + + "AND json -> 'payload' ->> 'suggestedValue' LIKE '%' || :classId || '%'", + connectionType = POSTGRES) + List findTestCaseSuggestionIdsOfClass(@Bind("classId") String classId); + @ConnectionAwareSqlUpdate( value = "UPDATE task_entity SET json = :json WHERE id = :id", connectionType = MYSQL) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java index 2a6bdfedbee8..18aaf92d4ee9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java @@ -849,6 +849,18 @@ List findIdsByEntityFQN( connectionType = POSTGRES) List findGeneratedIds(); + /** The ids of the test cases that a shape generated for one class, deleted ones included. */ + @ConnectionAwareSqlQuery( + value = + "SELECT id FROM test_case WHERE " + + "JSON_UNQUOTE(JSON_EXTRACT(json, '$.generatedBy.class.id')) = :classId", + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = + "SELECT id FROM test_case WHERE json -> 'generatedBy' -> 'class' ->> 'id' = :classId", + connectionType = POSTGRES) + List findGeneratedIdsOfClass(@Bind("classId") String classId); + class TestCaseRecord { @Getter String json; @Getter Integer rank; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java index 6f2bab1fa99c..b36fccf1ce1a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java @@ -35,12 +35,10 @@ import org.openmetadata.schema.type.TaskEntityStatus; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; -import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.jdbi3.TaskRepository; import org.openmetadata.service.jdbi3.TestCaseRepository; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; -import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.tasks.TestCaseSuggestion; /** @@ -79,7 +77,7 @@ private Held held(final UUID classId) { (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); final Map liveTests = new HashMap<>(); - for (final String id : dao.testCaseDAO().findGeneratedIds()) { + for (final String id : dao.testCaseDAO().findGeneratedIdsOfClass(classId.toString())) { final TestCase test = Entity.getEntity(Entity.TEST_CASE, UUID.fromString(id), "", Include.ALL); final TestCaseGeneratedBy by = test.getGeneratedBy(); @@ -90,7 +88,7 @@ private Held held(final UUID classId) { } } final Map byIdentity = new HashMap<>(); - for (final String id : dao.taskDAO().findTestCaseSuggestionIds()) { + for (final String id : dao.taskDAO().findTestCaseSuggestionIdsOfClass(classId.toString())) { final Task task = Entity.getEntity(Entity.TASK, UUID.fromString(id), "", Include.ALL); final TestCaseGeneratedBy by = TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload())).getGeneratedBy(); @@ -165,7 +163,9 @@ private boolean mayView(final Access access, final String type, final UUID id) { final EntityInterface entity = catalog.authorized(access, type, id, MetadataOperation.VIEW_BASIC); return entity != null; - } catch (final AuthorizationException | EntityNotFoundException denied) { + } catch (final RuntimeException denied) { + // A caller that cannot read the task or the test gets the state without it, whatever the + // reason. return false; } } From 798baac1a79c5f39910199ca47c44db864c9e253 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 21:34:48 -0800 Subject: [PATCH 155/203] Compare answers for what the compile says, not for the proposals a reconcile adds --- .../OntologyShapeCheckDefinitionRightsIT.java | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java index d4aa7cb70115..7b13bb1e08af 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java @@ -428,7 +428,9 @@ void aWriteToTheBindingOfAClassThatAReaderMayNotViewChangesNothingTheReaderReads filterProducts(fixture, OTHER_FILTER_TEXT); for (final OntologyStatementVersion version : VERSIONS) { - assertEquals(before.get(version), answer(reader, scene.order(), version)); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(before.get(version)), + OntologyShapeCheckFixtures.withoutProposals(answer(reader, scene.order(), version))); assertNotEquals(adminBefore.get(version), answer(admin(), scene.order(), version)); } } @@ -483,8 +485,12 @@ void aReleasedShapeIsReadAsReleasedAfterItsWorkingRowIsDeleted(final TestNamespa admin().ontologyShapes().delete(scene.lines().getId().toString()); - assertEquals(ownerRead, answer(owner, scene.order(), RELEASE)); - assertEquals(everyoneRead, answer(admin(), scene.order(), RELEASE)); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(ownerRead), + OntologyShapeCheckFixtures.withoutProposals(answer(owner, scene.order(), RELEASE))); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(everyoneRead), + OntologyShapeCheckFixtures.withoutProposals(answer(admin(), scene.order(), RELEASE))); scene.assertNamesNothingOf(answer(ofNoShape, scene.order(), RELEASE), scene.lines()); assertEquals( List.of(ORDER_SHAPE), @@ -528,8 +534,14 @@ void aReleasedClassPartIsReadAsReleasedAfterItsClassIsDeleted(final TestNamespac admin().ontologyShapes().delete(shape.getId().toString()); admin().ontologyConcepts().delete(stock.getId().toString()); - assertEquals(ownerRead, answer(owner, fixture.type("Order"), RELEASE)); - assertEquals(everyoneRead, answer(admin(), fixture.type("Order"), RELEASE)); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(ownerRead), + OntologyShapeCheckFixtures.withoutProposals( + answer(owner, fixture.type("Order"), RELEASE))); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(everyoneRead), + OntologyShapeCheckFixtures.withoutProposals( + answer(admin(), fixture.type("Order"), RELEASE))); } } } From 19413cfc87755c1911be756e78bd3a9557568c5d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 1 Dec 2026 22:01:58 -0800 Subject: [PATCH 156/203] Measure what a reconcile costs for 1, 10 and 100 classes --- .../tests/OntologyCheckReconcileCostIT.java | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java new file mode 100644 index 000000000000..2b6a88dbf497 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java @@ -0,0 +1,140 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.targets; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.statement.SqlLogger; +import org.jdbi.v3.core.statement.StatementContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.ActivateOntologyRelease; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; + +/** + * What a reconcile costs in statements and time for 1, 10 and 100 classes that each have one + * check: the run that proposes every check, and the run that finds nothing to write. The numbers + * are printed, and the second run is asserted to write nothing. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyCheckReconcileCostIT extends BaseOntologyApprovalIT { + private static final String JOB = "ontology-check-reconcile"; + + /** Counts the statements that the reconcile's own threads issue. */ + private static final class JobCounter implements SqlLogger { + private final AtomicInteger count = new AtomicInteger(); + + @Override + public void logBeforeExecution(final StatementContext context) { + if (Thread.currentThread().getName().equals(JOB)) { + count.incrementAndGet(); + } + } + } + + private static void settle() throws InterruptedException { + assertTrue(OntologyCheckReconcileQueue.instance().awaitIdle(600, TimeUnit.SECONDS)); + } + + @Test + void one(final TestNamespace ns) throws InterruptedException { + measure(ns, 1); + } + + @Test + void ten(final TestNamespace ns) throws InterruptedException { + measure(ns, 10); + } + + @Test + void hundred(final TestNamespace ns) throws InterruptedException { + measure(ns, 100); + } + + private static void measure(final TestNamespace ns, final int classes) + throws InterruptedException { + final Ontology ontology = createOntology(ns, "k" + classes); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, targets("k" + classes, classes, null))) { + fixture.bindAll(); + for (int i = 0; i < classes; i++) { + declare( + ontology, + fixture, + "S" + i, + "Target" + i, + on(fixture, "t" + i, "title" + i).withIn(literals("x"))); + } + final OntologyRelease release = capture(ontology); + final var task = submit(ns, Entity.ONTOLOGY_RELEASE, release.getFullyQualifiedName()); + org.openmetadata.it.util.SdkClients.user1Client() + .tasks() + .resolve(task.getId().toString(), decision(TaskResolutionType.Approved)); + final Jdbi jdbi = Entity.getJdbi(); + final SqlLogger previous = + jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); + final JobCounter counter = new JobCounter(); + jdbi.setSqlLogger(counter); + try { + final OntologyCheckReconcileQueue queue = OntologyCheckReconcileQueue.instance(); + long started = System.nanoTime(); + org.openmetadata.it.util.SdkClients.adminClient() + .ontologies() + .activate( + ontology.getId(), + new ActivateOntologyRelease() + .withReleaseId(release.getId()) + .withExpectedActivationRevision(0L)); + settle(); + final long firstMs = (System.nanoTime() - started) / 1_000_000; + final int firstStatements = counter.count.getAndSet(0); + final int firstWrites = queue.writesMade(ontology.getId()); + + started = System.nanoTime(); + queue.afterActivation(ontology.getId(), "admin"); + settle(); + final long secondMs = (System.nanoTime() - started) / 1_000_000; + final int secondStatements = counter.count.get(); + + System.out.printf( + "RECONCILE-COST classes=%d first: statements=%d ms=%d writes=%d | second: statements=%d ms=%d writes=%d%n", + classes, + firstStatements, + firstMs, + firstWrites, + secondStatements, + secondMs, + queue.writesMade(ontology.getId()) - firstWrites); + assertEquals(classes, firstWrites); + assertEquals(firstWrites, queue.writesMade(ontology.getId())); + } finally { + jdbi.setSqlLogger(previous); + } + } + } +} From 2dcc792da1937d71f5104da1443284e06277b42f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 07:31:48 -0800 Subject: [PATCH 157/203] Tell a test the reconcile deleted from one a person deleted, and keep one test per check The reconcile deletes and restores as the governance bot, so a later run reads that name in updatedBy. A test it deleted comes back when its check is wanted again, an approved task whose test has no row counts as a person's hard delete, and of several live tests of one check only the lowest id stays. Only a user who may create tests is made an assignee. --- .../ontology/OntologyCheckReconciler.java | 71 ++++++-- .../ontology/OntologyCheckReconciliation.java | 125 ++++++++++--- .../service/jdbi3/GeneratedTestScopeTest.java | 37 ++++ .../ontology/OntologyCheckReconcilerTest.java | 94 ++++++++++ .../OntologyCheckReconciliationTest.java | 170 ++++++++++++++++-- 5 files changed, 433 insertions(+), 64 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcilerTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java index bb45c57df4a5..ba2e4dcecf47 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java @@ -26,6 +26,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.function.Supplier; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.api.data.OntologyShapeCheck; @@ -51,6 +52,7 @@ import org.openmetadata.schema.type.TestCaseProposal; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.governance.workflows.WorkflowEventConsumer; import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; import org.openmetadata.service.jdbi3.TaskRepository; @@ -65,7 +67,9 @@ import org.openmetadata.service.ontology.OntologyCheckReconciliation.Proposed; import org.openmetadata.service.ontology.OntologyCheckReconciliation.Refused; import org.openmetadata.service.ontology.OntologyCheckReconciliation.ReplaceTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.RestoreTest; import org.openmetadata.service.ontology.OntologyCheckReconciliation.TaskState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TestState; import org.openmetadata.service.ontology.OntologyCheckReconciliation.UpdateTest; import org.openmetadata.service.ontology.OntologyCheckReconciliation.Wanted; import org.openmetadata.service.ontology.OntologyCheckReconciliation.Write; @@ -102,6 +106,7 @@ public final class OntologyCheckReconciler { private static final String NAME_PREFIX = "shapeCheck_"; private static final int NAME_IDENTITY_LENGTH = 16; private static final int NAME_SUFFIX_LENGTH = 8; + private static final String DELETE_AS = WorkflowEventConsumer.GOVERNANCE_BOT; private final CollectionDAO dao; private final OntologyConceptBindingStore store; @@ -151,14 +156,14 @@ public int writes() { } /** What one class compiled to, with what a task or a test needs to be written from it. */ - private record Planned( + record Planned( Wanted wanted, Generated generated, EntityReference classReference, EntityReference shapeReference, URI classIri) {} - private record Found(Compiled decision, Map byIdentity) {} + record Found(Compiled decision, Map byIdentity) {} Outcome run(final UUID ontologyId, final Scope scope, final String user) { try (FreshReadScope.Handle ignored = FreshReadScope.enter()) { @@ -208,15 +213,26 @@ private Map generatedTests() { new Held( test.getId(), by.getClass_().getId(), + test.getName(), by.getIdentity(), by.getContentDigest(), bindings(by.getReadBindings()), - Boolean.TRUE.equals(test.getDeleted()))); + testState(test))); } } return held; } + /** The reconcile deletes as the governance bot, so a delete by anyone else is a person's. */ + private static TestState testState(final TestCase test) { + if (!Boolean.TRUE.equals(test.getDeleted())) { + return TestState.LIVE; + } + return DELETE_AS.equals(test.getUpdatedBy()) + ? TestState.DELETED_BY_RECONCILE + : TestState.DELETED_BY_PERSON; + } + private Map suggestions() { final TaskRepository repository = (TaskRepository) Entity.getEntityRepository(Entity.TASK); final List ids = @@ -236,7 +252,8 @@ private Map suggestions() { by.getIdentity(), by.getContentDigest(), bindings(by.getReadBindings()), - stateOf(task))); + stateOf(task), + proposal.getTestCase().getName())); }); } } @@ -256,6 +273,7 @@ private static TaskState stateOf(final Task task) { return switch (task.getStatus()) { case Open, InProgress, Pending -> TaskState.OPEN; case Rejected -> TaskState.REJECTED; + case Approved, Completed -> TaskState.APPROVED; default -> TaskState.OTHER; }; } @@ -350,8 +368,13 @@ private Set inOntology(final UUID ontologyId, final Set classes) { // ---- the compile ------------------------------------------------------------------------- private Found compile(final UUID ontologyId, final Release active, final UUID classId) { + return attempt(classId, () -> compiled(ontologyId, active, classId)); + } + + /** Runs one compile, and turns a refusal or a failure into an answer that changes nothing. */ + static Found attempt(final UUID classId, final Supplier compile) { try { - return compiled(ontologyId, active, classId); + return compile.get(); } catch (final WebApplicationException refusal) { LOG.warn( "[OntologyChecks] The compile of class {} was refused, so nothing changes for it: {}", @@ -425,7 +448,7 @@ private Outcome execute( final Map found, final Map tests, final Map tasks) { - final int[] counts = new int[6]; + final int[] counts = new int[7]; for (final Write write : writes) { try { switch (write) { @@ -447,9 +470,13 @@ private Outcome execute( counts[3]++; } case DeleteTest delete -> { - deleteTest(user, delete.testId()); + deleteTest(delete.testId()); counts[4]++; } + case RestoreTest restore -> { + restoreTest(restore.testId()); + counts[6]++; + } } } catch (final RuntimeException failed) { counts[5]++; @@ -459,7 +486,8 @@ private Outcome execute( found.values().stream() .filter(one -> one.decision() instanceof Refused) .forEach(one -> counts[5]++); - return new Outcome(counts[0], counts[1], counts[2], counts[3], counts[4], counts[5]); + return new Outcome( + counts[0], counts[1], counts[2], counts[3] + counts[6], counts[4], counts[5]); } private static Planned planned( @@ -583,10 +611,17 @@ private void updateTest(final String user, final UUID testId, final Planned plan user); } - private void deleteTest(final String user, final UUID testId) { + /** Deletes as the governance bot, which is how a later run tells this delete from a person's. */ + private void deleteTest(final UUID testId) { + final TestCaseRepository tests = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + tests.delete(DELETE_AS, testId, false, false); + } + + private void restoreTest(final UUID testId) { final TestCaseRepository tests = (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); - tests.delete(user, testId, false, false); + tests.restoreEntity(DELETE_AS, testId); } // ---- who is asked ------------------------------------------------------------------------ @@ -628,15 +663,13 @@ private boolean mayCreateTests(final EntityReference user, final Table table) { } final ChangeActor actor = ChangeActor.user(name, null); final ResourceContext resource = new ResourceContext<>(Entity.TABLE, table.getId(), null); - for (final MetadataOperation operation : - List.of(MetadataOperation.CREATE_TESTS, MetadataOperation.EDIT_ALL)) { - try { - authorizer.authorizeActor(actor, new OperationContext(Entity.TABLE, operation), resource); - return true; - } catch (final AuthorizationException denied) { - LOG.debug("[OntologyChecks] {} may not {} on {}", name, operation, table.getId()); - } + try { + authorizer.authorizeActor( + actor, new OperationContext(Entity.TABLE, MetadataOperation.CREATE_TESTS), resource); + return true; + } catch (final AuthorizationException denied) { + LOG.debug("[OntologyChecks] {} may not create tests on {}", name, table.getId()); + return false; } - return false; } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java index 7611aa6c2aa1..2ba199abe2ae 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java @@ -14,6 +14,7 @@ package org.openmetadata.service.ontology; import java.util.ArrayList; +import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -55,38 +56,58 @@ record Checks(List checks) implements Compiled {} /** The compile refused, so nothing can be said about the class. */ record Refused(String reason) implements Compiled {} + /** Whether a test case is live, and who deleted it when it is not. */ + enum TestState { + LIVE, + DELETED_BY_PERSON, + DELETED_BY_RECONCILE + } + /** A test case that was generated from a check. */ record Held( UUID id, UUID classId, + String name, String identity, String digest, List readBindings, - boolean deleted) {} + TestState state) { + boolean live() { + return state == TestState.LIVE; + } + } /** Where a suggestion task of a check stands. */ enum TaskState { OPEN, REJECTED, + APPROVED, OTHER } - /** A suggestion task that proposes a check. */ + /** + * A suggestion task that proposes a check. {@code testName} is the name of the test the proposal + * creates, which is how an approved task finds the test it made. + */ record Proposed( UUID id, UUID classId, String identity, String digest, List readBindings, - TaskState state) {} + TaskState state, + String testName) {} /** One write the reconcile makes. */ - sealed interface Write permits UpdateTest, DeleteTest, ReplaceTask, CancelTask, CreateTask {} + sealed interface Write + permits UpdateTest, DeleteTest, RestoreTest, ReplaceTask, CancelTask, CreateTask {} record UpdateTest(UUID testId, UUID classId, String identity) implements Write {} record DeleteTest(UUID testId) implements Write {} + record RestoreTest(UUID testId) implements Write {} + record ReplaceTask(UUID taskId, UUID classId, String identity) implements Write {} record CancelTask(UUID taskId, String reason) implements Write {} @@ -133,7 +154,7 @@ private static List decide( } } tests.stream() - .filter(test -> !test.deleted() && !wanted.contains(test.identity())) + .filter(test -> test.live() && !wanted.contains(test.identity())) .forEach(test -> writes.add(new DeleteTest(test.id()))); tasks.stream() .filter(task -> task.state() == TaskState.OPEN && !claimed.contains(task.id())) @@ -147,7 +168,7 @@ private static String reasonFor( return NO_LONGER_CHECKED; } final boolean tested = - tests.stream().anyMatch(test -> !test.deleted() && test.identity().equals(task.identity())); + tests.stream().anyMatch(test -> test.live() && test.identity().equals(task.identity())); return tested ? ALREADY_TESTED : ANOTHER_OPEN; } @@ -157,13 +178,10 @@ private static List forCheck( final List tests, final List tasks, final Set claimed) { - final List mine = - tests.stream().filter(test -> test.identity().equals(check.identity())).toList(); - final List live = mine.stream().filter(test -> !test.deleted()).toList(); + final List mine = byId(tests.stream().filter(t -> t.identity().equals(check.identity()))); + final List live = mine.stream().filter(Held::live).toList(); if (!live.isEmpty()) { - return changed(check, live.getFirst().digest(), live.getFirst().readBindings()) - ? List.of(new UpdateTest(live.getFirst().id(), classId, check.identity())) - : List.of(); + return keepOne(classId, check, live); } final List open = tasks.stream() @@ -176,21 +194,74 @@ private static List forCheck( ? List.of(new ReplaceTask(open.getFirst().id(), classId, check.identity())) : List.of(); } - return alreadyAnswered(check, mine, tasks) - ? List.of() - : List.of(new CreateTask(classId, check.identity())); - } - - /** A person rejected this content, or deleted the test generated from it. */ - private static boolean alreadyAnswered( - final Wanted check, final List mine, final List tasks) { - return mine.stream().anyMatch(test -> test.deleted() && test.digest().equals(check.digest())) - || tasks.stream() - .anyMatch( - task -> - task.identity().equals(check.identity()) - && task.state() == TaskState.REJECTED - && task.digest().equals(check.digest())); + final Set personAnswered = answeredByPerson(check, mine, tasks, tests); + if (personAnswered.contains(check.digest()) || rejectedWith(check, tasks)) { + return List.of(); + } + final List reconcileDeleted = + mine.stream().filter(test -> test.state() == TestState.DELETED_BY_RECONCILE).toList(); + if (personAnswered.isEmpty() && !reconcileDeleted.isEmpty()) { + return restore(classId, check, reconcileDeleted.getFirst()); + } + return List.of(new CreateTask(classId, check.identity())); + } + + /** Keeps the live test with the lowest id, updates it when it is stale, and deletes the rest. */ + private static List keepOne( + final UUID classId, final Wanted check, final List live) { + final Held kept = live.getFirst(); + final List writes = new ArrayList<>(); + if (changed(check, kept.digest(), kept.readBindings())) { + writes.add(new UpdateTest(kept.id(), classId, check.identity())); + } + live.stream().skip(1).forEach(extra -> writes.add(new DeleteTest(extra.id()))); + return writes; + } + + private static List restore(final UUID classId, final Wanted check, final Held deleted) { + final List writes = new ArrayList<>(); + writes.add(new RestoreTest(deleted.id())); + if (changed(check, deleted.digest(), deleted.readBindings())) { + writes.add(new UpdateTest(deleted.id(), classId, check.identity())); + } + return writes; + } + + /** The tests of one identity, lowest id first, so two servers choose the same one. */ + private static List byId(final java.util.stream.Stream tests) { + return tests.sorted(Comparator.comparing(test -> test.id().toString())).toList(); + } + + /** + * The digests of what a person deleted for this check: a test they soft deleted, and an approved + * task whose test has no row left, which a hard delete leaves behind. + */ + private static Set answeredByPerson( + final Wanted check, + final List mine, + final List tasks, + final List allTests) { + final Set names = new HashSet<>(); + allTests.forEach(test -> names.add(test.name())); + final Set digests = new HashSet<>(); + mine.stream() + .filter(test -> test.state() == TestState.DELETED_BY_PERSON) + .forEach(test -> digests.add(test.digest())); + tasks.stream() + .filter(task -> task.identity().equals(check.identity())) + .filter(task -> task.state() == TaskState.APPROVED && !names.contains(task.testName())) + .forEach(task -> digests.add(task.digest())); + return digests; + } + + /** A person rejected this content. */ + private static boolean rejectedWith(final Wanted check, final List tasks) { + return tasks.stream() + .anyMatch( + task -> + task.identity().equals(check.identity()) + && task.state() == TaskState.REJECTED + && task.digest().equals(check.digest())); } private static boolean changed( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java index b75d74921ee4..907debeedb68 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java @@ -116,6 +116,43 @@ void theReconcileMayChangeWhatIsFrozenInsideTheScope() { } } + @Test + void aChangeToAnyOneOfTheFourFrozenParametersIsRefused() { + UUID definition = UUID.randomUUID(); + for (String name : List.of("sqlExpression", "strategy", "operator", "threshold")) { + TestCase original = counted(definition, "0"); + TestCase updated = counted(definition, "0"); + updated.getParameterValues().stream() + .filter(value -> name.equals(value.getName())) + .forEach(value -> value.setValue("changed")); + BadRequestException e = + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnchanged(original, updated), + name); + assertEquals(GeneratedTestScope.FROM_A_SHAPE, e.getMessage(), name); + } + } + + @Test + void theSameFourParametersAreAcceptedUnchanged() { + UUID definition = UUID.randomUUID(); + assertDoesNotThrow( + () -> + GeneratedTestScope.requireUnchanged( + counted(definition, "0"), counted(definition, "0").withDescription("words"))); + } + + private static TestCase counted(final UUID definition, final String threshold) { + return generated(definition, "SELECT 1") + .withParameterValues( + List.of( + new TestCaseParameterValue().withName("sqlExpression").withValue("SELECT 1"), + new TestCaseParameterValue().withName("strategy").withValue("COUNT"), + new TestCaseParameterValue().withName("operator").withValue("<="), + new TestCaseParameterValue().withName("threshold").withValue(threshold))); + } + private static TestCase plain(final UUID definition, final String statement) { return new TestCase() .withEntityLink("<#E::table::svc.db.schema.t>") diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcilerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcilerTest.java new file mode 100644 index 000000000000..d2535bd71362 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcilerTest.java @@ -0,0 +1,94 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +import jakarta.ws.rs.BadRequestException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Found; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Checks; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Compiled; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.DeleteTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Held; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Proposed; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Refused; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TaskState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TestState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Write; + +class OntologyCheckReconcilerTest { + private static final UUID CLASS = UUID.fromString("00000000-0000-0000-0000-0000000000c1"); + private static final UUID TEST = UUID.fromString("00000000-0000-0000-0000-000000000001"); + private static final UUID TASK = UUID.fromString("00000000-0000-0000-0000-000000000002"); + + @Test + void aCompileThatTheServerRefusesIsReadAsRefusedAndNotAsNoChecks() { + final Found found = + OntologyCheckReconciler.attempt( + CLASS, + () -> { + throw new BadRequestException("Binding property inheritance exceeds the limit"); + }); + + final Refused refused = assertInstanceOf(Refused.class, found.decision()); + assertEquals("Binding property inheritance exceeds the limit", refused.reason()); + assertEquals(Map.of(), found.byIdentity()); + } + + @Test + void aCompileThatFailsIsReadAsRefusedWithItsMessage() { + final Found found = + OntologyCheckReconciler.attempt( + CLASS, + () -> { + throw new IllegalStateException("the binding rows changed"); + }); + + assertEquals( + new Refused("the binding rows changed"), assertInstanceOf(Refused.class, found.decision())); + } + + @Test + void aCompileThatAnswersIsPassedOn() { + final Found answered = new Found(new Checks(List.of()), Map.of()); + assertEquals(answered, OntologyCheckReconciler.attempt(CLASS, () -> answered)); + } + + @Test + void aRefusedCompileLeavesTheTestAndTheOpenTaskOfItsClassAlone() { + final Found found = + OntologyCheckReconciler.attempt( + CLASS, + () -> { + throw new BadRequestException("refused"); + }); + final Map decisions = Map.of(CLASS, found.decision()); + final Held test = new Held(TEST, CLASS, "test", "a", "d1", List.of(), TestState.LIVE); + final Proposed task = new Proposed(TASK, CLASS, "b", "d1", List.of(), TaskState.OPEN, "other"); + + final List writes = + OntologyCheckReconciliation.decide(decisions, List.of(test), List.of(task)); + + assertEquals(List.of(), writes); + assertEquals( + List.of(new DeleteTest(TEST)), + OntologyCheckReconciliation.decide( + Map.of(CLASS, new Checks(List.of())), List.of(test), List.of())); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java index 8bba888e508c..c4f9a3a7e769 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java @@ -30,7 +30,9 @@ import org.openmetadata.service.ontology.OntologyCheckReconciliation.Proposed; import org.openmetadata.service.ontology.OntologyCheckReconciliation.Refused; import org.openmetadata.service.ontology.OntologyCheckReconciliation.ReplaceTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.RestoreTest; import org.openmetadata.service.ontology.OntologyCheckReconciliation.TaskState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TestState; import org.openmetadata.service.ontology.OntologyCheckReconciliation.UpdateTest; import org.openmetadata.service.ontology.OntologyCheckReconciliation.Wanted; import org.openmetadata.service.ontology.OntologyCheckReconciliation.Write; @@ -41,6 +43,8 @@ class OntologyCheckReconciliationTest { private static final UUID ASSET = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); private static final UUID ID_1 = UUID.fromString("00000000-0000-0000-0000-000000000001"); private static final UUID ID_2 = UUID.fromString("00000000-0000-0000-0000-000000000002"); + private static final UUID ID_3 = UUID.fromString("00000000-0000-0000-0000-000000000003"); + private static final UUID ID_4 = UUID.fromString("00000000-0000-0000-0000-000000000004"); private static final List REV_3 = List.of(new Binding(CLASS, ASSET, 3)); private static final List REV_4 = List.of(new Binding(CLASS, ASSET, 4)); @@ -49,13 +53,18 @@ private static Wanted check(final String identity, final String digest, final Li } private static Held test( - final UUID id, final String identity, final String digest, final boolean deleted) { - return new Held(id, CLASS, identity, digest, REV_3, deleted); + final UUID id, final String identity, final String digest, final TestState state) { + return new Held(id, CLASS, "test-" + id, identity, digest, REV_3, state); } private static Proposed task( final UUID id, final String identity, final String digest, final TaskState state) { - return new Proposed(id, CLASS, identity, digest, REV_3, state); + return new Proposed(id, CLASS, identity, digest, REV_3, state, "made-by-" + id); + } + + /** The task that was approved and created the test with this id, as {@code test} names it. */ + private static Proposed approvedTestOf(final UUID testId) { + return new Proposed(ID_2, CLASS, "a", "d1", REV_3, TaskState.APPROVED, "test-" + testId); } private static List decide( @@ -77,7 +86,7 @@ void aTestWhoseDigestChangedIsUpdatedInPlace() { final List writes = decide( new Checks(List.of(check("a", "d2", REV_3))), - List.of(test(ID_1, "a", "d1", false)), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), List.of()); assertEquals(List.of(new UpdateTest(ID_1, CLASS, "a")), writes); } @@ -87,7 +96,7 @@ void aTestWhoseReadBindingsChangedIsUpdatedInPlace() { final List writes = decide( new Checks(List.of(check("a", "d1", REV_4))), - List.of(test(ID_1, "a", "d1", false)), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), List.of()); assertEquals(List.of(new UpdateTest(ID_1, CLASS, "a")), writes); } @@ -97,7 +106,7 @@ void aTestWithTheSameDigestAndBindingsIsLeftAlone() { final List writes = decide( new Checks(List.of(check("a", "d1", REV_3))), - List.of(test(ID_1, "a", "d1", false)), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), List.of()); assertEquals(List.of(), writes); } @@ -107,7 +116,7 @@ void aTestMakesTheOpenTaskOfTheSameCheckWait() { final List writes = decide( new Checks(List.of(check("a", "d2", REV_3))), - List.of(test(ID_1, "a", "d1", false)), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), List.of(task(ID_2, "a", "d1", TaskState.OPEN))); assertEquals( List.of( @@ -160,7 +169,7 @@ void aTestAPersonDeletedWithTheSameDigestProposesNothing() { final List writes = decide( new Checks(List.of(check("a", "d1", REV_3))), - List.of(test(ID_1, "a", "d1", true)), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_PERSON)), List.of()); assertEquals(List.of(), writes); } @@ -170,7 +179,7 @@ void aTestAPersonDeletedWithOtherContentIsProposedAgain() { final List writes = decide( new Checks(List.of(check("a", "d2", REV_3))), - List.of(test(ID_1, "a", "d1", true)), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_PERSON)), List.of()); assertEquals(List.of(new CreateTask(CLASS, "a")), writes); } @@ -180,7 +189,7 @@ void aTestWhoseCheckNoLongerAppearsIsDeletedAndItsOpenTaskCancelled() { final List writes = decide( new Checks(List.of()), - List.of(test(ID_1, "a", "d1", false)), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), List.of(task(ID_2, "b", "d1", TaskState.OPEN))); assertEquals( List.of( @@ -194,7 +203,7 @@ void aTestAlreadyDeletedOrATaskAlreadyClosedWhoseCheckVanishedIsNotTouched() { final List writes = decide( new Checks(List.of()), - List.of(test(ID_1, "a", "d1", true)), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_PERSON)), List.of( task(ID_2, "b", "d1", TaskState.REJECTED), task(UUID.randomUUID(), "c", "d1", TaskState.OTHER))); @@ -206,8 +215,8 @@ void aRefusedCompileChangesNothingForItsClassAndStillReconcilesAnother() { final Map classes = new LinkedHashMap<>(); classes.put(CLASS, new Refused("Binding property inheritance exceeds the 10000 axiom limit")); classes.put(OTHER_CLASS, new Checks(List.of())); - final Held kept = test(ID_1, "a", "d1", false); - final Held goes = new Held(ID_2, OTHER_CLASS, "z", "d1", REV_3, false); + final Held kept = test(ID_1, "a", "d1", TestState.LIVE); + final Held goes = new Held(ID_2, OTHER_CLASS, "t-z", "z", "d1", REV_3, TestState.LIVE); final Proposed openTask = task(UUID.randomUUID(), "b", "d1", TaskState.OPEN); final List writes = OntologyCheckReconciliation.decide(classes, List.of(kept, goes), List.of(openTask)); @@ -225,7 +234,7 @@ void aSecondRunOverTheStateTheFirstRunWroteWritesNothing() { final Wanted created = check("a", "d2", REV_4); final Wanted replaced = check("b", "d2", REV_4); final Wanted fresh = check("c", "d1", REV_3); - final List tests = List.of(test(ID_1, "a", "d1", false)); + final List tests = List.of(test(ID_1, "a", "d1", TestState.LIVE)); final List tasks = List.of(task(ID_2, "b", "d1", TaskState.OPEN)); final List first = decide(new Checks(List.of(created, replaced, fresh)), tests, tasks); assertEquals( @@ -234,11 +243,12 @@ void aSecondRunOverTheStateTheFirstRunWroteWritesNothing() { new ReplaceTask(ID_2, CLASS, "b"), new CreateTask(CLASS, "c")), first); - final List testsAfter = List.of(new Held(ID_1, CLASS, "a", "d2", REV_4, false)); + final List testsAfter = + List.of(new Held(ID_1, CLASS, "test-" + ID_1, "a", "d2", REV_4, TestState.LIVE)); final List tasksAfter = List.of( - new Proposed(ID_2, CLASS, "b", "d2", REV_4, TaskState.OPEN), - new Proposed(UUID.randomUUID(), CLASS, "c", "d1", REV_3, TaskState.OPEN)); + new Proposed(ID_2, CLASS, "b", "d2", REV_4, TaskState.OPEN, "made-by-" + ID_2), + new Proposed(UUID.randomUUID(), CLASS, "c", "d1", REV_3, TaskState.OPEN, "made-by-c")); assertEquals( List.of(), decide(new Checks(List.of(created, replaced, fresh)), testsAfter, tasksAfter)); } @@ -258,10 +268,134 @@ void twoOpenTasksOfOneCheckKeepOneAndCancelTheOther() { @Test void theTestsOfAClassThatIsNotNamedAreNotTouched() { - final Held elsewhere = new Held(ID_1, OTHER_CLASS, "z", "d1", REV_3, false); + final Held elsewhere = new Held(ID_1, OTHER_CLASS, "t-z", "z", "d1", REV_3, TestState.LIVE); assertEquals( List.of(), OntologyCheckReconciliation.decide( Map.of(CLASS, new Checks(List.of())), List.of(elsewhere), List.of())); } + + @Test + void aTestTheReconcileDeletedComesBackWhenItsCheckIsWantedAgain() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + assertEquals(List.of(new RestoreTest(ID_1)), writes); + } + + @Test + void aTestTheReconcileDeletedComesBackUpdatedWhenItsContentChanged() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_4))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + assertEquals(List.of(new RestoreTest(ID_1), new UpdateTest(ID_1, CLASS, "a")), writes); + } + + @Test + void aTestTheReconcileDeletedStaysDeletedWhenAPersonDeletedAnotherOfTheSameContent() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of( + test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE), + test(ID_2, "a", "d1", TestState.DELETED_BY_PERSON)), + List.of()); + assertEquals(List.of(), writes); + } + + @Test + void aTestTheReconcileDeletedGivesWayToANewTaskWhenAPersonDeletedAnotherOfOtherContent() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of( + test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE), + test(ID_2, "a", "d1", TestState.DELETED_BY_PERSON)), + List.of()); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void ofSeveralTestsTheReconcileDeletedTheOneWithTheLowestIdComesBack() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of( + test(ID_3, "a", "d1", TestState.DELETED_BY_RECONCILE), + test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE), + test(ID_2, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of()); + assertEquals(List.of(new RestoreTest(ID_1)), writes); + } + + @Test + void anApprovedTaskWhoseTestWasHardDeletedProposesNothingForTheSameDigest() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.APPROVED))); + assertEquals(List.of(), writes); + } + + @Test + void anApprovedTaskWhoseTestWasHardDeletedIsProposedAgainForOtherContent() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.APPROVED))); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void anApprovedTaskWhoseTestStillHasARowIsNotAHardDelete() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + assertEquals(List.of(new RestoreTest(ID_1), new UpdateTest(ID_1, CLASS, "a")), writes); + } + + @Test + void threeLiveTestsOfOneCheckKeepTheLowestIdAndDeleteTheOthersInIdOrder() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of( + test(ID_3, "a", "d1", TestState.LIVE), + test(ID_1, "a", "d1", TestState.LIVE), + test(ID_2, "a", "d1", TestState.LIVE)), + List.of()); + assertEquals( + List.of(new UpdateTest(ID_1, CLASS, "a"), new DeleteTest(ID_2), new DeleteTest(ID_3)), + writes); + } + + @Test + void twoLiveTestsOfOneCheckThatAreCurrentLoseOnlyTheHigherId() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_4, "a", "d1", TestState.LIVE), test(ID_2, "a", "d1", TestState.LIVE)), + List.of()); + assertEquals(List.of(new DeleteTest(ID_4)), writes); + } + + @Test + void aSecondRunAfterTheDuplicatesWereDeletedWritesNothing() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of( + test(ID_1, "a", "d1", TestState.LIVE), + test(ID_2, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of()); + assertEquals(List.of(), writes); + } } From 6acf05bd013d88b093f49ebc334de70033f6de1c Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 08:53:50 -0800 Subject: [PATCH 158/203] ontology checks: read proposal states in batches, hold PUT to the read-only rule, ask only who may create tests, and record the reconcile's own deletes --- ...ck-reaches-its-table-as-a-proposed-test.md | 56 +- .../tests/OntologyCheckReconcileCostIT.java | 36 +- .../tests/OntologyShapeCheckProposalIT.java | 585 ++++++++++++++++-- .../it/tests/OntologyShapeCheckReadsIT.java | 82 ++- .../it/tests/OntologyShapeProposalAskIT.java | 376 +++++++++++ .../OntologyCheckReconcileAccess.java | 40 ++ .../service/jdbi3/TaskRepository.java | 15 +- .../service/jdbi3/TestCaseRepository.java | 9 + .../ontology/OntologyCheckProposals.java | 125 ++-- .../ontology/OntologyCheckReconciler.java | 26 +- 10 files changed, 1211 insertions(+), 139 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcileAccess.java diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index 366acc5b365b..be83983b51db 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-12-01 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, on MySQL and Postgres) +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted that comes back and a hard delete, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read) - **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) ## Context @@ -22,11 +22,15 @@ to find every test they made and change it by hand. **A check is proposed before it is a test.** The server files one suggestion task for each check (`suggestionType` `TestCase`, `fieldPath` `testCases`), about the table the check belongs to. -Approving it creates the test case as the approver, so the approver needs `CreateTests` on the table, -as a request to create a test case does. Rejecting creates nothing. The task is assigned to the -owners of the table, else the owners of the ontology, else nobody, and a user who lacks the right on -the table is left out. Its source is `Ingestion`, because a deterministic compile of a shape wrote it, -and no agent or model did. +Approving it creates the test case as the approver, so the approver needs `CreateTests` on the +table, as a request to create a test case does. Rejecting creates nothing. The task is assigned to +the owners of the table, else the owners of the ontology, else nobody. A team stands for its users, +and a user who may not create tests on the table is left out. A task filed with nobody takes the +owners of the table, as every task does. The approver needs `CreateTests` on the table and the right +to resolve the task, which the assignees, the owners of the table and the administrators have. A +task with no owner on the table or the ontology has no assignee, so only an administrator, or a user +whose role grants `ResolveTask`, can approve it. Its source is `Ingestion`, because a deterministic +compile of a shape wrote it, and no agent or model did. **A test is not kept in a review state.** The runner reads every test case of a suite and no status of it, so a test that waits for a decision would run. The proposal is the task and the test does not @@ -52,14 +56,21 @@ reconcile set it. **The reconcile.** A background job compiles the checks of each class in scope, for no caller, so it reads every shape, property and table and masks nothing (the answer a person gets is a masked view of -the same compile, and a step that creates tests must never read a hidden constraint as absent). For -each check it does the first of these: +the same compile, and a step that creates tests must never read a hidden constraint as absent). For each check it does the first of these that applies: -| A test case with the identity exists | The test is updated in place when its content digest or its bindings changed, else left alone | +| What exists for the check | What the reconcile does | |---|---| -| else an open task with the identity exists | Its suggested value is replaced when the content or the bindings changed, else left alone | -| else a rejected task, or a test a person deleted, has the identity and the same content digest | Nothing | -| else | A new task | +| A live test case with the identity | Updates it in place when its content digest or its bindings changed, else leaves it alone. Deletes every other live test case of the identity, keeping the one with the lowest id. | +| An open task with the identity | Replaces its suggested value when the content or the bindings changed, else leaves it alone. | +| A rejected task, a test a person deleted, or an approved task whose test a person hard deleted, with the same content digest | Nothing | +| A test the reconcile deleted, and no test a person deleted | Restores the one with the lowest id, then updates it as in the first row | +| None of these | Files a new task | + +The reconcile deletes and restores a test as the governance bot, and a later run reads that name in +the test's `updatedBy` to tell its own delete from a person's. So a test it deleted comes back, with +its id and its results, when an older release wants its check again. A hard delete leaves no row, +so the content is compared with the content the task was approved with. A test whose content was +updated after its approval and then hard deleted is proposed once more. A test whose identity no longer appears is deleted, as a soft delete a person can see. An open task whose identity no longer appears is closed as `Cancelled` with the reason as its comment. A part that @@ -84,9 +95,10 @@ asserts that the second count is zero. **Read-only.** A test case with `generatedBy` refuses a change to its test definition, entity link, parameter values or `generatedBy` by anyone but the reconcile, with a 400 that says the test comes -from a shape. A create or a patch that sends `generatedBy` is a 400. Its description, owners and tags -stay editable and a person may delete it. A deleted test is not brought back unless the content -changes. +from a shape. A create that sends `generatedBy` is a 400, and so is a patch that changes it. A PUT +keeps the stored `generatedBy`, so a PUT that changes only the description, owners or tags succeeds. +The description, owners and tags stay editable, and a person may delete the test. A test a person +deleted is not brought back unless the content changes. **What a test costs and reads.** The test is added to the basic test suite of its table, created if the table has none. A suite with no pipeline gets one that runs daily at midnight, and the deployment @@ -101,8 +113,10 @@ database or the pipeline sets. **What a caller reads.** Each check of `GET /v1/ontologyConcepts/{id}/shapeChecks` has a `proposal`: `none`, `proposed` with the task, `rejected` with the task, or `accepted` with the test case and the status and time of its latest result. A caller who may not view the task or the test case gets the -state without the reference. The proposals do not show in the lists of suggestions that a page of -descriptions and tags reads, because those lists leave out a suggestion type they cannot show. +state without the reference. A caller who may not view the test case gets no latest result either. +Reading the proposal states of a class takes the same number of statements for one check as for +forty. The proposals do not show in the lists of suggestions that a page of descriptions and tags +reads, because those lists leave out a suggestion type they cannot show. ## Consequences @@ -112,8 +126,12 @@ descriptions and tags reads, because those lists leave out a suggestion type the as one whose row filter changed, is updated without an activation. - The queue is in memory. A trigger lost with the server is made good by the next one for the ontology, because each run derives its writes from the state it reads. A crash in the middle of a - run leaves some writes made, each complete, and the next run finishes the rest. Two servers can run - two jobs of one ontology, which can file two open tasks of one check, and the next run closes one. + run leaves some writes made, each complete, and the next run finishes the rest. Two servers can + run two jobs of one ontology. They can file two open tasks of one check, or create two tests of it + once both tasks are approved. The next run cancels the second task, or deletes every test of the + check but the one with the lowest id. +- Finding the generated tests and their tasks reads every test case and every task of the + deployment, so a reconcile and a read of proposal states take time in proportion to them. - The compile reads three things after its check of the binding revisions: the holders of the inverse of a relation, the classes that share a filtered table, and the tables themselves. A change to them that moves no revision listed by a check is not triggered by itself. The holders of an inverse diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java index 2b6a88dbf497..6356e6e73508 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java @@ -45,13 +45,37 @@ class OntologyCheckReconcileCostIT extends BaseOntologyApprovalIT { private static final String JOB = "ontology-check-reconcile"; - /** Counts the statements that the reconcile's own threads issue. */ + /** What a run costs for each class, with the margin the shared lane's caches can move it by. */ + private static final int FIRST_RUN_STATEMENTS_PER_CLASS = 170; + + private static final int SECOND_RUN_STATEMENTS_PER_CLASS = 45; + private static final int FIXED_STATEMENTS = 40; + + /** + * Counts the statements of the runs of one ontology on the reconcile threads. A run starts with + * the read of the state of its ontology, so a thread counts from that statement until the read + * of another ontology's state starts the next run. Runs of other ontologies in the same lane are + * not counted. + */ private static final class JobCounter implements SqlLogger { + private static final String STATE = "from ontology_state"; + private final String ontologyId; private final AtomicInteger count = new AtomicInteger(); + private final ThreadLocal mine = ThreadLocal.withInitial(() -> Boolean.FALSE); + + JobCounter(final String ontologyId) { + this.ontologyId = ontologyId; + } @Override public void logBeforeExecution(final StatementContext context) { - if (Thread.currentThread().getName().equals(JOB)) { + if (!Thread.currentThread().getName().equals(JOB)) { + return; + } + if (context.getRenderedSql().toLowerCase(java.util.Locale.ROOT).contains(STATE)) { + mine.set(context.getBinding().toString().contains(ontologyId)); + } + if (mine.get()) { count.incrementAndGet(); } } @@ -98,7 +122,7 @@ private static void measure(final TestNamespace ns, final int classes) final Jdbi jdbi = Entity.getJdbi(); final SqlLogger previous = jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); - final JobCounter counter = new JobCounter(); + final JobCounter counter = new JobCounter(ontology.getId().toString()); jdbi.setSqlLogger(counter); try { final OntologyCheckReconcileQueue queue = OntologyCheckReconcileQueue.instance(); @@ -132,6 +156,12 @@ private static void measure(final TestNamespace ns, final int classes) queue.writesMade(ontology.getId()) - firstWrites); assertEquals(classes, firstWrites); assertEquals(firstWrites, queue.writesMade(ontology.getId())); + assertTrue( + firstStatements <= FIRST_RUN_STATEMENTS_PER_CLASS * classes + FIXED_STATEMENTS, + "first run " + firstStatements); + assertTrue( + secondStatements <= SECOND_RUN_STATEMENTS_PER_CLASS * classes + FIXED_STATEMENTS, + "second run " + secondStatements); } finally { jdbi.setSqlLogger(previous); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java index 1c9636276599..8e58bee93503 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java @@ -14,12 +14,14 @@ package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.openmetadata.it.tests.OntologyBindingFixtures.assertStatus; import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.PARTIES; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; @@ -39,9 +41,12 @@ import java.net.URI; import java.util.ArrayList; import java.util.List; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; @@ -61,8 +66,11 @@ import org.openmetadata.schema.type.TaskEntityStatus; import org.openmetadata.schema.type.TaskResolutionType; import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconcileAccess; import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; @@ -77,7 +85,7 @@ class OntologyShapeCheckProposalIT extends BaseOntologyApprovalIT { private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; private static final long WAIT_SECONDS = 120; - private static final Shape ACCOUNTS = + static final Shape ACCOUNTS = mapping( "accounts", List.of(table("accounts", List.of(integer("id"), text("email"), integer("age")))), @@ -95,12 +103,12 @@ class OntologyShapeCheckProposalIT extends BaseOntologyApprovalIT { bound("accountEmail", "email"), bound("accountAge", "age"))); - private static org.openmetadata.schema.type.OntologyShapeConstraint listed( + static org.openmetadata.schema.type.OntologyShapeConstraint listed( final OntologyShapeFixture fixture) { return on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b")); } - private static org.openmetadata.schema.type.OntologyShapeConstraint ranged( + static org.openmetadata.schema.type.OntologyShapeConstraint ranged( final OntologyShapeFixture fixture, final String upper) { return on(fixture, "age-range", "accountAge") .withDatatypeIri(URI.create(XSD + "integer")) @@ -108,7 +116,7 @@ private static org.openmetadata.schema.type.OntologyShapeConstraint ranged( .withMaxInclusive(limit(upper)); } - private static void settle() { + static void settle() { try { assertTrue( OntologyCheckReconcileQueue.instance().awaitIdle(WAIT_SECONDS, TimeUnit.SECONDS), @@ -120,12 +128,18 @@ private static void settle() { } /** Captures the working draft, approves the release and makes it the active one. */ - private static void release(final TestNamespace ns, final Ontology ontology) { + static OntologyRelease release(final TestNamespace ns, final Ontology ontology) { final OntologyRelease release = capture(ontology); final var task = submit(ns, Entity.ONTOLOGY_RELEASE, release.getFullyQualifiedName()); SdkClients.user1Client() .tasks() .resolve(task.getId().toString(), decision(TaskResolutionType.Approved)); + activate(ontology, release); + return release; + } + + /** Makes an approved release the active one, an older one included, and waits for the reconcile. */ + static void activate(final Ontology ontology, final OntologyRelease release) { final long revision = admin().ontologies().state(ontology.getId()).getActivationRevision(); admin() .ontologies() @@ -137,20 +151,14 @@ private static void release(final TestNamespace ns, final Ontology ontology) { settle(); } - private static List checks(final OntologyConcept account) { - final OntologyShapeChecks answer = - admin() - .getHttpClient() - .execute( - HttpMethod.GET, - "/v1/ontologyConcepts/" - + account.getId() - + "/shapeChecks?version=" - + RELEASE.value(), - null, - OntologyShapeChecks.class); + static List checks(final OntologyConcept account) { + return checks(admin(), account); + } + + static List checks( + final OpenMetadataClient reader, final OntologyConcept account) { final List found = new ArrayList<>(); - for (final OntologyCheckedShape shape : answer.getShapes()) { + for (final OntologyCheckedShape shape : answer(reader, account).getShapes()) { for (final OntologyCheckedConstraint constraint : shape.getConstraints()) { for (final OntologyCheckedPart part : constraint.getParts()) { if (part.getChecks() != null) { @@ -162,15 +170,46 @@ private static List checks(final OntologyConcept account) { return found; } - private static OntologyShapeCheck checkOf( - final List checks, final String column) { + /** The first check of the constraint with this id, as the reader is shown it. */ + static OntologyShapeCheck checkOfConstraint( + final OpenMetadataClient reader, final OntologyConcept account, final String constraintId) { + return answer(reader, account).getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .filter(constraint -> constraint.getId().equals(constraintId)) + .flatMap(constraint -> constraint.getParts().stream()) + .flatMap( + part -> java.util.Optional.ofNullable(part.getChecks()).stream().flatMap(List::stream)) + .findFirst() + .orElseThrow(); + } + + private static OntologyShapeChecks answer( + final OpenMetadataClient reader, final OntologyConcept account) { + return reader + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyConcepts/" + account.getId() + "/shapeChecks?version=" + RELEASE.value(), + null, + OntologyShapeChecks.class); + } + + static void cancel(final String taskId) { + OntologyCheckReconcileAccess.cancel(UUID.fromString(taskId)); + } + + static OntologyShapeCheck checkOf(final List checks, final String column) { return checks.stream() .filter(check -> check.getColumns().getFirst().getFirst().equals(column)) .findFirst() .orElseThrow(); } - private static JsonNode testsOf(final String tableFqn) { + static JsonNode testsOf(final String tableFqn) { + return testsOf(tableFqn, "non-deleted"); + } + + static JsonNode testsOf(final String tableFqn, final String include) { return JsonUtils.readTree( admin() .getHttpClient() @@ -179,21 +218,28 @@ private static JsonNode testsOf(final String tableFqn) { "/v1/dataQuality/testCases?entityLink=" + java.net.URLEncoder.encode( "<#E::table::" + tableFqn + ">", java.nio.charset.StandardCharsets.UTF_8) - + "&limit=100&fields=testSuite,testDefinition,inspectionQuery,generatedBy", + + "&limit=100&include=" + + include + + "&fields=testSuite,testDefinition,inspectionQuery,generatedBy", null)); } - private static int generatedTests(final String tableFqn) { - int count = 0; - for (final JsonNode test : testsOf(tableFqn).path("data")) { + static int generatedTests(final String tableFqn) { + return generated(tableFqn, "non-deleted").size(); + } + + /** The tests generated from a shape, with the deleted ones when {@code include} is {@code all}. */ + static List generated(final String tableFqn, final String include) { + final List found = new ArrayList<>(); + for (final JsonNode test : testsOf(tableFqn, include).path("data")) { if (test.has("generatedBy")) { - count++; + found.add(test); } } - return count; + return found; } - private static OntologyShapeCheckProposalState stateOf( + static OntologyShapeCheckProposalState stateOf( final OntologyConcept account, final String column) { return checkOf(checks(account), column).getProposal().getState(); } @@ -297,9 +343,17 @@ void acceptNeedsRight(final TestNamespace ns) { assertEquals(0, generatedTests(fixture.table("accounts").getFullyQualifiedName())); assertEquals(TaskEntityStatus.Open, admin().tasks().get(taskId).getStatus()); + assertFalse(hasTestSuite(fixture.table("accounts").getId().toString())); } } + static boolean hasTestSuite(final String tableId) { + return admin() + .getHttpClient() + .executeForString(HttpMethod.GET, "/v1/tables/" + tableId + "?fields=testSuite", null) + .contains("\"testSuite\""); + } + @Test void rejectedStays(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "rejected"); @@ -471,45 +525,145 @@ void constraintGone(final TestNamespace ns) { void readOnly(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "readonly"); try (OntologyShapeFixture fixture = - new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("pro")) { fixture.bindAll(); declareKey(fixture, "accounts", List.of("id"), "email"); declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + final OpenMetadataClient owner = + OntologyBindingFixtures.client(access.userToken("owner", List.of())); + fixture.ownedBy(owner, "accounts"); release(ns, ontology); final OntologyConcept account = fixture.type("Account"); - admin() - .tasks() - .resolve( - checkOf(checks(account), "email").getProposal().getTask().getId().toString(), - new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + approve(checkOf(checks(account), "email").getProposal().getTask().getId().toString()); final String testId = checkOf(checks(account), "email").getProposal().getTestCase().getId().toString(); final String path = "/v1/dataQuality/testCases/" + testId; - assertStatus( - 400, - () -> - admin() - .getHttpClient() - .execute( - HttpMethod.PATCH, - path, - JsonUtils.readTree( - "[{\"op\":\"replace\",\"path\":\"/parameterValues/0/value\"," - + "\"value\":\"SELECT 0\"}]"), - org.openmetadata.schema.tests.TestCase.class)); - - final org.openmetadata.schema.tests.TestCase described = - admin() - .getHttpClient() - .execute( - HttpMethod.PATCH, - path, - JsonUtils.readTree( - "[{\"op\":\"add\",\"path\":\"/description\",\"value\":\"looked at\"}]"), - org.openmetadata.schema.tests.TestCase.class); - assertEquals("looked at", described.getDescription()); + final java.util.Map callers = new java.util.LinkedHashMap<>(); + callers.put("admin", admin()); + callers.put("owner", owner); + for (final var caller : callers.entrySet()) { + final OpenMetadataClient who = caller.getValue(); + assertShapeRefusal( + () -> + who.getHttpClient() + .execute( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"replace\",\"path\":\"/parameterValues/0/value\"," + + "\"value\":\"SELECT 0\"}]"), + org.openmetadata.schema.tests.TestCase.class)); + assertShapeRefusal(() -> replaceDefinition(who, path)); + assertShapeRefusal(() -> put(who, testId, "threshold", "5")); + final String words = "looked at by " + caller.getKey(); + assertEquals(words, put(who, testId, null, words).getDescription()); + assertEquals(words, getTest(testId).getDescription()); + assertEquals("0", parameter(getTest(testId), "threshold")); + assertEquals( + "patched by " + words, + who.getHttpClient() + .execute( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/description\",\"value\":\"patched by " + + words + + "\"}]"), + org.openmetadata.schema.tests.TestCase.class) + .getDescription()); + } + } + } + + static final String FROM_A_SHAPE = + "This test comes from a shape: its test definition, entity link and parameter values change" + + " only when the shape or the table bindings change. Its description, owners and tags" + + " can be edited, and it can be deleted"; + + /** The request is a 400 that says the test comes from a shape. */ + private static void assertShapeRefusal(final Runnable request) { + final OpenMetadataException refused = assertThrows(OpenMetadataException.class, request::run); + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains(FROM_A_SHAPE), refused.getMessage()); + } + + private static void replaceDefinition(final OpenMetadataClient who, final String path) { + final String other = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testDefinitions/name/tableRowCountToEqual", + null)) + .path("id") + .asText(); + who.getHttpClient() + .execute( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"replace\",\"path\":\"/testDefinition\",\"value\":{\"id\":\"" + + other + + "\",\"type\":\"testDefinition\"}}]"), + org.openmetadata.schema.tests.TestCase.class); + } + + private static org.openmetadata.schema.tests.TestCase getTest(final String id) { + return admin() + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/dataQuality/testCases/" + id + "?fields=*", + null, + org.openmetadata.schema.tests.TestCase.class); + } + + private static String parameter( + final org.openmetadata.schema.tests.TestCase test, final String name) { + return test.getParameterValues().stream() + .filter(value -> name.equals(value.getName())) + .findFirst() + .orElseThrow() + .getValue(); + } + + /** + * A PUT of the test as a person would send it: the stored name, link, definition and + * parameters, with {@code changed} given another value, or the description when it is null. + */ + private static org.openmetadata.schema.tests.TestCase put( + final OpenMetadataClient who, final String id, final String changed, final String value) { + final org.openmetadata.schema.tests.TestCase stored = getTest(id); + final List> parameters = new ArrayList<>(); + for (final var parameter : stored.getParameterValues()) { + parameters.add( + java.util.Map.of( + "name", + parameter.getName(), + "value", + parameter.getName().equals(changed) ? value : parameter.getValue())); } + final java.util.Map body = new java.util.LinkedHashMap<>(); + body.put("name", stored.getName()); + body.put("entityLink", stored.getEntityLink()); + body.put("testDefinition", stored.getTestDefinition().getFullyQualifiedName()); + body.put("parameterValues", parameters); + body.put("description", changed == null ? value : stored.getDescription()); + return who.getHttpClient() + .execute( + HttpMethod.PUT, + "/v1/dataQuality/testCases", + body, + org.openmetadata.schema.tests.TestCase.class); + } + + static void approve(final String taskId) { + admin() + .tasks() + .resolve(taskId, new ResolveTask().withResolutionType(TaskResolutionType.Approved)); } @Test @@ -586,4 +740,319 @@ void filterChange(final TestNamespace ns) { test.path("parameterValues").get(0).path("value").asText()); } } + + static final String NO_PROPOSAL = "{\"state\":\"none\"}"; + + /** The open tasks that propose a check of the class. */ + static List openTasks(final OntologyConcept account) { + final JsonNode all = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, "/v1/tasks?limit=1000&fields=payload,assignees", null)); + final List open = new ArrayList<>(); + for (final JsonNode task : all.path("data")) { + final String status = task.path("status").asText(); + if (("Open".equals(status) || "InProgress".equals(status) || "Pending".equals(status)) + && "TestCase".equals(task.path("payload").path("suggestionType").asText()) + && task.path("payload") + .path("suggestedValue") + .asText() + .contains(account.getId().toString())) { + open.add(task); + } + } + return open; + } + + private static String proposalOf(final OntologyConcept account, final String column) { + return JsonUtils.pojoToJson(checkOf(checks(account), column).getProposal()); + } + + private static void setConstraints( + final OntologyShape shape, + final List constraints) { + admin() + .ontologyShapes() + .update( + shape.getId(), + admin().ontologyShapes().get(shape.getId().toString()).withConstraints(constraints)); + } + + private static void deleteTest(final String id, final String query) { + admin() + .getHttpClient() + .executeForString(HttpMethod.DELETE, "/v1/dataQuality/testCases/" + id + query, null); + } + + @Test + void olderComesBack(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "older"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + final OntologyRelease first = release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + approve(checkOf(checks(account), "email").getProposal().getTask().getId().toString()); + final OntologyShapeCheck accepted = checkOf(checks(account), "email"); + final String testId = accepted.getProposal().getTestCase().getId().toString(); + admin() + .getHttpClient() + .executeForString( + HttpMethod.POST, + "/v1/dataQuality/testCases/testCaseResults/" + + java.net.URLEncoder.encode( + accepted.getProposal().getTestCase().getFullyQualifiedName(), + java.nio.charset.StandardCharsets.UTF_8), + java.util.Map.of( + "timestamp", + System.currentTimeMillis(), + "testCaseStatus", + "Failed", + "result", + "3 violations")); + setConstraints(shape, List.of()); + final OntologyRelease second = release(ns, ontology); + assertEquals(0, generatedTests(tableFqn)); + assertEquals(1, generated(tableFqn, "all").size()); + assertEquals( + "governance-bot", generated(tableFqn, "all").getFirst().path("updatedBy").asText()); + + activate(ontology, first); + + final List live = generated(tableFqn, "non-deleted"); + assertEquals(1, live.size()); + assertEquals(testId, live.getFirst().path("id").asText()); + assertEquals(0, openTasks(account).size()); + final OntologyShapeCheck back = checkOf(checks(account), "email"); + assertEquals(OntologyShapeCheckProposalState.ACCEPTED, back.getProposal().getState()); + assertEquals(testId, back.getProposal().getTestCase().getId().toString()); + assertEquals( + org.openmetadata.schema.tests.type.TestCaseStatus.Failed, + back.getProposal().getLatestResultStatus()); + + deleteTest(testId, "?recursive=true"); + assertEquals(0, generatedTests(tableFqn)); + assertEquals("admin", generated(tableFqn, "all").getFirst().path("updatedBy").asText()); + activate(ontology, second); + activate(ontology, first); + + assertEquals(NO_PROPOSAL, proposalOf(account, "email")); + assertEquals(0, openTasks(account).size()); + assertEquals(0, generatedTests(tableFqn)); + assertEquals(1, generated(tableFqn, "all").size()); + } + } + + @Test + void hardDeleted(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "harddelete"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + approve(checkOf(checks(account), "email").getProposal().getTask().getId().toString()); + final String testId = + checkOf(checks(account), "email").getProposal().getTestCase().getId().toString(); + + deleteTest(testId, "?hardDelete=true"); + OntologyCheckReconcileQueue.instance().afterActivation(ontology.getId(), "admin"); + settle(); + + assertEquals(0, openTasks(account).size()); + assertEquals(0, generated(tableFqn, "all").size()); + assertEquals(NO_PROPOSAL, proposalOf(account, "email")); + + setConstraints( + shape, + List.of(on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b", "c")))); + release(ns, ontology); + + assertEquals(1, openTasks(account).size()); + assertEquals(OntologyShapeCheckProposalState.PROPOSED, stateOf(account, "email")); + } + } + + @Test + void twoServers(final TestNamespace ns) throws Exception { + final Ontology ontology = createOntology(ns, "twoservers"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + + for (int attempt = 0; attempt < 8 && openTasks(account).size() < 2; attempt++) { + openTasks(account) + .forEach( + task -> + OntologyCheckReconcileAccess.cancel(UUID.fromString(task.path("id").asText()))); + runTwoServersAtOnce(ontology.getId()); + } + final List open = openTasks(account); + assertEquals(2, open.size()); + for (final JsonNode task : open) { + approve(task.path("id").asText()); + } + assertEquals(2, generatedTests(tableFqn)); + final String lowest = + generated(tableFqn, "non-deleted").stream() + .map(test -> test.path("id").asText()) + .sorted() + .findFirst() + .orElseThrow(); + + OntologyCheckReconcileQueue.instance().afterActivation(ontology.getId(), "admin"); + settle(); + + final List kept = generated(tableFqn, "non-deleted"); + assertEquals(1, kept.size()); + assertEquals(lowest, kept.getFirst().path("id").asText()); + assertEquals(2, generated(tableFqn, "all").size()); + + setConstraints( + shape, + List.of(on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b", "c")))); + release(ns, ontology); + + final List after = generated(tableFqn, "non-deleted"); + assertEquals(1, after.size()); + assertEquals(lowest, after.getFirst().path("id").asText()); + assertTrue( + after.getFirst().path("parameterValues").get(0).path("value").asText().contains("'c'")); + } + } + + private static void runTwoServersAtOnce(final UUID ontologyId) throws InterruptedException { + final CyclicBarrier together = new CyclicBarrier(2); + final List failures = java.util.Collections.synchronizedList(new ArrayList<>()); + final Runnable server = + () -> { + try { + together.await(60, TimeUnit.SECONDS); + OntologyCheckReconcileAccess.runAsAnotherServer(ontologyId); + } catch (final Exception failed) { + failures.add(failed); + } + }; + final Thread one = new Thread(server); + final Thread other = new Thread(server); + one.start(); + other.start(); + one.join(); + other.join(); + assertEquals(List.of(), failures); + } + + @Test + void otherClass(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "otherclass"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PARTIES).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "placed-by", "placedBy").withClassIri(fixture.type("Person").getIri())); + release(ns, ontology); + final OntologyConcept orders = fixture.type("Order"); + final String tableFqn = fixture.table("orders").getFullyQualifiedName(); + approve(checkOf(checks(orders), "party_id").getProposal().getTask().getId().toString()); + final String before = + generated(tableFqn, "non-deleted") + .getFirst() + .path("parameterValues") + .get(0) + .path("value") + .asText(); + final String testId = generated(tableFqn, "non-deleted").getFirst().path("id").asText(); + + final BindingSpec person = + fixture.shape().bindings().stream() + .filter(spec -> spec.type().equals("Person")) + .findFirst() + .orElseThrow(); + fixture.bind( + new BindingSpec( + person.type(), + person.table(), + person.role(), + person.key(), + new FilterSpec( + "kind", org.openmetadata.schema.type.OntologyRowFilterOperator.EQUALS, "human"), + person.columns())); + settle(); + + final List after = generated(tableFqn, "non-deleted"); + assertEquals(1, after.size()); + assertEquals(testId, after.getFirst().path("id").asText()); + final String now = after.getFirst().path("parameterValues").get(0).path("value").asText(); + assertNotEquals(before, now); + assertTrue(now.contains("human"), now); + assertEquals( + checkOf(checks(orders), "party_id").getParameterValues().getFirst().getValue(), now); + } + } + + @Test + void inARow(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "inarow"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + approve(checkOf(checks(account), "email").getProposal().getTask().getId().toString()); + final OntologyCheckReconcileQueue queue = OntologyCheckReconcileQueue.instance(); + + queue.afterActivation(ontology.getId(), "admin"); + queue.afterActivation(ontology.getId(), "admin"); + final BindingSpec spec = fixture.shape().bindings().getFirst(); + fixture.bind( + new BindingSpec( + spec.type(), + spec.table(), + spec.role(), + spec.key(), + new FilterSpec("email", NOT_EQUALS, "zz"), + spec.columns())); + settle(); + + final OntologyShapeCheck email = checkOf(checks(account), "email"); + final List tests = generated(tableFqn, "non-deleted"); + assertEquals(1, tests.size()); + assertEquals( + email.getParameterValues().getFirst().getValue(), + tests.getFirst().path("parameterValues").get(0).path("value").asText()); + assertTrue(email.getParameterValues().getFirst().getValue().contains("'zz'")); + assertEquals(OntologyShapeCheckProposalState.ACCEPTED, email.getProposal().getState()); + final OntologyShapeCheck age = checkOf(checks(account), "age"); + assertEquals(OntologyShapeCheckProposalState.PROPOSED, age.getProposal().getState()); + assertEquals(1, openTasks(account).size()); + final int written = queue.writesMade(ontology.getId()); + queue.afterActivation(ontology.getId(), "admin"); + settle(); + assertEquals(written, queue.writesMade(ontology.getId())); + } + } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index 3ceca9ab0c99..509d6f41c66c 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -24,6 +24,7 @@ import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.contributing; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declareKey; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.joined; @@ -282,6 +283,12 @@ private static Reads reads( * of a setting is not a read for the answer. */ private static List ofTheRequestThatReadTheBindings(final List issued) { + return ofTheAnsweringRequest(issued).stream() + .takeWhile(statement -> !readsProposals(statement)) + .toList(); + } + + private static List ofTheAnsweringRequest(final List issued) { final RequestLatencyContext.RequestContext answering = issued.stream() .filter(read -> read.statement().contains(BINDING_ROWS)) @@ -292,10 +299,83 @@ private static List ofTheRequestThatReadTheBindings(final List i .filter(read -> read.request() == answering) .map(Issued::statement) .filter(statement -> statement.startsWith(SELECT) && !statement.contains(SETTINGS)) - .takeWhile(statement -> !readsProposals(statement)) .toList(); } + /** + * The statements the answering request runs from the lookup of the tests and the suggestions of + * the checks on, which is what it reads for the proposal state of each check. + */ + private static int statementsAfterTheLookup(final OntologyConcept account) { + settleReconcile(); + checks(admin(), account, RELEASE); + final List issued = Collections.synchronizedList(new ArrayList<>()); + try (var ignored = + SqlQueryCounter.forRequests( + Entity.getJdbi(), + SELECT, + statement -> + issued.add( + new Issued( + RequestLatencyContext.getContext(), plain(statement.getRenderedSql()))))) { + checks(admin(), account, RELEASE); + } + return (int) + ofTheAnsweringRequest(List.copyOf(issued)).stream() + .dropWhile(statement -> !readsProposals(statement)) + .count(); + } + + /** + * One class with {@code constraints} checks on a table with no row, each proposed, or each + * accepted. The statements after the lookup are the same for any number of checks. + */ + private static int proposalReads( + final TestNamespace ns, final int constraints, final boolean accepted) { + final String size = "proposalReads" + constraints + (accepted ? "a" : "p"); + ns.setMethodId(size); + final Ontology ontology = createOntology(ns, size); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, OntologyShapeCheckProposalIT.ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, + fixture, + "AccountShape", + "Account", + IntStream.range(0, constraints) + .mapToObj( + constraint -> + on(fixture, "c" + constraint, "accountEmail") + .withIn(literals("v" + constraint))) + .toArray(OntologyShapeConstraint[]::new)); + OntologyShapeCheckProposalIT.release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + assertEquals(constraints, OntologyShapeCheckProposalIT.openTasks(account).size()); + if (accepted) { + OntologyShapeCheckProposalIT.openTasks(account) + .forEach(task -> OntologyShapeCheckProposalIT.approve(task.path("id").asText())); + } + return statementsAfterTheLookup(account); + } + } + + @Test + void theProposalsOfOneCheckAndOfFortyAreReadInTheSameStatementsWhetherProposedOrAccepted( + final TestNamespace ns) { + final List counts = + List.of( + proposalReads(ns, 1, false), + proposalReads(ns, 40, false), + proposalReads(ns, 1, true), + proposalReads(ns, 40, true)); + + assertEquals(counts.getFirst(), counts.get(1), counts.toString()); + assertEquals(counts.get(2), counts.get(3), counts.toString()); + assertEquals(List.of(5, 5, 32, 32), counts); + } + /** * The first statement of the lookup of the tests and the suggestions of the checks. It comes * after the compile and is what the rest of the request reads for each proposal it finds. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java new file mode 100644 index 000000000000..92ce9a196a36 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java @@ -0,0 +1,376 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declareKey; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.ACCOUNTS; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.approve; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.checkOf; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.checkOfConstraint; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.generated; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.hasTestSuite; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.listed; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.openTasks; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.ranged; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.release; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.api.teams.CreateTeam; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.teams.Role; +import org.openmetadata.schema.entity.teams.Team; +import org.openmetadata.schema.tests.type.TestCaseStatus; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; + +/** + * Who is asked to accept a proposed test, who may, and what a reader who may not view the task or + * the test is shown (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeProposalAskIT extends BaseOntologyApprovalIT { + private static final String DENIED = "operation CreateTests denied by role"; + + private static List assignees(final JsonNode task) { + final List names = new ArrayList<>(); + task.path("assignees").forEach(assignee -> names.add(assignee.path("name").asText())); + return names; + } + + private static void ownedBy(final String path, final String type, final EntityReference owner) { + admin() + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/owners\",\"value\":[{\"id\":\"" + + owner.getId() + + "\",\"type\":\"" + + type + + "\"}]}]")); + } + + private static Ontology ontologyWith(final TestNamespace ns, final String name) { + return createOntology(ns, name); + } + + private static JsonNode onlyTask(final OntologyConcept account) { + final List open = openTasks(account); + assertEquals(1, open.size()); + return open.getFirst(); + } + + private static OpenMetadataException refused(final OpenMetadataClient who, final String taskId) { + return assertThrows( + OpenMetadataException.class, + () -> + who.tasks() + .resolve( + taskId, new ResolveTask().withResolutionType(TaskResolutionType.Approved))); + } + + private static Role mayCreate(final RdfAccessFixtures access) { + return access.allowRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + } + + @Test + void teamMembers(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignteam"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("pra")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final OpenMetadataClient ok = + OntologyBindingFixtures.client(access.userToken("mok", List.of())); + final OpenMetadataClient denied = + OntologyBindingFixtures.client(access.userToken("mdeny", List.of(deny.getId()))); + final EntityReference okUser = OntologyBindingFixtures.readerReference(ok); + final EntityReference deniedUser = OntologyBindingFixtures.readerReference(denied); + final Team team = + admin() + .teams() + .create( + new CreateTeam() + .withName("team" + access.suffix()) + .withTeamType(CreateTeam.TeamType.GROUP) + .withUsers(List.of(okUser.getId(), deniedUser.getId()))); + try { + final String tableId = fixture.table("accounts").getId().toString(); + ownedBy("/v1/tables/" + tableId, "team", team.getEntityReference()); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final JsonNode task = onlyTask(account); + assertEquals(List.of(okUser.getName()), assignees(task)); + + final String taskId = task.path("id").asText(); + final OpenMetadataException refusal = refused(denied, taskId); + assertEquals(403, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains(DENIED), refusal.getMessage()); + assertEquals(0, generated(fixture.table("accounts").getFullyQualifiedName(), "all").size()); + assertFalse(hasTestSuite(tableId)); + + ok.tasks() + .resolve(taskId, new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + final List tests = + generated(fixture.table("accounts").getFullyQualifiedName(), "all"); + assertEquals(1, tests.size()); + assertEquals(okUser.getName(), tests.getFirst().path("updatedBy").asText()); + final String suiteId = tests.getFirst().path("testSuite").path("id").asText(); + final JsonNode suite = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testSuites/" + suiteId + "?fields=pipelines", + null)); + assertEquals(1, suite.path("pipelines").size()); + } finally { + admin().teams().delete(team.getId().toString()); + } + } + } + + @Test + void deniedOwner(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assigndenied"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prb")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final EntityReference deniedOwner = + OntologyBindingFixtures.readerReference( + OntologyBindingFixtures.client(access.userToken("odeny", List.of(deny.getId())))); + final EntityReference ontologyOwner = + OntologyBindingFixtures.readerReference( + OntologyBindingFixtures.client( + access.userToken("oont", List.of(mayCreate(access).getId())))); + ownedBy("/v1/tables/" + fixture.table("accounts").getId(), "user", deniedOwner); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ontologyOwner); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + + release(ns, ontology); + + assertEquals(List.of(ontologyOwner.getName()), assignees(onlyTask(fixture.type("Account")))); + } + } + + @Test + void noTableOwner(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignontology"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prc")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + for (final JsonNode task : openTasks(account)) { + assertEquals(List.of(), assignees(task)); + } + + final EntityReference ontologyOwner = + OntologyBindingFixtures.readerReference( + OntologyBindingFixtures.client( + access.userToken("oont", List.of(mayCreate(access).getId())))); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ontologyOwner); + final String emailTask = + checkOf(checks(account), "email").getProposal().getTask().getId().toString(); + OntologyShapeCheckProposalIT.cancel(emailTask); + OntologyShapeCheckProposalIT.cancel( + checkOf(checks(account), "age").getProposal().getTask().getId().toString()); + OntologyCheckReconcileQueue.instance().afterActivation(ontology.getId(), "admin"); + OntologyShapeCheckProposalIT.settle(); + + final List asked = openTasks(account); + assertEquals(2, asked.size()); + for (final JsonNode task : asked) { + assertEquals(List.of(ontologyOwner.getName()), assignees(task)); + } + } + } + + @Test + void lostTheRight(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignlost"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prd")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role allow = access.allowRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final OpenMetadataClient assignee = + OntologyBindingFixtures.client(access.userToken("assignee", List.of(allow.getId()))); + final EntityReference user = OntologyBindingFixtures.readerReference(assignee); + final String tableId = fixture.table("accounts").getId().toString(); + ownedBy("/v1/tables/" + tableId, "user", user); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final JsonNode task = onlyTask(fixture.type("Account")); + assertEquals(List.of(user.getName()), assignees(task)); + + admin() + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + "/v1/users/" + user.getId(), + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/roles/-\",\"value\":{\"id\":\"" + + deny.getId() + + "\",\"type\":\"role\"}}]")); + final String taskId = task.path("id").asText(); + final OpenMetadataException refusal = refused(assignee, taskId); + + assertEquals(403, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains(DENIED), refusal.getMessage()); + assertEquals(TaskEntityStatus.Open, admin().tasks().get(taskId).getStatus()); + assertEquals(0, generated(fixture.table("accounts").getFullyQualifiedName(), "all").size()); + assertFalse(hasTestSuite(tableId)); + } + } + + @Test + void blindReaders(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "readers"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures noTask = new RdfAccessFixtures("pre"); + RdfAccessFixtures noTest = new RdfAccessFixtures("prf")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, + fixture, + "AccountShape", + "Account", + on(fixture, "l1", "accountEmail").withIn(literals("a")), + on(fixture, "l2", "accountEmail").withIn(literals("b")), + on(fixture, "l3", "accountEmail").withIn(literals("c")), + ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + approve(taskOf(account, "l1")); + approve(taskOf(account, "age-range")); + admin() + .tasks() + .resolve( + taskOf(account, "l3"), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + final String ageTest = + proposalOf(admin(), account, "age-range").getTestCase().getFullyQualifiedName(); + admin() + .getHttpClient() + .executeForString( + HttpMethod.POST, + "/v1/dataQuality/testCases/testCaseResults/" + + java.net.URLEncoder.encode(ageTest, java.nio.charset.StandardCharsets.UTF_8), + Map.of( + "timestamp", 1_700_000_000_000L, "testCaseStatus", "Failed", "result", "3 hits")); + final OpenMetadataClient taskBlind = + OntologyBindingFixtures.client( + noTask.userToken( + "notask", List.of(noTask.denyRole(MetadataOperation.ALL, Entity.TASK).getId()))); + final OpenMetadataClient testBlind = + OntologyBindingFixtures.client( + noTest.userToken( + "notest", + List.of(noTest.denyRole(MetadataOperation.ALL, Entity.TEST_CASE).getId()))); + + assertEquals( + "{\"state\":\"accepted\",\"testCase\":{\"id\":\"" + + proposalOf(admin(), account, "l1").getTestCase().getId() + + "\",\"type\":\"testCase\",\"name\":\"" + + proposalOf(admin(), account, "l1").getTestCase().getName() + + "\",\"fullyQualifiedName\":\"" + + proposalOf(admin(), account, "l1").getTestCase().getFullyQualifiedName() + + "\",\"description\":" + + JsonUtils.pojoToJson( + proposalOf(admin(), account, "l1").getTestCase().getDescription()) + + ",\"displayName\":\"" + + proposalOf(admin(), account, "l1").getTestCase().getDisplayName() + + "\",\"deleted\":false}}", + json(proposalOf(admin(), account, "l1")).replaceAll(",\"href\":\"[^\"]*\"", "")); + assertEquals( + TestCaseStatus.Failed, proposalOf(admin(), account, "age-range").getLatestResultStatus()); + assertEquals( + 1_700_000_000_000L, proposalOf(admin(), account, "age-range").getLatestResultTimestamp()); + + assertEquals("{\"state\":\"proposed\"}", json(proposalOf(taskBlind, account, "l2"))); + assertEquals("{\"state\":\"rejected\"}", json(proposalOf(taskBlind, account, "l3"))); + assertNotNull(proposalOf(taskBlind, account, "l1").getTestCase()); + assertEquals( + TestCaseStatus.Failed, + proposalOf(taskBlind, account, "age-range").getLatestResultStatus()); + + assertEquals("{\"state\":\"accepted\"}", json(proposalOf(testBlind, account, "l1"))); + assertEquals("{\"state\":\"accepted\"}", json(proposalOf(testBlind, account, "age-range"))); + assertNull(proposalOf(testBlind, account, "age-range").getLatestResultStatus()); + assertNull(proposalOf(testBlind, account, "age-range").getLatestResultTimestamp()); + assertNotNull(proposalOf(testBlind, account, "l2").getTask()); + assertNotNull(proposalOf(testBlind, account, "l3").getTask()); + } + } + + private static String json(final Object proposal) { + return JsonUtils.pojoToJson(proposal); + } + + private static String taskOf(final OntologyConcept account, final String constraintId) { + return proposalOf(admin(), account, constraintId).getTask().getId().toString(); + } + + private static org.openmetadata.schema.api.data.OntologyShapeCheckProposal proposalOf( + final OpenMetadataClient reader, final OntologyConcept account, final String constraintId) { + return checkOfConstraint(reader, account, constraintId).getProposal(); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcileAccess.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcileAccess.java new file mode 100644 index 000000000000..59ea3699eb74 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcileAccess.java @@ -0,0 +1,40 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.util.UUID; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.TaskRepository; + +/** + * Lets an integration test run the reconcile of shape checks outside the queue of this server, as + * the queue of a second server would, and close a suggestion task the way a person who cancels it + * does. + */ +public final class OntologyCheckReconcileAccess { + private OntologyCheckReconcileAccess() {} + + /** One run over every class of the ontology, made by the calling thread. */ + public static OntologyCheckReconciler.Outcome runAsAnotherServer(final UUID ontologyId) { + return new OntologyCheckReconciler(Entity.getCollectionDAO(), Entity.getAuthorizer()) + .run(ontologyId, OntologyCheckReconciler.Scope.everything(), "admin"); + } + + public static void cancel(final UUID taskId) { + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final Task task = tasks.get(null, taskId, tasks.getFields("*")); + tasks.closeTaskAndCancelWorkflowRun(task, "admin", "Cancelled by a test"); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index 34553342dd96..049e86ebeca4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -359,12 +359,25 @@ public void setFieldsInBulk(Fields fields, java.util.List entities) { fetchAndSetFields(entities, fields); setInheritedFields(entities, fields); RelationIncludes defaultIncludes = RelationIncludes.fromInclude(NON_DELETED); + final Fields perTask = withoutBatched(fields); for (Task entity : entities) { - setFields(entity, fields, defaultIncludes); + setFields(entity, perTask, defaultIncludes); clearFieldsInternal(entity, fields); } } + /** The fields that {@code fetchAndSetFields} has already set for the whole list in one read. */ + private Fields withoutBatched(final Fields fields) { + final java.util.Set rest = new java.util.HashSet<>(fields.getFieldList()); + if (supportsDomains) { + rest.remove(Entity.FIELD_DOMAINS); + } + if (supportsReviewers) { + rest.remove(Entity.FIELD_REVIEWERS); + } + return new Fields(rest); + } + @Override public void clearFields(Task task, Fields fields) { task.setAssignees(fields.contains(FIELD_ASSIGNEES) ? task.getAssignees() : null); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index 171f0a8128aa..fd4df0950a44 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -877,6 +877,11 @@ public void setFullyQualifiedName(TestCase test) { public void prepare(TestCase test, boolean update) { if (!update) { GeneratedTestScope.requireUnsetOnCreate(test); + } else if (test.getGeneratedBy() != null) { + // Before the parameter checks, so a change to what the shape freezes says where the test + // comes from instead of which parameter it breaks. + GeneratedTestScope.requireUnchanged( + get(null, test.getId(), getFields(TEST_DEFINITION), ALL, false), test); } Table table = validateForWrite(test, update); // Create/resolve the basic test suite only after all validations pass. @@ -2104,6 +2109,10 @@ protected boolean shouldCompare(String fieldName) { @Transaction @Override public void entitySpecificUpdate(boolean consolidatingChanges) { + if (operation == Operation.PUT && updated.getGeneratedBy() == null) { + // A request body cannot carry generatedBy, so a PUT keeps the stored one. + updated.setGeneratedBy(original.getGeneratedBy()); + } GeneratedTestScope.requireUnchanged(original, updated); validateChangedConformance(); compareAndUpdate( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java index b36fccf1ce1a..b88cbb59a517 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java @@ -15,11 +15,13 @@ import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; -import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.api.data.OntologyCheckedConstraint; import org.openmetadata.schema.api.data.OntologyCheckedPart; import org.openmetadata.schema.api.data.OntologyCheckedShape; @@ -31,7 +33,6 @@ import org.openmetadata.schema.tests.TestCaseGeneratedBy; import org.openmetadata.schema.tests.type.TestCaseResult; import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.TaskEntityStatus; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -40,6 +41,7 @@ import org.openmetadata.service.jdbi3.TestCaseRepository; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.tasks.TestCaseSuggestion; +import org.openmetadata.service.util.EntityUtil.Fields; /** * Sets how each check of a class stands as a test on its table: accepted when a test generated from @@ -48,6 +50,9 @@ * never reveals what the caller cannot see (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). */ final class OntologyCheckProposals { + private static final int ID_CHUNK = 500; + private static final Fields WITH_RESULT = new Fields(Set.of(Entity.TEST_CASE_RESULT)); + private final CollectionDAO dao; private final OntologyBindingAccess catalog; @@ -56,47 +61,87 @@ final class OntologyCheckProposals { this.catalog = catalog; } - /** What exists for the checks of one class, keyed by check identity. */ - private record Held(Map tests, Map tasks) {} + /** What exists for the checks of one class, keyed by check identity, and what the caller sees. */ + private record Held( + Map tests, + Map tasks, + Set viewableTests, + Set viewableTasks) {} void mark(final Access access, final UUID classId, final List shapes) { - final Held held = held(classId); + final Held held = held(access, classId); for (final OntologyCheckedShape shape : shapes) { for (final OntologyCheckedConstraint constraint : listOrEmpty(shape.getConstraints())) { for (final OntologyCheckedPart part : listOrEmpty(constraint.getParts())) { for (final OntologyShapeCheck check : listOrEmpty(part.getChecks())) { - check.setProposal(proposal(access, held, check.getIdentity())); + check.setProposal(proposal(held, check.getIdentity())); } } } } } - private Held held(final UUID classId) { + /** + * Reads the tests and the tasks of the class by id list, one call each, and the latest results + * with the tests, so the statements do not grow with the checks. + */ + private Held held(final Access access, final UUID classId) { final TestCaseRepository tests = (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); final Map liveTests = new HashMap<>(); - for (final String id : dao.testCaseDAO().findGeneratedIdsOfClass(classId.toString())) { - final TestCase test = - Entity.getEntity(Entity.TEST_CASE, UUID.fromString(id), "", Include.ALL); - final TestCaseGeneratedBy by = test.getGeneratedBy(); - if (by != null - && classId.equals(by.getClass_().getId()) - && !Boolean.TRUE.equals(test.getDeleted())) { - liveTests.put(by.getIdentity(), test); + final List testIds = + dao.testCaseDAO().findGeneratedIdsOfClass(classId.toString()).stream() + .map(UUID::fromString) + .toList(); + for (final List chunk : chunks(testIds)) { + for (final TestCase test : tests.get(null, chunk, WITH_RESULT, Include.ALL)) { + final TestCaseGeneratedBy by = test.getGeneratedBy(); + if (by != null + && classId.equals(by.getClass_().getId()) + && !Boolean.TRUE.equals(test.getDeleted())) { + liveTests.put(by.getIdentity(), test); + } } } final Map byIdentity = new HashMap<>(); - for (final String id : dao.taskDAO().findTestCaseSuggestionIdsOfClass(classId.toString())) { - final Task task = Entity.getEntity(Entity.TASK, UUID.fromString(id), "", Include.ALL); - final TestCaseGeneratedBy by = - TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload())).getGeneratedBy(); - if (classId.equals(by.getClass_().getId())) { - byIdentity.merge(by.getIdentity(), task, OntologyCheckProposals::stronger); + final List taskIds = + dao.taskDAO().findTestCaseSuggestionIdsOfClass(classId.toString()).stream() + .map(UUID::fromString) + .toList(); + for (final List chunk : chunks(taskIds)) { + for (final Task task : tasks.get(null, chunk, Fields.EMPTY_FIELDS, Include.ALL)) { + final TestCaseGeneratedBy by = + TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload())) + .getGeneratedBy(); + if (classId.equals(by.getClass_().getId())) { + byIdentity.merge(by.getIdentity(), task, OntologyCheckProposals::stronger); + } } } - return new Held(liveTests, byIdentity); + return new Held( + liveTests, + byIdentity, + viewable(access, Entity.TEST_CASE, liveTests.values().stream().map(TestCase::getId)), + viewable(access, Entity.TASK, byIdentity.values().stream().map(Task::getId))); + } + + /** The ids among {@code ids} that the caller may view, one read for all of them. */ + private Set viewable( + final Access access, final String type, final java.util.stream.Stream ids) { + final Set viewable = new HashSet<>(); + for (final List chunk : chunks(ids.distinct().toList())) { + viewable.addAll(catalog.viewable(access, type, chunk).keySet()); + } + return viewable; + } + + private static List> chunks(final List all) { + final List> chunks = new ArrayList<>(); + for (int from = 0; from < all.size(); from += ID_CHUNK) { + chunks.add(all.subList(from, Math.min(all.size(), from + ID_CHUNK))); + } + return chunks; } /** An open task outranks a closed one, and a later one an earlier one. */ @@ -115,58 +160,42 @@ private static boolean open(final Task task) { || task.getStatus() == TaskEntityStatus.Pending; } - private OntologyShapeCheckProposal proposal( - final Access access, final Held held, final String identity) { + private OntologyShapeCheckProposal proposal(final Held held, final String identity) { final TestCase test = held.tests().get(identity); if (test != null) { - return accepted(access, test); + return accepted(held, test); } final Task task = held.tasks().get(identity); if (task != null && open(task)) { - return withTask(access, task, OntologyShapeCheckProposalState.PROPOSED); + return withTask(held, task, OntologyShapeCheckProposalState.PROPOSED); } if (task != null && task.getStatus() == TaskEntityStatus.Rejected) { - return withTask(access, task, OntologyShapeCheckProposalState.REJECTED); + return withTask(held, task, OntologyShapeCheckProposalState.REJECTED); } return new OntologyShapeCheckProposal().withState(OntologyShapeCheckProposalState.NONE); } - private OntologyShapeCheckProposal withTask( - final Access access, final Task task, final OntologyShapeCheckProposalState state) { + private static OntologyShapeCheckProposal withTask( + final Held held, final Task task, final OntologyShapeCheckProposalState state) { final OntologyShapeCheckProposal proposal = new OntologyShapeCheckProposal().withState(state); - if (mayView(access, Entity.TASK, task.getId())) { + if (held.viewableTasks().contains(task.getId())) { proposal.setTask(task.getEntityReference()); } return proposal; } - private OntologyShapeCheckProposal accepted(final Access access, final TestCase test) { + private static OntologyShapeCheckProposal accepted(final Held held, final TestCase test) { final OntologyShapeCheckProposal proposal = new OntologyShapeCheckProposal().withState(OntologyShapeCheckProposalState.ACCEPTED); - if (!mayView(access, Entity.TEST_CASE, test.getId())) { + if (!held.viewableTests().contains(test.getId())) { return proposal; } proposal.setTestCase(test.getEntityReference()); - final TestCaseResult latest = - Entity.getEntity( - Entity.TEST_CASE, test.getId(), "testCaseResult", Include.NON_DELETED) - .getTestCaseResult(); + final TestCaseResult latest = test.getTestCaseResult(); if (latest != null) { proposal.setLatestResultStatus(latest.getTestCaseStatus()); proposal.setLatestResultTimestamp(latest.getTimestamp()); } return proposal; } - - private boolean mayView(final Access access, final String type, final UUID id) { - try { - final EntityInterface entity = - catalog.authorized(access, type, id, MetadataOperation.VIEW_BASIC); - return entity != null; - } catch (final RuntimeException denied) { - // A caller that cannot read the task or the test gets the state without it, whatever the - // reason. - return false; - } - } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java index ba2e4dcecf47..1a09be1fe5f1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java @@ -611,11 +611,15 @@ private void updateTest(final String user, final UUID testId, final Planned plan user); } - /** Deletes as the governance bot, which is how a later run tells this delete from a person's. */ + /** + * Deletes as the governance bot, which is how a later run tells this delete from a person's. It + * is recursive because a test with a failed result has an incident under it, which a plain delete + * refuses. + */ private void deleteTest(final UUID testId) { final TestCaseRepository tests = (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); - tests.delete(DELETE_AS, testId, false, false); + tests.delete(DELETE_AS, testId, true, false); } private void restoreTest(final UUID testId) { @@ -627,16 +631,20 @@ private void restoreTest(final UUID testId) { // ---- who is asked ------------------------------------------------------------------------ /** - * The owners of the table, else the owners of the ontology, as the users who may create tests on - * the table. A team stands for its users, and a user who lacks the right is left out. + * The owners of the table who may create tests on it, else the owners of the ontology who may. A + * team stands for its users, and a user who lacks the right is left out. */ private List assignees(final UUID ontologyId, final Table table) { - List owners = listOrEmpty(table.getOwners()); - if (owners.isEmpty()) { - final Ontology ontology = - Entity.getEntity(Entity.ONTOLOGY, ontologyId, "owners", Include.NON_DELETED); - owners = listOrEmpty(ontology.getOwners()); + final List fromTable = mayCreate(listOrEmpty(table.getOwners()), table); + if (!fromTable.isEmpty()) { + return fromTable; } + final Ontology ontology = + Entity.getEntity(Entity.ONTOLOGY, ontologyId, "owners", Include.NON_DELETED); + return mayCreate(listOrEmpty(ontology.getOwners()), table); + } + + private List mayCreate(final List owners, final Table table) { final Map users = new LinkedHashMap<>(); for (final EntityReference owner : owners) { for (final EntityReference user : usersOf(owner)) { From 29574e631dd22d4d0ac87547f3417141096004d3 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 09:18:21 -0800 Subject: [PATCH 159/203] docs: the record's guard names the governance bot --- ...-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index be83983b51db..4464cd436cd9 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-12-01 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted that comes back and a hard delete, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read) +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, and a hard delete, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read) - **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) ## Context From efdf1dfa3f274e4f65772ae6cf021f3120bc8d11 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 10:14:48 -0800 Subject: [PATCH 160/203] Test that a list of tasks returns each task's reviewers and domains as a read by id does, and import the collections the bulk read uses --- .../openmetadata/it/tests/TaskResourceIT.java | 66 +++++++++++++++++++ .../service/jdbi3/TaskRepository.java | 5 +- 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index f9134f41325a..e3451a0527c0 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -1386,6 +1386,72 @@ void testCreatedEndpointSupportsStatusFilter(TestNamespace ns) { "Cancelled created tasks should not include open task"); } + @Test + void testListReturnsEachTasksReviewersAndDomainsAsAGetByIdDoes(TestNamespace ns) { + SharedEntities shared = SharedEntities.get(); + Domain domainA = createDomain(ns, "bulk-fields-domain-a"); + Domain domainB = createDomain(ns, "bulk-fields-domain-b"); + Table tableInDomainA = + createTableWithDomainAndOwners(ns, domainA.getEntityReference(), List.of(shared.USER1_REF)); + Table tableInDomainB = + createTableWithDomainAndOwners(ns, domainB.getEntityReference(), List.of(shared.USER1_REF)); + Task taskA = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "bulk-fields-a", tableInDomainA) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName())) + .withReviewers(List.of(shared.USER2.getFullyQualifiedName()))); + Task taskB = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "bulk-fields-b", tableInDomainB) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName())) + .withReviewers(List.of(shared.USER3.getFullyQualifiedName()))); + + ListResponse listed = + SdkClients.user1Client() + .tasks() + .listAssigned( + null, + "open", + domainA.getFullyQualifiedName() + "," + domainB.getFullyQualifiedName(), + "reviewers,domains"); + + Task listedA = taskIn(listed, taskA); + Task listedB = taskIn(listed, taskB); + assertEquals( + List.of(shared.USER2.getName()), + listedA.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + List.of(domainA.getFullyQualifiedName()), + listedA.getDomains().stream().map(EntityReference::getFullyQualifiedName).toList()); + assertEquals( + List.of(shared.USER3.getName()), + listedB.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + List.of(domainB.getFullyQualifiedName()), + listedB.getDomains().stream().map(EntityReference::getFullyQualifiedName).toList()); + for (Task listedTask : List.of(listedA, listedB)) { + Task byId = + SdkClients.adminClient().tasks().get(listedTask.getId().toString(), "reviewers,domains"); + assertEquals( + byId.getReviewers().stream().map(EntityReference::getName).toList(), + listedTask.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + byId.getDomains().stream().map(EntityReference::getName).toList(), + listedTask.getDomains().stream().map(EntityReference::getName).toList()); + } + } + + private static Task taskIn(ListResponse listed, Task wanted) { + return listed.getData().stream() + .filter(task -> task.getId().equals(wanted.getId())) + .findFirst() + .orElseThrow(() -> new AssertionError("task " + wanted.getName() + " is not in the list")); + } + @Test void testAssignedEndpointSupportsStatusGroupAndDomainFilter(TestNamespace ns) { SharedEntities shared = SharedEntities.get(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index 049e86ebeca4..b58864e9f2e5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -29,6 +29,7 @@ import jakarta.ws.rs.core.UriInfo; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -352,7 +353,7 @@ public void setFields(Task task, Fields fields, RelationIncludes relationInclude } @Override - public void setFieldsInBulk(Fields fields, java.util.List entities) { + public void setFieldsInBulk(Fields fields, List entities) { if (entities == null || entities.isEmpty()) { return; } @@ -368,7 +369,7 @@ public void setFieldsInBulk(Fields fields, java.util.List entities) { /** The fields that {@code fetchAndSetFields} has already set for the whole list in one read. */ private Fields withoutBatched(final Fields fields) { - final java.util.Set rest = new java.util.HashSet<>(fields.getFieldList()); + final Set rest = new HashSet<>(fields.getFieldList()); if (supportsDomains) { rest.remove(Entity.FIELD_DOMAINS); } From 4181e04a644ff3bf9468f6dc0562f3f2d8569c70 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 10:15:00 -0800 Subject: [PATCH 161/203] Count a restore of a test the reconcile deleted as a restore, and show that such a test comes back with its incident as it was --- .../tests/OntologyShapeCheckProposalIT.java | 46 +++++++++ .../ontology/OntologyCheckReconcileQueue.java | 15 ++- .../ontology/OntologyCheckReconciler.java | 97 +++++++++++-------- .../OntologyCheckReconciliationTest.java | 40 ++++++++ 4 files changed, 155 insertions(+), 43 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java index 8e58bee93503..4832abd0ff84 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java @@ -13,6 +13,7 @@ package org.openmetadata.it.tests; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -58,11 +59,13 @@ import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; import org.openmetadata.schema.api.data.OntologyShapeChecks; import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.api.tests.CreateTestCaseResolutionStatus; import org.openmetadata.schema.entity.data.Ontology; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyRelease; import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; import org.openmetadata.schema.type.TaskEntityStatus; import org.openmetadata.schema.type.TaskResolutionType; import org.openmetadata.schema.utils.JsonUtils; @@ -72,6 +75,7 @@ import org.openmetadata.service.Entity; import org.openmetadata.service.ontology.OntologyCheckReconcileAccess; import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Outcome; import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; @@ -786,6 +790,30 @@ private static void deleteTest(final String id, final String query) { .executeForString(HttpMethod.DELETE, "/v1/dataQuality/testCases/" + id + query, null); } + /** The incidents of a test as "stateId type", one for each incident, at their latest state. */ + private static List incidents(final String testFqn) { + final JsonNode data = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testCases/testCaseIncidentStatus?testCaseFQN=" + + java.net.URLEncoder.encode( + testFqn, java.nio.charset.StandardCharsets.UTF_8) + + "&latest=true&limit=10", + null)); + final List found = new ArrayList<>(); + data.path("data") + .forEach( + one -> + found.add( + one.path("stateId").asText() + + " " + + one.path("testCaseResolutionStatusType").asText())); + return found; + } + @Test void olderComesBack(final TestNamespace ns) { final Ontology ontology = createOntology(ns, "older"); @@ -816,6 +844,17 @@ void olderComesBack(final TestNamespace ns) { "Failed", "result", "3 violations")); + final String testFqn = accepted.getProposal().getTestCase().getFullyQualifiedName(); + await().atMost(30, TimeUnit.SECONDS).until(() -> incidents(testFqn).size() == 1); + admin() + .testCaseResolutionStatuses() + .create( + new CreateTestCaseResolutionStatus() + .withTestCaseResolutionStatusType(TestCaseResolutionStatusTypes.Ack) + .withTestCaseReference(testFqn)); + final List incidentBefore = incidents(testFqn); + assertEquals(1, incidentBefore.size()); + assertTrue(incidentBefore.getFirst().endsWith(" Ack"), incidentBefore.toString()); setConstraints(shape, List.of()); final OntologyRelease second = release(ns, ontology); assertEquals(0, generatedTests(tableFqn)); @@ -835,6 +874,13 @@ void olderComesBack(final TestNamespace ns) { assertEquals( org.openmetadata.schema.tests.type.TestCaseStatus.Failed, back.getProposal().getLatestResultStatus()); + assertEquals(incidentBefore, incidents(testFqn)); + final Outcome restored = + OntologyCheckReconcileQueue.instance().outcomeSoFar(ontology.getId()); + assertEquals(1, restored.deleted()); + assertEquals(1, restored.restored()); + assertEquals(0, restored.updated()); + assertEquals(0, restored.refused()); deleteTest(testId, "?recursive=true"); assertEquals(0, generatedTests(tableFqn)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java index bd8736bfc860..d65299da7456 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java @@ -43,7 +43,7 @@ public final class OntologyCheckReconcileQueue { private final ExecutorService executor; private final Map pending = new HashMap<>(); private final Set running = new HashSet<>(); - private final Map writes = new HashMap<>(); + private final Map totals = new HashMap<>(); private record Pending(Scope scope, String user) { Pending merge(final Pending later) { @@ -115,7 +115,7 @@ private void run(final UUID ontologyId, final Pending request) { try { final Outcome outcome = reconciler.run(ontologyId, request.scope(), request.user()); synchronized (this) { - writes.merge(ontologyId, outcome.writes(), Integer::sum); + totals.merge(ontologyId, outcome, Outcome::plus); } LOG.info("[OntologyChecks] Reconciled ontology {}: {}", ontologyId, outcome); } catch (final RuntimeException failed) { @@ -123,9 +123,14 @@ private void run(final UUID ontologyId, final Pending request) { } } - /** The writes that the jobs of an ontology have made on this server so far. */ - public synchronized int writesMade(final UUID ontologyId) { - return writes.getOrDefault(ontologyId, 0); + /** The writes that the jobs of an ontology have made on this server so far, by kind. */ + public synchronized Outcome outcomeSoFar(final UUID ontologyId) { + return totals.getOrDefault(ontologyId, Outcome.NONE); + } + + /** How many writes the jobs of an ontology have made on this server so far. */ + public int writesMade(final UUID ontologyId) { + return outcomeSoFar(ontologyId).writes(); } /** Waits until no job runs or waits, and says whether that happened within the time. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java index 1a09be1fe5f1..5b2db0fde38d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java @@ -147,11 +147,48 @@ Scope merge(final Scope other) { } } - /** The writes a run made, by kind. */ + /** The writes a run made, by kind, and the failures it counted as refused. */ public record Outcome( - int created, int replaced, int cancelled, int updated, int deleted, int refused) { + int created, + int replaced, + int cancelled, + int updated, + int restored, + int deleted, + int refused) { + static final Outcome NONE = new Outcome(0, 0, 0, 0, 0, 0, 0); + public int writes() { - return created + replaced + cancelled + updated + deleted; + return created + replaced + cancelled + updated + restored + deleted; + } + + Outcome plus(final Outcome other) { + return new Outcome( + created + other.created, + replaced + other.replaced, + cancelled + other.cancelled, + updated + other.updated, + restored + other.restored, + deleted + other.deleted, + refused + other.refused); + } + + /** What the writes that were made add up to, by kind. */ + static Outcome tally(final List made, final int refused) { + return made.stream() + .map(Outcome::one) + .reduce(new Outcome(0, 0, 0, 0, 0, 0, refused), Outcome::plus); + } + + private static Outcome one(final Write write) { + return switch (write) { + case CreateTask ignored -> new Outcome(1, 0, 0, 0, 0, 0, 0); + case ReplaceTask ignored -> new Outcome(0, 1, 0, 0, 0, 0, 0); + case CancelTask ignored -> new Outcome(0, 0, 1, 0, 0, 0, 0); + case UpdateTest ignored -> new Outcome(0, 0, 0, 1, 0, 0, 0); + case RestoreTest ignored -> new Outcome(0, 0, 0, 0, 1, 0, 0); + case DeleteTest ignored -> new Outcome(0, 0, 0, 0, 0, 1, 0); + }; } } @@ -169,7 +206,7 @@ Outcome run(final UUID ontologyId, final Scope scope, final String user) { try (FreshReadScope.Handle ignored = FreshReadScope.enter()) { final Optional active = activeRelease(ontologyId); if (active.isEmpty()) { - return new Outcome(0, 0, 0, 0, 0, 0); + return Outcome.NONE; } final Map tests = generatedTests(); final Map tasks = suggestions(); @@ -448,46 +485,30 @@ private Outcome execute( final Map found, final Map tests, final Map tasks) { - final int[] counts = new int[7]; + final List made = new ArrayList<>(); + int failed = 0; for (final Write write : writes) { try { switch (write) { - case CreateTask create -> { - createTask(ontologyId, user, planned(found, create.classId(), create.identity())); - counts[0]++; - } - case ReplaceTask replace -> { - replaceTask( - user, replace.taskId(), planned(found, replace.classId(), replace.identity())); - counts[1]++; - } - case CancelTask cancel -> { - cancelTask(user, cancel); - counts[2]++; - } - case UpdateTest update -> { - updateTest(user, update.testId(), planned(found, update.classId(), update.identity())); - counts[3]++; - } - case DeleteTest delete -> { - deleteTest(delete.testId()); - counts[4]++; - } - case RestoreTest restore -> { - restoreTest(restore.testId()); - counts[6]++; - } + case CreateTask create -> createTask( + ontologyId, user, planned(found, create.classId(), create.identity())); + case ReplaceTask replace -> replaceTask( + user, replace.taskId(), planned(found, replace.classId(), replace.identity())); + case CancelTask cancel -> cancelTask(user, cancel); + case UpdateTest update -> updateTest( + user, update.testId(), planned(found, update.classId(), update.identity())); + case DeleteTest delete -> deleteTest(delete.testId()); + case RestoreTest restore -> restoreTest(restore.testId()); } - } catch (final RuntimeException failed) { - counts[5]++; - LOG.warn("[OntologyChecks] A write of the reconcile failed: {}", write, failed); + made.add(write); + } catch (final RuntimeException failure) { + failed++; + LOG.warn("[OntologyChecks] A write of the reconcile failed: {}", write, failure); } } - found.values().stream() - .filter(one -> one.decision() instanceof Refused) - .forEach(one -> counts[5]++); - return new Outcome( - counts[0], counts[1], counts[2], counts[3] + counts[6], counts[4], counts[5]); + final long refusedCompiles = + found.values().stream().filter(one -> one.decision() instanceof Refused).count(); + return Outcome.tally(made, failed + (int) refusedCompiles); } private static Planned planned( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java index c4f9a3a7e769..3c1ebf64c0ff 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java @@ -20,6 +20,7 @@ import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.Test; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Outcome; import org.openmetadata.service.ontology.OntologyCheckReconciliation.Binding; import org.openmetadata.service.ontology.OntologyCheckReconciliation.CancelTask; import org.openmetadata.service.ontology.OntologyCheckReconciliation.Checks; @@ -285,6 +286,45 @@ void aTestTheReconcileDeletedComesBackWhenItsCheckIsWantedAgain() { assertEquals(List.of(new RestoreTest(ID_1)), writes); } + @Test + void aRestoreIsReportedAsARestoreAndNotAsAnUpdate() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + + assertEquals(new Outcome(0, 0, 0, 0, 1, 0, 0), Outcome.tally(writes, 0)); + } + + @Test + void aRestoreThatAlsoChangedTheContentIsReportedAsARestoreAndAnUpdate() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_4))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + + assertEquals(new Outcome(0, 0, 0, 1, 1, 0, 0), Outcome.tally(writes, 0)); + } + + @Test + void everyKindOfWriteIsCountedOnceAndTheRefusedCountIsKept() { + final List writes = + List.of( + new CreateTask(CLASS, "a"), + new ReplaceTask(ID_2, CLASS, "b"), + new CancelTask(ID_3, "gone"), + new UpdateTest(ID_1, CLASS, "c"), + new RestoreTest(ID_4), + new DeleteTest(ID_1)); + + final Outcome outcome = Outcome.tally(writes, 2); + + assertEquals(new Outcome(1, 1, 1, 1, 1, 1, 2), outcome); + assertEquals(6, outcome.writes()); + } + @Test void aTestTheReconcileDeletedComesBackUpdatedWhenItsContentChanged() { final List writes = From 6a74f59584287a749fe7ab6380c93d4dc19dbdb2 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 10:15:06 -0800 Subject: [PATCH 162/203] Say in the record who is asked to approve a proposed test, and test a table that no one who owns it may approve --- ...ck-reaches-its-table-as-a-proposed-test.md | 20 +++-- .../it/tests/OntologyShapeProposalAskIT.java | 86 +++++++++++++++++++ 2 files changed, 97 insertions(+), 9 deletions(-) diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index 4464cd436cd9..6a9b4727a0af 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -22,14 +22,15 @@ to find every test they made and change it by hand. **A check is proposed before it is a test.** The server files one suggestion task for each check (`suggestionType` `TestCase`, `fieldPath` `testCases`), about the table the check belongs to. -Approving it creates the test case as the approver, so the approver needs `CreateTests` on the -table, as a request to create a test case does. Rejecting creates nothing. The task is assigned to -the owners of the table, else the owners of the ontology, else nobody. A team stands for its users, -and a user who may not create tests on the table is left out. A task filed with nobody takes the -owners of the table, as every task does. The approver needs `CreateTests` on the table and the right -to resolve the task, which the assignees, the owners of the table and the administrators have. A -task with no owner on the table or the ontology has no assignee, so only an administrator, or a user -whose role grants `ResolveTask`, can approve it. Its source is `Ingestion`, because a deterministic +Approving it creates the test case as the approver. So the approver needs `CreateTests` on the +table, as a request to create a test case does, and the right to resolve the task, which the +assignees, the owners of the table and the administrators have. Rejecting creates nothing. The +reconcile assigns the task to the owners of the table who may create tests on it, and when none +of them may, to the owners of the ontology who may. A team stands for its users. When nobody +qualifies, the task is filed with no assignee, and the server gives it to the owners of the +table, as it does any task filed with no assignee. Those owners may reject the task but may not +approve it, so an administrator approves it. A table with no owner leaves such a task with no +assignee, and an administrator resolves it. Its source is `Ingestion`, because a deterministic compile of a shape wrote it, and no agent or model did. **A test is not kept in a review state.** The runner reads every test case of a suite and no status of @@ -56,7 +57,8 @@ reconcile set it. **The reconcile.** A background job compiles the checks of each class in scope, for no caller, so it reads every shape, property and table and masks nothing (the answer a person gets is a masked view of -the same compile, and a step that creates tests must never read a hidden constraint as absent). For each check it does the first of these that applies: +the same compile, and a step that creates tests must never read a hidden constraint as absent). +For each check it does the first of these that applies: | What exists for the check | What the reconcile does | |---|---| diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java index 92ce9a196a36..3b070eee650c 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java @@ -40,11 +40,13 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.openmetadata.it.util.RdfAccessFixtures; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; import org.openmetadata.schema.api.tasks.ResolveTask; import org.openmetadata.schema.api.teams.CreateTeam; import org.openmetadata.schema.entity.data.Ontology; @@ -239,6 +241,90 @@ void noTableOwner(final TestNamespace ns) { } } + @Test + void noOneMay(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignnone"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prg")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final OpenMetadataClient tableOwner = + OntologyBindingFixtures.client(access.userToken("tdeny", List.of(deny.getId()))); + final EntityReference tableOwnerUser = OntologyBindingFixtures.readerReference(tableOwner); + final EntityReference ontologyOwnerUser = + OntologyBindingFixtures.readerReference( + OntologyBindingFixtures.client(access.userToken("odeny", List.of(deny.getId())))); + final String tableId = fixture.table("accounts").getId().toString(); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + ownedBy("/v1/tables/" + tableId, "user", tableOwnerUser); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ontologyOwnerUser); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + + release(ns, ontology); + + final OntologyConcept account = fixture.type("Account"); + final List filed = openTasks(account); + assertEquals(2, filed.size()); + for (final JsonNode task : filed) { + assertEquals(List.of(tableOwnerUser.getName()), assignees(task)); + } + final String emailTask = taskOf(account, "email-listed"); + final String ageTask = taskOf(account, "age-range"); + + final OpenMetadataException refusal = refused(tableOwner, emailTask); + assertEquals(403, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains(DENIED), refusal.getMessage()); + assertEquals(TaskEntityStatus.Open, admin().tasks().get(emailTask).getStatus()); + assertEquals(0, generated(tableFqn, "all").size()); + assertFalse(hasTestSuite(tableId)); + + approve(ageTask); + assertEquals(1, generated(tableFqn, "all").size()); + assertTrue(hasTestSuite(tableId)); + } + } + + /** + * The record says the owners of the table may reject a task they may not approve. A reject is a + * resolve, and a resolve asks for the right of the task's operation on the table, so this answers + * 403 today. Disabled until the record or the rule is changed. + */ + @Disabled("answers 403: a resolve of any kind asks for CreateTests on the table") + @Test + void deniedOwnerMayReject(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignreject"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prh")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final OpenMetadataClient tableOwner = + OntologyBindingFixtures.client(access.userToken("rdeny", List.of(deny.getId()))); + ownedBy( + "/v1/tables/" + fixture.table("accounts").getId(), + "user", + OntologyBindingFixtures.readerReference(tableOwner)); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + + tableOwner + .tasks() + .resolve( + taskOf(account, "email-listed"), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals( + OntologyShapeCheckProposalState.REJECTED, + proposalOf(admin(), account, "email-listed").getState()); + assertEquals(0, generated(fixture.table("accounts").getFullyQualifiedName(), "all").size()); + } + } + @Test void lostTheRight(final TestNamespace ns) { final Ontology ontology = ontologyWith(ns, "assignlost"); From 04e250b5e247cd6b8e4a7209a0a48849a9c481e9 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 12:59:29 -0800 Subject: [PATCH 163/203] Test that the owner of a table who is denied CreateTests cannot reject a proposed test either, and that the task's source is Ingestion --- .../it/tests/OntologyShapeProposalAskIT.java | 55 ++++++++++++------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java index 3b070eee650c..c78ca4f2e6f1 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java @@ -40,13 +40,11 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.openmetadata.it.util.RdfAccessFixtures; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; -import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; import org.openmetadata.schema.api.tasks.ResolveTask; import org.openmetadata.schema.api.teams.CreateTeam; import org.openmetadata.schema.entity.data.Ontology; @@ -100,6 +98,7 @@ private static Ontology ontologyWith(final TestNamespace ns, final String name) private static JsonNode onlyTask(final OntologyConcept account) { final List open = openTasks(account); assertEquals(1, open.size()); + assertEquals("Ingestion", open.getFirst().path("payload").path("source").asText()); return open.getFirst(); } @@ -287,14 +286,8 @@ void noOneMay(final TestNamespace ns) { } } - /** - * The record says the owners of the table may reject a task they may not approve. A reject is a - * resolve, and a resolve asks for the right of the task's operation on the table, so this answers - * 403 today. Disabled until the record or the rule is changed. - */ - @Disabled("answers 403: a resolve of any kind asks for CreateTests on the table") @Test - void deniedOwnerMayReject(final TestNamespace ns) { + void deniedOwnerMayNotReject(final TestNamespace ns) { final Ontology ontology = ontologyWith(ns, "assignreject"); try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); @@ -304,24 +297,44 @@ void deniedOwnerMayReject(final TestNamespace ns) { final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); final OpenMetadataClient tableOwner = OntologyBindingFixtures.client(access.userToken("rdeny", List.of(deny.getId()))); - ownedBy( - "/v1/tables/" + fixture.table("accounts").getId(), - "user", - OntologyBindingFixtures.readerReference(tableOwner)); + final String tableId = fixture.table("accounts").getId().toString(); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + final EntityReference ownerUser = OntologyBindingFixtures.readerReference(tableOwner); + ownedBy("/v1/tables/" + tableId, "user", ownerUser); declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); release(ns, ontology); final OntologyConcept account = fixture.type("Account"); + final String taskId = taskOf(account, "email-listed"); + + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + tableOwner + .tasks() + .resolve( + taskId, + new ResolveTask().withResolutionType(TaskResolutionType.Rejected))); - tableOwner + assertEquals(403, refusal.getStatusCode()); + assertEquals( + "Principal: CatalogPrincipal{name='" + + ownerUser.getName() + + "'} operation CreateTests denied by role " + + deny.getName() + + ", policy " + + deny.getName().replace("Role", "Policy") + + ", rule prhdeny", + refusal.getMessage()); + assertEquals(TaskEntityStatus.Open, admin().tasks().get(taskId).getStatus()); + + admin() .tasks() - .resolve( - taskOf(account, "email-listed"), - new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + .resolve(taskId, new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); - assertEquals( - OntologyShapeCheckProposalState.REJECTED, - proposalOf(admin(), account, "email-listed").getState()); - assertEquals(0, generated(fixture.table("accounts").getFullyQualifiedName(), "all").size()); + assertEquals(TaskEntityStatus.Rejected, admin().tasks().get(taskId).getStatus()); + assertEquals(0, generated(tableFqn, "all").size()); + assertFalse(hasTestSuite(tableId)); } } From 9178df6d0a70feb18060a6bc3ad26e627bf8011d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 12:59:46 -0800 Subject: [PATCH 164/203] Say in the record that a resolve of either kind asks for the right to create the test --- ...ck-reaches-its-table-as-a-proposed-test.md | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index 6a9b4727a0af..ad38c7044556 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -22,16 +22,19 @@ to find every test they made and change it by hand. **A check is proposed before it is a test.** The server files one suggestion task for each check (`suggestionType` `TestCase`, `fieldPath` `testCases`), about the table the check belongs to. -Approving it creates the test case as the approver. So the approver needs `CreateTests` on the -table, as a request to create a test case does, and the right to resolve the task, which the -assignees, the owners of the table and the administrators have. Rejecting creates nothing. The -reconcile assigns the task to the owners of the table who may create tests on it, and when none -of them may, to the owners of the ontology who may. A team stands for its users. When nobody -qualifies, the task is filed with no assignee, and the server gives it to the owners of the -table, as it does any task filed with no assignee. Those owners may reject the task but may not -approve it, so an administrator approves it. A table with no owner leaves such a task with no -assignee, and an administrator resolves it. Its source is `Ingestion`, because a deterministic -compile of a shape wrote it, and no agent or model did. +Approving it creates the test case as the approver, and rejecting it creates nothing. A resolve of +either kind needs the right to resolve the task, which the assignees, the owners of the table and +the administrators have. As for any task that changes an entity, the server also asks on every +resolve for the right to make the change, here `CreateTests` or `EditAll` on the table +(`TaskRepository.validateUnderlyingEntityPermission`). A denial of `CreateTests` refuses that check +whatever else is allowed (`DefaultAuthorizer.authorizeRequests`). The reconcile assigns the task to +the owners of the table who may create tests on it, and when none of them may, to the owners of the +ontology who may. A team stands for its users. When nobody qualifies, the task is filed with no +assignee, and the server gives it to the owners of the table, as it does any task filed with no +assignee. An owner denied `CreateTests` may then neither approve nor reject it, so an administrator +resolves it. A table with no owner leaves such a task with no assignee, and an administrator +resolves it. Its source is `Ingestion`, because a deterministic compile of a shape wrote it, and no +agent or model did. **A test is not kept in a review state.** The runner reads every test case of a suite and no status of it, so a test that waits for a decision would run. The proposal is the task and the test does not From fc2ccdbda9cf587991b0f9c2819b6eb09178a52d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 22:28:35 -0800 Subject: [PATCH 165/203] File a proposed test as the governance bot, so the person whose change started the run may resolve it --- .../it/tests/OntologyShapeFixture.java | 14 ++- .../it/tests/OntologyShapeProposalAskIT.java | 101 ++++++++++++++++++ .../ontology/OntologyCheckReconciler.java | 9 +- 3 files changed, 118 insertions(+), 6 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java index d91733ee141e..d0dbe89b4c57 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java @@ -245,12 +245,22 @@ OntologyProperty property(final String name) { /** Writes every binding of the shape, in the order the shape lists them. */ OntologyShapeFixture bindAll() { - shape.bindings().forEach(this::bind); + return bindAll(admin()); + } + + /** Writes every binding of the shape as {@code writer}. */ + OntologyShapeFixture bindAll(final OpenMetadataClient writer) { + shape.bindings().forEach(spec -> bind(writer, spec)); return this; } /** Writes one binding of the shape, or a changed copy of one, over what the class binds now. */ OntologyConceptBindingsResponse bind(final BindingSpec spec) { + return bind(admin(), spec); + } + + private OntologyConceptBindingsResponse bind( + final OpenMetadataClient writer, final BindingSpec spec) { final OntologyConcept type = type(spec.type()); final Table table = tables.get(spec.table()); final OntologyAssetBinding asset = @@ -262,7 +272,7 @@ OntologyConceptBindingsResponse bind(final BindingSpec spec) { asset.withRowFilter( filter(spec.filter().column(), spec.filter().operator(), spec.filter().value())); } - return put(admin(), type, asset, bindings(admin(), type).getRevision()); + return put(writer, type, asset, bindings(writer, type).getRevision()); } private OntologyColumnBinding column(final ColumnBindingSpec spec) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java index c78ca4f2e6f1..04709c23c22c 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java @@ -43,12 +43,15 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.ActivateOntologyRelease; import org.openmetadata.schema.api.tasks.ResolveTask; import org.openmetadata.schema.api.teams.CreateTeam; import org.openmetadata.schema.entity.data.Ontology; import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyRelease; import org.openmetadata.schema.entity.teams.Role; import org.openmetadata.schema.entity.teams.Team; import org.openmetadata.schema.tests.type.TestCaseStatus; @@ -378,6 +381,104 @@ void lostTheRight(final TestNamespace ns) { } } + private static JsonNode taskWithFiler(final String taskId) { + return JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, "/v1/tasks/" + taskId + "?fields=assignees,createdBy", null)); + } + + private static void activateAs( + final OpenMetadataClient activator, final TestNamespace ns, final Ontology ontology) { + final OntologyRelease release = capture(ontology); + final var review = submit(ns, Entity.ONTOLOGY_RELEASE, release.getFullyQualifiedName()); + SdkClients.user1Client() + .tasks() + .resolve(review.getId().toString(), decision(TaskResolutionType.Approved)); + activator + .ontologies() + .activate( + ontology.getId(), + new ActivateOntologyRelease() + .withReleaseId(release.getId()) + .withExpectedActivationRevision( + admin().ontologies().state(ontology.getId()).getActivationRevision())); + OntologyShapeCheckProposalIT.settle(); + } + + @Test + void theOwnerWhoActivatesMayApprove(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "filerapprove"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("pri")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OpenMetadataClient owner = + OntologyBindingFixtures.client(access.userToken("filer", List.of())); + final EntityReference ownerUser = OntologyBindingFixtures.readerReference(owner); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + ownedBy("/v1/tables/" + fixture.table("accounts").getId(), "user", ownerUser); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ownerUser); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + + activateAs(owner, ns, ontology); + + final JsonNode filed = onlyTask(fixture.type("Account")); + final JsonNode task = taskWithFiler(filed.path("id").asText()); + assertEquals("governance-bot", task.path("createdBy").path("name").asText()); + assertEquals("governance-bot", task.path("updatedBy").asText()); + assertEquals(List.of(ownerUser.getName()), assignees(task)); + assertEquals(0, generated(tableFqn, "all").size()); + + owner + .tasks() + .resolve( + filed.path("id").asText(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + assertEquals(1, generated(tableFqn, "all").size()); + } + } + + @Test + void theOwnerWhoWritesABindingMayReject(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "filerreject"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prj")) { + declareKey(fixture, "accounts", List.of("id"), "email"); + final OpenMetadataClient owner = + OntologyBindingFixtures.client(access.userToken("binder", List.of())); + final EntityReference ownerUser = OntologyBindingFixtures.readerReference(owner); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + ownedBy("/v1/tables/" + fixture.table("accounts").getId(), "user", ownerUser); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ownerUser); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + assertEquals(0, openTasks(fixture.type("Account")).size()); + + fixture.bindAll(owner); + OntologyShapeCheckProposalIT.settle(); + + final JsonNode filed = onlyTask(fixture.type("Account")); + final JsonNode task = taskWithFiler(filed.path("id").asText()); + assertEquals("governance-bot", task.path("createdBy").path("name").asText()); + assertEquals(List.of(ownerUser.getName()), assignees(task)); + + owner + .tasks() + .resolve( + filed.path("id").asText(), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals( + TaskEntityStatus.Rejected, admin().tasks().get(filed.path("id").asText()).getStatus()); + assertEquals(0, generated(tableFqn, "all").size()); + } + } + @Test void blindReaders(final TestNamespace ns) { final Ontology ontology = ontologyWith(ns, "readers"); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java index 5b2db0fde38d..96d51bcfe43e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java @@ -491,7 +491,7 @@ private Outcome execute( try { switch (write) { case CreateTask create -> createTask( - ontologyId, user, planned(found, create.classId(), create.identity())); + ontologyId, planned(found, create.classId(), create.identity())); case ReplaceTask replace -> replaceTask( user, replace.taskId(), planned(found, replace.classId(), replace.identity())); case CancelTask cancel -> cancelTask(user, cancel); @@ -564,7 +564,7 @@ private static String newName(final String identity) { + UUID.randomUUID().toString().replace("-", "").substring(0, NAME_SUFFIX_LENGTH); } - private void createTask(final UUID ontologyId, final String user, final Planned planned) { + private void createTask(final UUID ontologyId, final Planned planned) { final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); final OntologyShapeCheck check = planned.generated().check(); final TestCaseProposal proposal = proposal(planned, newName(check.getIdentity())); @@ -582,9 +582,10 @@ private void createTask(final UUID ontologyId, final String user, final Planned .withPayload(suggestion(proposal)) .withAssignees(assignees(ontologyId, table)) .withUseEntityOwnerFallback(false) - .withCreatedBy(Entity.getEntityReferenceByName(Entity.USER, user, Include.NON_DELETED)) + .withCreatedBy( + Entity.getEntityReferenceByName(Entity.USER, DELETE_AS, Include.NON_DELETED)) .withCreatedAt(now) - .withUpdatedBy(user) + .withUpdatedBy(DELETE_AS) .withUpdatedAt(now); tasks.create(null, task); } From a2af43ba9cc92ec3e10d7d86e2526f9da1f7ee2d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 22:28:42 -0800 Subject: [PATCH 166/203] Read the reviewers of a list of tasks as a GET of each does, soft-deleted reviewers included --- .../openmetadata/it/tests/TaskResourceIT.java | 33 ++++++- .../service/jdbi3/TaskRepository.java | 91 +++++++++++++++++-- 2 files changed, 115 insertions(+), 9 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index e3451a0527c0..d0c8a3bfdf75 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -1409,6 +1409,25 @@ void testListReturnsEachTasksReviewersAndDomainsAsAGetByIdDoes(TestNamespace ns) createTaskRequestAboutTable(ns, "bulk-fields-b", tableInDomainB) .withAssignees(List.of(shared.USER1.getFullyQualifiedName())) .withReviewers(List.of(shared.USER3.getFullyQualifiedName()))); + String goneName = "bulkgone" + UUID.randomUUID().toString().substring(0, 8); + User gone = + SdkClients.adminClient() + .users() + .create(new CreateUser().withName(goneName).withEmail(goneName + "@test.om.org")); + Task taskWithDeletedReviewer = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "bulk-fields-gone", tableInDomainA) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName())) + .withReviewers(List.of(gone.getFullyQualifiedName()))); + Task taskWithoutReviewer = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "bulk-fields-none", tableInDomainB) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName()))); + SdkClients.adminClient().users().delete(gone.getId()); ListResponse listed = SdkClients.user1Client() @@ -1421,6 +1440,15 @@ void testListReturnsEachTasksReviewersAndDomainsAsAGetByIdDoes(TestNamespace ns) Task listedA = taskIn(listed, taskA); Task listedB = taskIn(listed, taskB); + Task listedGone = taskIn(listed, taskWithDeletedReviewer); + Task listedNone = taskIn(listed, taskWithoutReviewer); + assertEquals( + List.of(goneName), + listedGone.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + List.of(Boolean.TRUE), + listedGone.getReviewers().stream().map(EntityReference::getDeleted).toList()); + assertEquals(List.of(), listedNone.getReviewers()); assertEquals( List.of(shared.USER2.getName()), listedA.getReviewers().stream().map(EntityReference::getName).toList()); @@ -1433,12 +1461,15 @@ void testListReturnsEachTasksReviewersAndDomainsAsAGetByIdDoes(TestNamespace ns) assertEquals( List.of(domainB.getFullyQualifiedName()), listedB.getDomains().stream().map(EntityReference::getFullyQualifiedName).toList()); - for (Task listedTask : List.of(listedA, listedB)) { + for (Task listedTask : List.of(listedA, listedB, listedGone, listedNone)) { Task byId = SdkClients.adminClient().tasks().get(listedTask.getId().toString(), "reviewers,domains"); assertEquals( byId.getReviewers().stream().map(EntityReference::getName).toList(), listedTask.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + byId.getReviewers().stream().map(EntityReference::getDeleted).toList(), + listedTask.getReviewers().stream().map(EntityReference::getDeleted).toList()); assertEquals( byId.getDomains().stream().map(EntityReference::getName).toList(), listedTask.getDomains().stream().map(EntityReference::getName).toList()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index b58864e9f2e5..deab4b28257b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -29,6 +29,7 @@ import jakarta.ws.rs.core.UriInfo; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -37,6 +38,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.core.Jdbi; import org.openmetadata.schema.EntityInterface; @@ -77,6 +79,7 @@ import org.openmetadata.service.governance.workflows.WorkflowHandler; import org.openmetadata.service.governance.workflows.WorkflowInstanceTerminator; import org.openmetadata.service.governance.workflows.WorkflowInstanceTerminator.TaskCloseRequest; +import org.openmetadata.service.jdbi3.CoreRelationshipDAOs.EntityRelationshipObject; import org.openmetadata.service.jdbi3.CoreRelationshipDAOs.FieldRelationshipDAO.FieldRelationship; import org.openmetadata.service.resources.feeds.MessageParser; import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; @@ -357,7 +360,8 @@ public void setFieldsInBulk(Fields fields, List entities) { if (entities == null || entities.isEmpty()) { return; } - fetchAndSetFields(entities, fields); + fetchAndSetFields(entities, withoutBatched(fields)); + setDomainsAndReviewers(entities, fields); setInheritedFields(entities, fields); RelationIncludes defaultIncludes = RelationIncludes.fromInclude(NON_DELETED); final Fields perTask = withoutBatched(fields); @@ -367,15 +371,86 @@ public void setFieldsInBulk(Fields fields, List entities) { } } - /** The fields that {@code fetchAndSetFields} has already set for the whole list in one read. */ - private Fields withoutBatched(final Fields fields) { - final Set rest = new HashSet<>(fields.getFieldList()); - if (supportsDomains) { - rest.remove(Entity.FIELD_DOMAINS); + /** + * Reads the domains and the reviewers of all the tasks in one statement, and gives each task what + * a GET of it gives. A GET returns reviewers that were soft deleted, which the batched read of + * the base class leaves out. + */ + private void setDomainsAndReviewers(final List tasks, final Fields fields) { + final boolean domains = fields.contains(FIELD_DOMAINS); + final boolean reviewers = fields.contains(FIELD_REVIEWERS); + if (!domains && !reviewers) { + return; + } + final List relations = new ArrayList<>(); + if (domains) { + relations.add(Relationship.HAS.ordinal()); + } + if (reviewers) { + relations.add(Relationship.REVIEWS.ordinal()); + } + final List records = + daoCollection + .relationshipDAO() + .findFromBatchWithRelations( + entityListToStrings(tasks), Entity.TASK, relations, Include.ALL) + .stream() + .filter( + record -> + record.getRelation() == Relationship.REVIEWS.ordinal() + || DOMAIN.equals(record.getFromEntity())) + .toList(); + final Map references = referencesOf(records); + final Map> domainsOf = new HashMap<>(); + final Map> reviewersOf = new HashMap<>(); + for (EntityRelationshipObject record : records) { + final EntityReference source = references.get(UUID.fromString(record.getFromId())); + if (source == null) { + continue; + } + final UUID taskId = UUID.fromString(record.getToId()); + if (record.getRelation() == Relationship.REVIEWS.ordinal()) { + reviewersOf.computeIfAbsent(taskId, id -> new ArrayList<>()).add(source); + } else if (DOMAIN.equals(record.getFromEntity())) { + domainsOf.computeIfAbsent(taskId, id -> new ArrayList<>()).add(source); + } + } + for (Task task : tasks) { + if (domains) { + task.setDomains(domainsOf.getOrDefault(task.getId(), List.of())); + } + if (reviewers) { + task.setReviewers( + reviewersOf.getOrDefault(task.getId(), List.of()).stream() + .sorted(EntityUtil.compareEntityReference) + .collect(Collectors.toList())); + } } - if (supportsReviewers) { - rest.remove(Entity.FIELD_REVIEWERS); + } + + /** A domain is looked up as the base class does, a reviewer as a GET does: deleted included. */ + private static Map referencesOf( + final List records) { + final Map> idsByType = new LinkedHashMap<>(); + for (EntityRelationshipObject record : records) { + idsByType + .computeIfAbsent(record.getFromEntity(), type -> new ArrayList<>()) + .add(UUID.fromString(record.getFromId())); } + final Map references = new HashMap<>(); + idsByType.forEach( + (type, ids) -> + Entity.getEntityReferencesByIds( + type, ids, DOMAIN.equals(type) ? NON_DELETED : Include.ALL) + .forEach(reference -> references.put(reference.getId(), reference))); + return references; + } + + /** The fields that {@link #setDomainsAndReviewers} sets for the whole list in one read. */ + private static Fields withoutBatched(final Fields fields) { + final Set rest = new HashSet<>(fields.getFieldList()); + rest.remove(Entity.FIELD_DOMAINS); + rest.remove(Entity.FIELD_REVIEWERS); return new Fields(rest); } From 7b859803fbcc24f34a34237b3ee6d776f3509a98 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 22:28:48 -0800 Subject: [PATCH 167/203] Check a PUT against the stored test's generatedBy before the parameter checks --- .../tests/OntologyShapeCheckProposalIT.java | 20 ++++++++++++++- .../service/jdbi3/GeneratedTestScope.java | 25 ++++++++++++++++--- .../service/jdbi3/TestCaseRepository.java | 23 +++++++++++++++-- .../resources/dqtests/TestCaseResource.java | 7 +++--- 4 files changed, 64 insertions(+), 11 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java index 4832abd0ff84..a751523c24de 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java @@ -561,6 +561,7 @@ void readOnly(final TestNamespace ns) { org.openmetadata.schema.tests.TestCase.class)); assertShapeRefusal(() -> replaceDefinition(who, path)); assertShapeRefusal(() -> put(who, testId, "threshold", "5")); + assertShapeRefusal(() -> putDefinition(who, testId, "tableRowCountToEqual")); final String words = "looked at by " + caller.getKey(); assertEquals(words, put(who, testId, null, words).getDescription()); assertEquals(words, getTest(testId).getDescription()); @@ -640,6 +641,21 @@ private static String parameter( */ private static org.openmetadata.schema.tests.TestCase put( final OpenMetadataClient who, final String id, final String changed, final String value) { + return put(who, id, changed, value, null); + } + + /** A PUT that names another test definition and sends the stored parameters. */ + private static org.openmetadata.schema.tests.TestCase putDefinition( + final OpenMetadataClient who, final String id, final String definition) { + return put(who, id, null, "same words", definition); + } + + private static org.openmetadata.schema.tests.TestCase put( + final OpenMetadataClient who, + final String id, + final String changed, + final String value, + final String definition) { final org.openmetadata.schema.tests.TestCase stored = getTest(id); final List> parameters = new ArrayList<>(); for (final var parameter : stored.getParameterValues()) { @@ -653,7 +669,9 @@ private static org.openmetadata.schema.tests.TestCase put( final java.util.Map body = new java.util.LinkedHashMap<>(); body.put("name", stored.getName()); body.put("entityLink", stored.getEntityLink()); - body.put("testDefinition", stored.getTestDefinition().getFullyQualifiedName()); + body.put( + "testDefinition", + definition == null ? stored.getTestDefinition().getFullyQualifiedName() : definition); body.put("parameterValues", parameters); body.put("description", changed == null ? value : stored.getDescription()); return who.getHttpClient() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java index 9c54c21f7bae..51e468130865 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java @@ -69,7 +69,17 @@ static void requireUnchanged(final TestCase original, final TestCase updated) { if (!Objects.equals(original.getGeneratedBy(), updated.getGeneratedBy())) { throw BadRequestException.of(SET_BY_SERVER); } - if (original.getGeneratedBy() != null && frozenFieldsChanged(original, updated)) { + requireFrozenFieldsUnchanged(original, updated); + } + + /** + * Refuses a change to what the stored test's {@code generatedBy} freezes. A PUT body cannot carry + * {@code generatedBy}, so the stored test says whether the test comes from a shape. + */ + static void requireFrozenFieldsUnchanged(final TestCase original, final TestCase updated) { + if (!isActive() + && original.getGeneratedBy() != null + && frozenFieldsChanged(original, updated)) { throw BadRequestException.of(FROM_A_SHAPE); } } @@ -83,8 +93,15 @@ private static boolean frozenFieldsChanged(final TestCase original, final TestCa private static boolean sameDefinition(final TestCase original, final TestCase updated) { return original.getTestDefinition() == null ? updated.getTestDefinition() == null - : updated.getTestDefinition() != null - && Objects.equals( - original.getTestDefinition().getId(), updated.getTestDefinition().getId()); + : updated.getTestDefinition() != null && sameReference(original, updated); + } + + /** A PUT names its definition by name until the write resolves it, so it has no id yet. */ + private static boolean sameReference(final TestCase original, final TestCase updated) { + final var stored = original.getTestDefinition(); + final var incoming = updated.getTestDefinition(); + return incoming.getId() == null + ? Objects.equals(stored.getFullyQualifiedName(), incoming.getFullyQualifiedName()) + : Objects.equals(stored.getId(), incoming.getId()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index fd4df0950a44..3977ac7aeeb6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -891,6 +891,24 @@ public void prepare(TestCase test, boolean update) { test.setTestSuite(getOrCreateTestSuite(test, table)); } + /** + * Prepares a PUT, given the test the PUT finds by name, or null when it creates one. A stored + * test that comes from a shape is checked before the parameters, so a change to what the shape + * freezes says where the test comes from. + */ + public void prepareInternal(TestCase test, TestCase stored) { + if (stored != null && stored.getGeneratedBy() != null) { + GeneratedTestScope.requireFrozenFieldsUnchanged( + new TestCase() + .withGeneratedBy(stored.getGeneratedBy()) + .withEntityLink(stored.getEntityLink()) + .withParameterValues(stored.getParameterValues()) + .withTestDefinition(getTestDefinition(stored)), + test); + } + prepareInternal(test, stored != null); + } + /** * Runs the checks {@link #prepareInternal} runs for a test case, minus the basic test suite, so a * CSV dry run reports the rows the real import would and creates nothing. @@ -2676,7 +2694,8 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro parsedLink.getFullyQualifiedFieldValue(), EntityInterfaceUtil.quoteName(name)); testCase.setFullyQualifiedName(testCaseFqn); testCase.setEntityFQN(parsedLink.getFullyQualifiedFieldValue()); - boolean isUpdate = repository.findByNameOrNull(testCaseFqn, Include.ALL) != null; + TestCase stored = repository.findByNameOrNull(testCaseFqn, Include.ALL); + boolean isUpdate = stored != null; // A row can name any table, so it is checked as the matching REST write, before anything // is created for it (e.g. the table's test suite) @@ -2698,7 +2717,7 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro repository.checkForImport(testCase, isUpdate); importSuccess(printer, csvRecord, isUpdate ? ENTITY_UPDATED : ENTITY_CREATED); } else { - repository.prepareInternal(testCase, isUpdate); + repository.prepareInternal(testCase, stored); importedTestSuiteIds.putIfAbsent( testCase.getTestSuite().getFullyQualifiedName(), testCase.getTestSuite().getId()); if (testCase.getId() == null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResource.java index a1be5efaf154..2772e1461f1a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResource.java @@ -962,11 +962,10 @@ public Response createOrUpdate( TestCase test = mapper.createToEntity(create, securityContext.getUserPrincipal().getName()); // Only the FQN before authorizing: prepare creates the table's test suite if it is missing. repository.setFullyQualifiedName(test); - boolean testCaseExists = - repository.findByNameOrNull(test.getFullyQualifiedName(), Include.ALL) != null; + TestCase stored = repository.findByNameOrNull(test.getFullyQualifiedName(), Include.ALL); authorizer.authorizeRequests( - securityContext, createOrUpdateRequests(test, testCaseExists), AuthorizationLogic.ANY); - repository.prepareInternal(test, testCaseExists); + securityContext, createOrUpdateRequests(test, stored != null), AuthorizationLogic.ANY); + repository.prepareInternal(test, stored); PutResponse response = repository.createOrUpdate(uriInfo, test, securityContext.getUserPrincipal().getName()); addHref(uriInfo, response.getEntity()); From cccd7010c4382a947062dea6e7d0d6373e71ec70 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 22:28:54 -0800 Subject: [PATCH 168/203] Say in the record who files the task, what a PUT with another entity link does and what a list of tasks reads --- ...hape-check-reaches-its-table-as-a-proposed-test.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index ad38c7044556..5dd678530358 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-12-01 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, and a hard delete, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read) +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, and a hard delete, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, and who may approve or reject), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (a list of tasks gives what a GET gives) - **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) ## Context @@ -34,7 +34,8 @@ assignee, and the server gives it to the owners of the table, as it does any tas assignee. An owner denied `CreateTests` may then neither approve nor reject it, so an administrator resolves it. A table with no owner leaves such a task with no assignee, and an administrator resolves it. Its source is `Ingestion`, because a deterministic compile of a shape wrote it, and no -agent or model did. +agent or model did. The governance bot files the task, not the person whose change started the run, +because the server lets no filer resolve their own task (`TaskAuthorPolicy`). **A test is not kept in a review state.** The runner reads every test case of a suite and no status of it, so a test that waits for a decision would run. The proposal is the task and the test does not @@ -102,6 +103,8 @@ asserts that the second count is zero. parameter values or `generatedBy` by anyone but the reconcile, with a 400 that says the test comes from a shape. A create that sends `generatedBy` is a 400, and so is a patch that changes it. A PUT keeps the stored `generatedBy`, so a PUT that changes only the description, owners or tags succeeds. +A PUT finds a test by its entity link and name, so a PUT with another entity link creates a separate +test and leaves the generated one as it was. The description, owners and tags stay editable, and a person may delete the test. A test a person deleted is not brought back unless the content changes. @@ -113,7 +116,9 @@ apply to them. OpenMetadata has no way to read the most frequent schedule a depl schedule stays daily at midnight. A check reads every row of its tables: the runner executes the statement of a `tableCustomSQLQuery` test with `COUNT` as written, on its own session, and never through the sampled data set that built-in tests read, whatever sample the table, its schema, its -database or the pipeline sets. +database or the pipeline sets. A list of tasks reads the reviewers and the domains of all its tasks +together, not task by task, and gives each task the reviewers and domains that a GET of it gives, +deleted reviewers included. **What a caller reads.** Each check of `GET /v1/ontologyConcepts/{id}/shapeChecks` has a `proposal`: `none`, `proposed` with the task, `rejected` with the task, or `accepted` with the test case and the From 75bf0c970d215363872bbde1dc3c4e2355a0313e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Wed, 2 Dec 2026 22:53:41 -0800 Subject: [PATCH 169/203] Test that a PUT that names its test definition is checked against the stored one --- .../service/jdbi3/GeneratedTestScopeTest.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java index 907debeedb68..0dce6ff1b37a 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java @@ -161,6 +161,31 @@ private static TestCase plain(final UUID definition, final String statement) { List.of(new TestCaseParameterValue().withName("sqlExpression").withValue(statement))); } + @Test + void aPutNamesTheDefinitionByNameAndTheStoredTestSaysWhereItComesFrom() { + UUID definition = UUID.randomUUID(); + TestCase stored = generated(definition, "a = 1"); + stored.getTestDefinition().setFullyQualifiedName("tableCustomSQLQuery"); + TestCase sameName = plain(definition, "a = 1"); + sameName.setTestDefinition( + new EntityReference() + .withType("testDefinition") + .withFullyQualifiedName("tableCustomSQLQuery")); + TestCase otherName = plain(definition, "a = 1"); + otherName.setTestDefinition( + new EntityReference() + .withType("testDefinition") + .withFullyQualifiedName("tableRowCountToEqual")); + + assertDoesNotThrow(() -> GeneratedTestScope.requireFrozenFieldsUnchanged(stored, sameName)); + assertEquals( + GeneratedTestScope.FROM_A_SHAPE, + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireFrozenFieldsUnchanged(stored, otherName)) + .getMessage()); + } + private static TestCase generated(final UUID definition, final String statement) { return plain(definition, statement) .withGeneratedBy(new TestCaseGeneratedBy().withIdentity("a".repeat(64))); From da39148aed4807b4f2b8ee9edb34d54838a3d27b Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 3 Dec 2026 01:40:14 -0800 Subject: [PATCH 170/203] Test that the repository refuses a PUT of a changed threshold that reaches it without the resource's checks --- .../tests/OntologyShapeCheckProposalIT.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java index a751523c24de..27d7bf938d47 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java @@ -544,6 +544,8 @@ void readOnly(final TestNamespace ns) { checkOf(checks(account), "email").getProposal().getTestCase().getId().toString(); final String path = "/v1/dataQuality/testCases/" + testId; + assertRepositoryRefusesAPutOfAChangedThreshold(testId); + final java.util.Map callers = new java.util.LinkedHashMap<>(); callers.put("admin", admin()); callers.put("owner", owner); @@ -582,6 +584,25 @@ void readOnly(final TestNamespace ns) { } } + /** A write that reaches the repository without the resource's checks is refused as well. */ + private static void assertRepositoryRefusesAPutOfAChangedThreshold(final String testId) { + final org.openmetadata.schema.tests.TestCase body = + JsonUtils.deepCopy(getTest(testId), org.openmetadata.schema.tests.TestCase.class); + body.setGeneratedBy(null); + body.getParameterValues().stream() + .filter(value -> "threshold".equals(value.getName())) + .forEach(value -> value.setValue("5")); + final org.openmetadata.service.exception.BadRequestException refused = + assertThrows( + org.openmetadata.service.exception.BadRequestException.class, + () -> + ((org.openmetadata.service.jdbi3.TestCaseRepository) + Entity.getEntityRepository(Entity.TEST_CASE)) + .createOrUpdate(null, body, "admin")); + assertEquals(FROM_A_SHAPE, refused.getMessage()); + assertEquals("0", parameter(getTest(testId), "threshold")); + } + static final String FROM_A_SHAPE = "This test comes from a shape: its test definition, entity link and parameter values change" + " only when the shape or the table bindings change. Its description, owners and tags" From 97742a608fc41977b45007f5bf6aa2a944c43f70 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 3 Dec 2026 09:33:13 -0800 Subject: [PATCH 171/203] Give each listed task its domains in the order a GET gives them --- .../openmetadata/it/tests/TaskResourceIT.java | 98 +++++++++++++++++++ .../service/jdbi3/TaskRepository.java | 5 +- 2 files changed, 102 insertions(+), 1 deletion(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index d0c8a3bfdf75..022c2d80c1e9 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -1476,6 +1476,104 @@ void testListReturnsEachTasksReviewersAndDomainsAsAGetByIdDoes(TestNamespace ns) } } + @Test + void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { + SharedEntities shared = SharedEntities.get(); + String assignee = shared.USER1.getFullyQualifiedName(); + Domain domainZ = createDomain(ns, "order-zz"); + Domain domainA = createDomain(ns, "order-aa"); + String suffix = UUID.randomUUID().toString().substring(0, 8); + String aboutName = "orderabout" + suffix; + User about = + SdkClients.adminClient() + .users() + .create( + new CreateUser() + .withName(aboutName) + .withEmail(aboutName + "@test.om.org") + .withDomains( + List.of(domainZ.getFullyQualifiedName(), domainA.getFullyQualifiedName()))); + String reviewerZ = "orderrevz" + suffix; + String reviewerA = "orderreva" + suffix; + for (String name : List.of(reviewerZ, reviewerA)) { + SdkClients.adminClient() + .users() + .create(new CreateUser().withName(name).withEmail(name + "@test.om.org")); + } + Table inDomainZ = + createTableWithDomainAndOwners(ns, domainZ.getEntityReference(), List.of(shared.USER1_REF)); + Table withoutDomain = createTableWithDomainAndOwners(ns, null, List.of(shared.USER1_REF)); + Task aboutUser = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "order-user", inDomainZ) + .withAbout(entityLink("user", about.getFullyQualifiedName())) + .withAssignees(List.of(assignee))); + Task twoReviewers = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "order-reviewers", inDomainZ) + .withAssignees(List.of(assignee)) + .withReviewers(List.of(reviewerZ, reviewerA))); + Task noDomain = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "order-none", withoutDomain) + .withAssignees(List.of(assignee))); + String filter = domainZ.getFullyQualifiedName() + "," + domainA.getFullyQualifiedName(); + + ListResponse assigned = + SdkClients.user1Client() + .tasks() + .listAssigned(null, "open", filter, "reviewers,domains", 1000); + ListResponse assignedUnfiltered = + SdkClients.user1Client() + .tasks() + .listAssigned(null, "open", null, "reviewers,domains", 1000); + ListResponse created = + SdkClients.adminClient() + .tasks() + .listCreated(null, "open", filter, "reviewers,domains", 1000); + ListResponse owned = + SdkClients.user1Client().tasks().listOwned(null, "open", filter, "reviewers,domains"); + + List domainsOfUser = List.of(domainA.getName(), domainZ.getName()); + List reviewersInOrder = List.of(reviewerA, reviewerZ); + for (ListResponse listed : List.of(assigned, created)) { + assertEquals(domainsOfUser, namesOf(taskIn(listed, aboutUser).getDomains())); + assertEquals(reviewersInOrder, namesOf(taskIn(listed, twoReviewers).getReviewers())); + } + assertEquals(reviewersInOrder, namesOf(taskIn(owned, twoReviewers).getReviewers())); + assertEquals(List.of(), taskIn(assignedUnfiltered, noDomain).getDomains()); + assertEquals(List.of(), taskIn(assignedUnfiltered, noDomain).getReviewers()); + for (Task listedTask : + List.of( + taskIn(assigned, aboutUser), + taskIn(assigned, twoReviewers), + taskIn(created, aboutUser), + taskIn(created, twoReviewers), + taskIn(assignedUnfiltered, noDomain))) { + Task byId = + SdkClients.adminClient().tasks().get(listedTask.getId().toString(), "reviewers,domains"); + assertEquals(namesOf(byId.getDomains()), namesOf(listedTask.getDomains())); + assertEquals(namesOf(byId.getReviewers()), namesOf(listedTask.getReviewers())); + } + assertEquals( + domainsOfUser, + namesOf( + SdkClients.adminClient() + .tasks() + .get(aboutUser.getId().toString(), "domains") + .getDomains())); + } + + private static List namesOf(List references) { + return references == null ? null : references.stream().map(EntityReference::getName).toList(); + } + private static Task taskIn(ListResponse listed, Task wanted) { return listed.getData().stream() .filter(task -> task.getId().equals(wanted.getId())) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index deab4b28257b..7cc0a055cf26 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -417,7 +417,10 @@ record -> } for (Task task : tasks) { if (domains) { - task.setDomains(domainsOf.getOrDefault(task.getId(), List.of())); + task.setDomains( + domainsOf.getOrDefault(task.getId(), List.of()).stream() + .sorted(EntityUtil.compareEntityReference) + .collect(Collectors.toList())); } if (reviewers) { task.setReviewers( From 808dafe689cbdcee4ad7b078989ebb2039b3a03f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 3 Dec 2026 09:33:20 -0800 Subject: [PATCH 172/203] Run the generated-test check in a CSV dry run, stop a task replace setting updatedBy, and test a reference that carries an id --- .../tests/OntologyShapeCheckProposalIT.java | 30 +++++++++++++++++++ .../it/tests/OntologyShapeProposalAskIT.java | 19 ++++++++++++ .../service/jdbi3/TestCaseRepository.java | 19 +++++++++--- .../ontology/OntologyCheckReconciler.java | 1 - .../service/jdbi3/GeneratedTestScopeTest.java | 19 ++++++++++++ 5 files changed, 83 insertions(+), 5 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java index 27d7bf938d47..1aca88daa641 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java @@ -464,6 +464,14 @@ void boundChange(final TestNamespace ns) { test.path("parameterValues").get(0).path("value").asText()); final OntologyShapeCheck replaced = checkOf(checks(account), "email"); assertEquals(openTask, replaced.getProposal().getTask().getId().toString()); + assertEquals( + "governance-bot", + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString(HttpMethod.GET, "/v1/tasks/" + openTask, null)) + .path("updatedBy") + .asText()); final JsonNode value = JsonUtils.readTree( JsonUtils.readTree( @@ -545,6 +553,8 @@ void readOnly(final TestNamespace ns) { final String path = "/v1/dataQuality/testCases/" + testId; assertRepositoryRefusesAPutOfAChangedThreshold(testId); + assertCsvImportRefusesAChangedThreshold( + fixture.table("accounts").getFullyQualifiedName(), testId); final java.util.Map callers = new java.util.LinkedHashMap<>(); callers.put("admin", admin()); @@ -584,6 +594,26 @@ void readOnly(final TestNamespace ns) { } } + /** A CSV dry run refuses the row that the real import refuses, and neither changes the test. */ + private static void assertCsvImportRefusesAChangedThreshold( + final String tableFqn, final String testId) { + final String exported = admin().testCases().exportCsv(tableFqn); + final String changed = exported.replaceFirst("(name\\W+threshold\\W+value\\W+)0", "$15"); + assertNotEquals(exported, changed); + for (final boolean dryRun : new boolean[] {true, false}) { + final JsonNode result = + JsonUtils.readTree(admin().testCases().importCsv(tableFqn, changed, dryRun, "table")); + assertEquals("failure", result.path("status").asText(), "dryRun=" + dryRun); + assertEquals(1, result.path("numberOfRowsProcessed").asInt(), "dryRun=" + dryRun); + assertEquals(0, result.path("numberOfRowsPassed").asInt(), "dryRun=" + dryRun); + assertEquals(1, result.path("numberOfRowsFailed").asInt(), "dryRun=" + dryRun); + assertTrue( + result.path("importResultsCsv").asText().contains(FROM_A_SHAPE), + result.path("importResultsCsv").asText()); + assertEquals("0", parameter(getTest(testId), "threshold")); + } + } + /** A write that reaches the repository without the resource's checks is refused as well. */ private static void assertRepositoryRefusesAPutOfAChangedThreshold(final String testId) { final org.openmetadata.schema.tests.TestCase body = diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java index 04709c23c22c..5759f0a184ab 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java @@ -431,6 +431,13 @@ void theOwnerWhoActivatesMayApprove(final TestNamespace ns) { assertEquals("governance-bot", task.path("updatedBy").asText()); assertEquals(List.of(ownerUser.getName()), assignees(task)); assertEquals(0, generated(tableFqn, "all").size()); + final String taskId = filed.path("id").asText(); + assertFalse( + owner.tasks().listCreated(null, null, null, null, 1000).getData().stream() + .anyMatch(listed -> listed.getId().toString().equals(taskId))); + assertTrue( + owner.tasks().listAssigned(null, null, null, null, 1000).getData().stream() + .anyMatch(listed -> listed.getId().toString().equals(taskId))); owner .tasks() @@ -439,6 +446,18 @@ void theOwnerWhoActivatesMayApprove(final TestNamespace ns) { new ResolveTask().withResolutionType(TaskResolutionType.Approved)); assertEquals(1, generated(tableFqn, "all").size()); + + admin().users().delete(ownerUser.getId()); + assertEquals( + "governance-bot", + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, "/v1/tasks/" + taskId + "?fields=createdBy", null)) + .path("createdBy") + .path("name") + .asText()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index 3977ac7aeeb6..00d6befd72e0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -897,6 +897,15 @@ public void prepare(TestCase test, boolean update) { * freezes says where the test comes from. */ public void prepareInternal(TestCase test, TestCase stored) { + requireGeneratedScope(test, stored); + prepareInternal(test, stored != null); + } + + /** + * A stored test that comes from a shape keeps what the shape freezes. Both the real import and + * its dry run call this, so the dry run reports the rows the real import refuses. + */ + private void requireGeneratedScope(TestCase test, TestCase stored) { if (stored != null && stored.getGeneratedBy() != null) { GeneratedTestScope.requireFrozenFieldsUnchanged( new TestCase() @@ -906,14 +915,16 @@ public void prepareInternal(TestCase test, TestCase stored) { .withTestDefinition(getTestDefinition(stored)), test); } - prepareInternal(test, stored != null); } /** * Runs the checks {@link #prepareInternal} runs for a test case, minus the basic test suite, so a - * CSV dry run reports the rows the real import would and creates nothing. + * CSV dry run reports the rows the real import would and creates nothing. It takes the stored + * test the row names, or null when the row creates one. */ - void checkForImport(TestCase test, boolean isUpdate) { + void checkForImport(TestCase test, TestCase stored) { + final boolean isUpdate = stored != null; + requireGeneratedScope(test, stored); validateTags(test); validateForWrite(test, isUpdate); validateExtension(test, isUpdate); @@ -2714,7 +2725,7 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro } if (importResult.getDryRun()) { - repository.checkForImport(testCase, isUpdate); + repository.checkForImport(testCase, stored); importSuccess(printer, csvRecord, isUpdate ? ENTITY_UPDATED : ENTITY_CREATED); } else { repository.prepareInternal(testCase, stored); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java index 96d51bcfe43e..7de975216093 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java @@ -608,7 +608,6 @@ private void replaceTask(final String user, final UUID taskId, final Planned pla .getName(); task.setPayload(suggestion(proposal(planned, name))); task.setDescription(describe(planned)); - task.setUpdatedBy(user); task.setUpdatedAt(System.currentTimeMillis()); tasks.createOrUpdate(null, task, user); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java index 0dce6ff1b37a..ded7192d6096 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java @@ -186,6 +186,25 @@ void aPutNamesTheDefinitionByNameAndTheStoredTestSaysWhereItComesFrom() { .getMessage()); } + @Test + void aReferenceThatCarriesAnIdIsComparedByIdAndNotByName() { + UUID definition = UUID.randomUUID(); + TestCase stored = generated(definition, "a = 1"); + stored.getTestDefinition().setFullyQualifiedName("tableCustomSQLQuery"); + TestCase sameId = plain(definition, "a = 1"); + sameId.getTestDefinition().setFullyQualifiedName("renamedDefinition"); + TestCase otherId = plain(UUID.randomUUID(), "a = 1"); + otherId.getTestDefinition().setFullyQualifiedName("tableCustomSQLQuery"); + + assertDoesNotThrow(() -> GeneratedTestScope.requireFrozenFieldsUnchanged(stored, sameId)); + assertEquals( + GeneratedTestScope.FROM_A_SHAPE, + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireFrozenFieldsUnchanged(stored, otherId)) + .getMessage()); + } + private static TestCase generated(final UUID definition, final String statement) { return plain(definition, statement) .withGeneratedBy(new TestCaseGeneratedBy().withIdentity("a".repeat(64))); From 0e0d9c472e5b289fc4a4d04cec02695a24c3eea2 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 3 Dec 2026 09:33:25 -0800 Subject: [PATCH 173/203] Record the filer's effects, the order of a listed task's fields and the CSV check --- ...ck-reaches-its-table-as-a-proposed-test.md | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index 5dd678530358..a5259cb20525 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-12-01 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, and a hard delete, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, and who may approve or reject), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (a list of tasks gives what a GET gives) +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, a hard delete, and a CSV import that changes a generated test's threshold, refused by the dry run and by the real import with the same message, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, who may approve or reject, and that a filer owner finds the task under assigned and not under created), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (a list of tasks gives the reviewers and domains that a GET gives, in the same order, including a task with none) - **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) ## Context @@ -35,7 +35,9 @@ assignee. An owner denied `CreateTests` may then neither approve nor reject it, resolves it. A table with no owner leaves such a task with no assignee, and an administrator resolves it. Its source is `Ingestion`, because a deterministic compile of a shape wrote it, and no agent or model did. The governance bot files the task, not the person whose change started the run, -because the server lets no filer resolve their own task (`TaskAuthorPolicy`). +because `TaskAuthorPolicy` refuses a non-administrator's resolve of a task they filed, and that +person is often the owner the task asks. So the task is not among the tasks that person created, and +deleting that person leaves the task in place. **A test is not kept in a review state.** The runner reads every test case of a suite and no status of it, so a test that waits for a decision would run. The proposal is the task and the test does not @@ -104,21 +106,21 @@ parameter values or `generatedBy` by anyone but the reconcile, with a 400 that s from a shape. A create that sends `generatedBy` is a 400, and so is a patch that changes it. A PUT keeps the stored `generatedBy`, so a PUT that changes only the description, owners or tags succeeds. A PUT finds a test by its entity link and name, so a PUT with another entity link creates a separate -test and leaves the generated one as it was. -The description, owners and tags stay editable, and a person may delete the test. A test a person -deleted is not brought back unless the content changes. +test and leaves the generated one as it was. A CSV import runs the same check, and its dry run +reports the rows the real import refuses. The description, owners and tags stay editable, and a +person may delete the test. A test a person deleted is not brought back unless the content changes. **What a test costs and reads.** The test is added to the basic test suite of its table, created if -the table has none. A suite with no pipeline gets one that runs daily at midnight, and the deployment -is best-effort, as for a data contract. Creating the test and the pipeline happens in the repositories, -so the limits that a resource enforces on a request, which a deployment can set per feature, do not -apply to them. OpenMetadata has no way to read the most frequent schedule a deployment allows, so the -schedule stays daily at midnight. A check reads every row of its tables: the runner executes the -statement of a `tableCustomSQLQuery` test with `COUNT` as written, on its own session, and never -through the sampled data set that built-in tests read, whatever sample the table, its schema, its -database or the pipeline sets. A list of tasks reads the reviewers and the domains of all its tasks -together, not task by task, and gives each task the reviewers and domains that a GET of it gives, -deleted reviewers included. +the table has none. A suite with no pipeline gets one that runs daily at midnight, and the +deployment is best-effort, as for a data contract. Creating the test and the pipeline happens in the +repositories, so the limits that a resource enforces on a request, which a deployment can set per +feature, do not apply to them. OpenMetadata has no way to read the most frequent schedule a +deployment allows, so the schedule stays daily at midnight. A check reads every row of its tables: +the runner executes the statement of a `tableCustomSQLQuery` test with `COUNT` as written, on its +own session, and never through the sampled data set that built-in tests read, whatever sample the +table, its schema, its database or the pipeline sets. A list of tasks reads the reviewers and the +domains of all its tasks together, not task by task, and gives each task the reviewers and domains +that a GET of it gives, in the same order, deleted reviewers included. **What a caller reads.** Each check of `GET /v1/ontologyConcepts/{id}/shapeChecks` has a `proposal`: `none`, `proposed` with the task, `rejected` with the task, or `accepted` with the test case and the From 2f34320fc993f0e06f3ee744a4e67534772ca058 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 3 Dec 2026 13:25:08 -0800 Subject: [PATCH 174/203] Test a CSV row that changes the definition of a generated test, and list five domains and four reviewers in reverse name order --- .../tests/OntologyShapeCheckProposalIT.java | 35 +++++++++++-------- .../openmetadata/it/tests/TaskResourceIT.java | 29 ++++++++------- 2 files changed, 37 insertions(+), 27 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java index 1aca88daa641..c7b7a5499b20 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java @@ -553,7 +553,7 @@ void readOnly(final TestNamespace ns) { final String path = "/v1/dataQuality/testCases/" + testId; assertRepositoryRefusesAPutOfAChangedThreshold(testId); - assertCsvImportRefusesAChangedThreshold( + assertCsvImportRefusesWhatTheShapeFreezes( fixture.table("accounts").getFullyQualifiedName(), testId); final java.util.Map callers = new java.util.LinkedHashMap<>(); @@ -595,22 +595,27 @@ void readOnly(final TestNamespace ns) { } /** A CSV dry run refuses the row that the real import refuses, and neither changes the test. */ - private static void assertCsvImportRefusesAChangedThreshold( + private static void assertCsvImportRefusesWhatTheShapeFreezes( final String tableFqn, final String testId) { final String exported = admin().testCases().exportCsv(tableFqn); - final String changed = exported.replaceFirst("(name\\W+threshold\\W+value\\W+)0", "$15"); - assertNotEquals(exported, changed); - for (final boolean dryRun : new boolean[] {true, false}) { - final JsonNode result = - JsonUtils.readTree(admin().testCases().importCsv(tableFqn, changed, dryRun, "table")); - assertEquals("failure", result.path("status").asText(), "dryRun=" + dryRun); - assertEquals(1, result.path("numberOfRowsProcessed").asInt(), "dryRun=" + dryRun); - assertEquals(0, result.path("numberOfRowsPassed").asInt(), "dryRun=" + dryRun); - assertEquals(1, result.path("numberOfRowsFailed").asInt(), "dryRun=" + dryRun); - assertTrue( - result.path("importResultsCsv").asText().contains(FROM_A_SHAPE), - result.path("importResultsCsv").asText()); - assertEquals("0", parameter(getTest(testId), "threshold")); + final String threshold = exported.replaceFirst("(name\\W+threshold\\W+value\\W+)0", "$15"); + final String definition = exported.replace(",tableCustomSQLQuery,", ",tableRowCountToEqual,"); + assertNotEquals(exported, threshold); + assertNotEquals(exported, definition); + for (final String changed : List.of(threshold, definition)) { + for (final boolean dryRun : new boolean[] {true, false}) { + final JsonNode result = + JsonUtils.readTree(admin().testCases().importCsv(tableFqn, changed, dryRun, "table")); + assertEquals("failure", result.path("status").asText(), "dryRun=" + dryRun); + assertEquals(1, result.path("numberOfRowsProcessed").asInt(), "dryRun=" + dryRun); + assertEquals(0, result.path("numberOfRowsPassed").asInt(), "dryRun=" + dryRun); + assertEquals(1, result.path("numberOfRowsFailed").asInt(), "dryRun=" + dryRun); + assertTrue( + result.path("importResultsCsv").asText().contains(FROM_A_SHAPE), + result.path("importResultsCsv").asText()); + assertEquals("0", parameter(getTest(testId), "threshold")); + assertEquals("tableCustomSQLQuery", getTest(testId).getTestDefinition().getName()); + } } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index 022c2d80c1e9..82a488617f78 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -29,6 +29,7 @@ import java.util.UUID; import java.util.function.BiFunction; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -1480,8 +1481,11 @@ void testListReturnsEachTasksReviewersAndDomainsAsAGetByIdDoes(TestNamespace ns) void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { SharedEntities shared = SharedEntities.get(); String assignee = shared.USER1.getFullyQualifiedName(); - Domain domainZ = createDomain(ns, "order-zz"); - Domain domainA = createDomain(ns, "order-aa"); + List domains = + Stream.of("e", "d", "c", "b", "a") + .map(letter -> createDomain(ns, "order-" + letter)) + .toList(); + Domain firstDomain = domains.getFirst(); String suffix = UUID.randomUUID().toString().substring(0, 8); String aboutName = "orderabout" + suffix; User about = @@ -1491,17 +1495,17 @@ void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { new CreateUser() .withName(aboutName) .withEmail(aboutName + "@test.om.org") - .withDomains( - List.of(domainZ.getFullyQualifiedName(), domainA.getFullyQualifiedName()))); - String reviewerZ = "orderrevz" + suffix; - String reviewerA = "orderreva" + suffix; - for (String name : List.of(reviewerZ, reviewerA)) { + .withDomains(domains.stream().map(Domain::getFullyQualifiedName).toList())); + List reviewersCreated = + Stream.of("d", "c", "b", "a").map(letter -> "orderrev" + letter + suffix).toList(); + for (String name : reviewersCreated) { SdkClients.adminClient() .users() .create(new CreateUser().withName(name).withEmail(name + "@test.om.org")); } Table inDomainZ = - createTableWithDomainAndOwners(ns, domainZ.getEntityReference(), List.of(shared.USER1_REF)); + createTableWithDomainAndOwners( + ns, firstDomain.getEntityReference(), List.of(shared.USER1_REF)); Table withoutDomain = createTableWithDomainAndOwners(ns, null, List.of(shared.USER1_REF)); Task aboutUser = SdkClients.adminClient() @@ -1516,14 +1520,15 @@ void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { .create( createTaskRequestAboutTable(ns, "order-reviewers", inDomainZ) .withAssignees(List.of(assignee)) - .withReviewers(List.of(reviewerZ, reviewerA))); + .withReviewers(reviewersCreated)); Task noDomain = SdkClients.adminClient() .tasks() .create( createTaskRequestAboutTable(ns, "order-none", withoutDomain) .withAssignees(List.of(assignee))); - String filter = domainZ.getFullyQualifiedName() + "," + domainA.getFullyQualifiedName(); + String filter = + domains.stream().map(Domain::getFullyQualifiedName).collect(Collectors.joining(",")); ListResponse assigned = SdkClients.user1Client() @@ -1540,8 +1545,8 @@ void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { ListResponse owned = SdkClients.user1Client().tasks().listOwned(null, "open", filter, "reviewers,domains"); - List domainsOfUser = List.of(domainA.getName(), domainZ.getName()); - List reviewersInOrder = List.of(reviewerA, reviewerZ); + List domainsOfUser = domains.reversed().stream().map(Domain::getName).toList(); + List reviewersInOrder = reviewersCreated.reversed(); for (ListResponse listed : List.of(assigned, created)) { assertEquals(domainsOfUser, namesOf(taskIn(listed, aboutUser).getDomains())); assertEquals(reviewersInOrder, namesOf(taskIn(listed, twoReviewers).getReviewers())); From 97e120e0998dd0ab05001b28624d17ce98db5aab Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 3 Dec 2026 13:25:22 -0800 Subject: [PATCH 175/203] Name the CSV rows the record's guard imports --- ...-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index a5259cb20525..f6ac54ab44f9 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-12-01 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, a hard delete, and a CSV import that changes a generated test's threshold, refused by the dry run and by the real import with the same message, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, who may approve or reject, and that a filer owner finds the task under assigned and not under created), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (a list of tasks gives the reviewers and domains that a GET gives, in the same order, including a task with none) +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, a hard delete, and a CSV import that changes a generated test's threshold or its test definition, refused by the dry run and by the real import with the same message, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, who may approve or reject, and that a filer owner finds the task under assigned and not under created), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (a list of tasks gives the reviewers and domains that a GET gives, in the same order, including a task with none) - **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) ## Context From 077a3b80f6fdf0bae49bc2a12d9bf83c2bd20bb8 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 07:50:28 -0800 Subject: [PATCH 176/203] Test a list that asks for domains alone and for reviewers alone, and say in the record how a list sorts them --- ...ck-reaches-its-table-as-a-proposed-test.md | 14 ++++++++------ .../openmetadata/it/tests/TaskResourceIT.java | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index f6ac54ab44f9..93bfcd0417f7 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-12-01 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, a hard delete, and a CSV import that changes a generated test's threshold or its test definition, refused by the dry run and by the real import with the same message, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, who may approve or reject, and that a filer owner finds the task under assigned and not under created), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (a list of tasks gives the reviewers and domains that a GET gives, in the same order, including a task with none) +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, a hard delete, and a CSV import that changes a generated test's threshold or its test definition, refused by the dry run and by the real import with the same message, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, who may approve or reject, and that the owner whose activation filed the task finds it under assigned and not under created, and keeps it after that owner is deleted), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (`testListGivesReviewersAndDomainsInTheOrderAGetDoes`: a list of tasks gives the reviewers and domains in the order a GET gives, from a list that asks for both fields and from a list that asks for `domains` alone and one that asks for `reviewers` alone, including a task with none; `testCreatorWhoIsAlsoAssigneeCannotApprove`: a user who files a task and is also its assignee is refused when they resolve it, while another assignee may approve it) - **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) ## Context @@ -35,7 +35,8 @@ assignee. An owner denied `CreateTests` may then neither approve nor reject it, resolves it. A table with no owner leaves such a task with no assignee, and an administrator resolves it. Its source is `Ingestion`, because a deterministic compile of a shape wrote it, and no agent or model did. The governance bot files the task, not the person whose change started the run, -because `TaskAuthorPolicy` refuses a non-administrator's resolve of a task they filed, and that +because `TaskAuthorPolicy`, which every user holds through the organization's default role, +refuses a non-administrator's resolve of a task they filed, and that person is often the owner the task asks. So the task is not among the tasks that person created, and deleting that person leaves the task in place. @@ -106,8 +107,8 @@ parameter values or `generatedBy` by anyone but the reconcile, with a 400 that s from a shape. A create that sends `generatedBy` is a 400, and so is a patch that changes it. A PUT keeps the stored `generatedBy`, so a PUT that changes only the description, owners or tags succeeds. A PUT finds a test by its entity link and name, so a PUT with another entity link creates a separate -test and leaves the generated one as it was. A CSV import runs the same check, and its dry run -reports the rows the real import refuses. The description, owners and tags stay editable, and a +test and leaves the generated one as it was. A CSV import runs the same check in its dry run and in the real import, so the dry run +reports a row that changes what the shape freezes. The description, owners and tags stay editable, and a person may delete the test. A test a person deleted is not brought back unless the content changes. **What a test costs and reads.** The test is added to the basic test suite of its table, created if @@ -119,8 +120,9 @@ deployment allows, so the schedule stays daily at midnight. A check reads every the runner executes the statement of a `tableCustomSQLQuery` test with `COUNT` as written, on its own session, and never through the sampled data set that built-in tests read, whatever sample the table, its schema, its database or the pipeline sets. A list of tasks reads the reviewers and the -domains of all its tasks together, not task by task, and gives each task the reviewers and domains -that a GET of it gives, in the same order, deleted reviewers included. +domains of all its tasks together, not task by task, and gives each task the reviewers and domains that a GET of it gives, sorted by name as a GET +sorts them, deleted reviewers included. Two domains with the same name, which sub-domains +under different parents can have, come in no fixed order in either. **What a caller reads.** Each check of `GET /v1/ontologyConcepts/{id}/shapeChecks` has a `proposal`: `none`, `proposed` with the task, `rejected` with the task, or `accepted` with the test case and the diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index 82a488617f78..2fac703a4961 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -1573,6 +1573,25 @@ void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { .tasks() .get(aboutUser.getId().toString(), "domains") .getDomains())); + ListResponse domainsOnly = + SdkClients.adminClient() + .tasks() + .listWithFilters( + Map.of("aboutEntity", about.getFullyQualifiedName(), "fields", "domains")); + assertEquals( + List.of("order-a", "order-b", "order-c", "order-d", "order-e").stream() + .map(ns::prefix) + .toList(), + namesOf(taskIn(domainsOnly, aboutUser).getDomains())); + ListResponse reviewersOnly = + SdkClients.adminClient() + .tasks() + .listWithFilters( + Map.of("aboutEntity", inDomainZ.getFullyQualifiedName(), "fields", "reviewers")); + assertEquals( + List.of( + "orderreva" + suffix, "orderrevb" + suffix, "orderrevc" + suffix, "orderrevd" + suffix), + namesOf(taskIn(reviewersOnly, twoReviewers).getReviewers())); } private static List namesOf(List references) { From eb153d69683ee93bc1c58a4cdf0f3e3c32dcf5b0 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 11:08:51 -0800 Subject: [PATCH 177/203] Say in the record only what its tests assert, and list six reviewers in reverse name order --- ...eck-reaches-its-table-as-a-proposed-test.md | 10 ++++++---- .../openmetadata/it/tests/TaskResourceIT.java | 18 ++++++++++++------ .../service/jdbi3/TestCaseRepository.java | 9 +++++---- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md index 93bfcd0417f7..5eb86fc41745 100644 --- a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-12-01 (initial) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, a hard delete, and a CSV import that changes a generated test's threshold or its test definition, refused by the dry run and by the real import with the same message, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, who may approve or reject, and that the owner whose activation filed the task finds it under assigned and not under created, and keeps it after that owner is deleted), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (`testListGivesReviewersAndDomainsInTheOrderAGetDoes`: a list of tasks gives the reviewers and domains in the order a GET gives, from a list that asks for both fields and from a list that asks for `domains` alone and one that asks for `reviewers` alone, including a task with none; `testCreatorWhoIsAlsoAssigneeCannotApprove`: a user who files a task and is also its assignee is refused when they resolve it, while another assignee may approve it) +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, a hard delete, and a CSV import that changes a generated test's threshold or its test definition, refused by the dry run and by the real import with the same message, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, who may approve or reject, and that the owner whose activation filed the task finds it under assigned and not under created), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (`testListGivesReviewersAndDomainsInTheOrderAGetDoes`: a list of tasks gives the reviewers and domains in the order a GET gives, from a list that asks for both fields, including a task with none, and from a list that asks for `domains` alone and one that asks for `reviewers` alone; `testCreatorWhoIsAlsoAssigneeCannotApprove`: a non-administrator who files a task and is also its assignee is refused when they approve it, while another assignee may approve it) - **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) ## Context @@ -107,8 +107,9 @@ parameter values or `generatedBy` by anyone but the reconcile, with a 400 that s from a shape. A create that sends `generatedBy` is a 400, and so is a patch that changes it. A PUT keeps the stored `generatedBy`, so a PUT that changes only the description, owners or tags succeeds. A PUT finds a test by its entity link and name, so a PUT with another entity link creates a separate -test and leaves the generated one as it was. A CSV import runs the same check in its dry run and in the real import, so the dry run -reports a row that changes what the shape freezes. The description, owners and tags stay editable, and a +test and leaves the generated one as it was. A CSV import runs the same check in its dry run and in +the real import, so the dry run reports a row that changes what the shape freezes. The description, +owners and tags stay editable, and a person may delete the test. A test a person deleted is not brought back unless the content changes. **What a test costs and reads.** The test is added to the basic test suite of its table, created if @@ -120,7 +121,8 @@ deployment allows, so the schedule stays daily at midnight. A check reads every the runner executes the statement of a `tableCustomSQLQuery` test with `COUNT` as written, on its own session, and never through the sampled data set that built-in tests read, whatever sample the table, its schema, its database or the pipeline sets. A list of tasks reads the reviewers and the -domains of all its tasks together, not task by task, and gives each task the reviewers and domains that a GET of it gives, sorted by name as a GET +domains of all its tasks together, not task by task, and gives each task the reviewers and domains +that a GET of it gives, sorted by name as a GET sorts them, deleted reviewers included. Two domains with the same name, which sub-domains under different parents can have, come in no fixed order in either. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index 2fac703a4961..9ef5cf8e63ed 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -1497,7 +1497,17 @@ void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { .withEmail(aboutName + "@test.om.org") .withDomains(domains.stream().map(Domain::getFullyQualifiedName).toList())); List reviewersCreated = - Stream.of("d", "c", "b", "a").map(letter -> "orderrev" + letter + suffix).toList(); + Stream.of("f", "e", "d", "c", "b", "a") + .map(letter -> "orderrev" + letter + suffix) + .toList(); + List reviewersInOrder = + List.of( + "orderreva" + suffix, + "orderrevb" + suffix, + "orderrevc" + suffix, + "orderrevd" + suffix, + "orderreve" + suffix, + "orderrevf" + suffix); for (String name : reviewersCreated) { SdkClients.adminClient() .users() @@ -1546,7 +1556,6 @@ void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { SdkClients.user1Client().tasks().listOwned(null, "open", filter, "reviewers,domains"); List domainsOfUser = domains.reversed().stream().map(Domain::getName).toList(); - List reviewersInOrder = reviewersCreated.reversed(); for (ListResponse listed : List.of(assigned, created)) { assertEquals(domainsOfUser, namesOf(taskIn(listed, aboutUser).getDomains())); assertEquals(reviewersInOrder, namesOf(taskIn(listed, twoReviewers).getReviewers())); @@ -1588,10 +1597,7 @@ void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { .tasks() .listWithFilters( Map.of("aboutEntity", inDomainZ.getFullyQualifiedName(), "fields", "reviewers")); - assertEquals( - List.of( - "orderreva" + suffix, "orderrevb" + suffix, "orderrevc" + suffix, "orderrevd" + suffix), - namesOf(taskIn(reviewersOnly, twoReviewers).getReviewers())); + assertEquals(reviewersInOrder, namesOf(taskIn(reviewersOnly, twoReviewers).getReviewers())); } private static List namesOf(List references) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index 00d6befd72e0..a8b8386239da 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -902,8 +902,8 @@ public void prepareInternal(TestCase test, TestCase stored) { } /** - * A stored test that comes from a shape keeps what the shape freezes. Both the real import and - * its dry run call this, so the dry run reports the rows the real import refuses. + * A stored test that comes from a shape keeps what the shape freezes. The real import and its + * dry run run this same check, so the dry run reports a row that changes what the shape freezes. */ private void requireGeneratedScope(TestCase test, TestCase stored) { if (stored != null && stored.getGeneratedBy() != null) { @@ -919,8 +919,9 @@ private void requireGeneratedScope(TestCase test, TestCase stored) { /** * Runs the checks {@link #prepareInternal} runs for a test case, minus the basic test suite, so a - * CSV dry run reports the rows the real import would and creates nothing. It takes the stored - * test the row names, or null when the row creates one. + * CSV dry run creates nothing. The dry run and the real import run the same check of what a + * shape freezes, so the dry run reports a row that changes it. It takes the stored test the row + * names, or null when the row creates one. */ void checkForImport(TestCase test, TestCase stored) { final boolean isUpdate = stored != null; From 71ab4d344eb71822e3b6c1a06f75d8fcac480121 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 13:06:30 -0800 Subject: [PATCH 178/203] Regenerate the UI types for proposed tests --- .../generated/api/data/ontologyShapeChecks.ts | 80 +++- .../ui/src/generated/tests/testCase.ts | 72 +++ .../src/generated/type/suggestionPayload.ts | 8 +- .../ui/src/generated/type/testCaseProposal.ts | 434 ++++++++++++++++++ 4 files changed, 582 insertions(+), 12 deletions(-) create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/type/testCaseProposal.ts diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyShapeChecks.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyShapeChecks.ts index 5f5ac26467d1..648450409b72 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyShapeChecks.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyShapeChecks.ts @@ -126,6 +126,10 @@ export interface Check { * The statement returns one number, the records in violation. */ parameterValues: TestCaseParameterValue[]; + /** + * How the check stands as a test on its table. + */ + proposal?: Proposal; /** * Every table binding the check read: the identity table of the class, the table that holds * the property, and the identity table of the class a `class` part names. All revisions @@ -161,31 +165,69 @@ export interface TestCaseParameterValue { } /** - * One table binding that a check was built from, with the binding revision of its class. + * How the check stands as a test on its table. + * + * How a check stands as a test on its table. A reference is left out when the caller may + * not view the task or the test case. */ -export interface ReadBinding { +export interface Proposal { /** - * Id of the bound table. + * Status of the latest result of the test case. Absent when it has no result or the caller + * may not view the test case. */ - assetId: string; + latestResultStatus?: TestCaseStatus; /** - * Id of the class that binds the table. + * Time of the latest result of the test case. */ - conceptId: string; + latestResultTimestamp?: number; + state: ProposalState; /** - * Revision of the bindings of the class, as the bindings endpoint returns it. + * The suggestion task. Present for `proposed` and `rejected` when the caller may view it. */ - revision: number; + task?: EntityReference; + /** + * The test case. Present for `accepted` when the caller may view it. + */ + testCase?: EntityReference; } /** - * The table the test belongs to: the one whose binding holds the property, which is a link - * table when a link table holds a relation. + * Status of the latest result of the test case. Absent when it has no result or the caller + * may not view the test case. + * + * Status of Test Case run. + */ +export enum TestCaseStatus { + Aborted = "Aborted", + Failed = "Failed", + Queued = "Queued", + Success = "Success", +} + +/** + * Whether a check has reached its table as a test case. `none`: no proposal exists. + * `proposed`: a suggestion task is open. `rejected`: a person rejected the suggestion of + * the current content. `accepted`: the test case exists. + */ +export enum ProposalState { + Accepted = "accepted", + None = "none", + Proposed = "proposed", + Rejected = "rejected", +} + +/** + * The suggestion task. Present for `proposed` and `rejected` when the caller may view it. * * This schema defines the EntityReference type used for referencing an entity. * EntityReference is used for capturing relationships from one entity to another. For * example, a table has an attribute called database of type EntityReference that captures * the relationship of a table `belongs to a` database. + * + * The test case. Present for `accepted` when the caller may view it. + * + * The table the test belongs to: the one whose binding holds the property, which is a link + * table when a link table holds a relation. */ export interface EntityReference { /** @@ -230,6 +272,24 @@ export interface EntityReference { type: string; } +/** + * One table binding that a check was built from, with the binding revision of its class. + */ +export interface ReadBinding { + /** + * Id of the bound table. + */ + assetId: string; + /** + * Id of the class that binds the table. + */ + conceptId: string; + /** + * Revision of the bindings of the class, as the bindings endpoint returns it. + */ + revision: number; +} + /** * How a part is checked. `check` carries the tests that check it. `heldByMapping` needs no * test, because the table bindings already hold the part for every record. `notMapped` diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCase.ts b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCase.ts index e2f987df0c6b..0955e727fb15 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCase.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCase.ts @@ -87,6 +87,12 @@ export interface TestCase { * FullyQualifiedName same as `name`. */ fullyQualifiedName?: string; + /** + * Present when the server generated this test from a shape constraint. A create or a patch + * that sends it is refused, and so is a change to the test definition, the entity link or + * the parameter values of such a test. + */ + generatedBy?: GeneratedBy; /** * Link to the resource corresponding to this entity. */ @@ -257,6 +263,10 @@ export interface FieldChange { * defaults to the dimension of the test definition. Any dimension registered in Settings > * Preferences > Data Quality can be used, system and custom alike. * + * The class whose records the test counts violations of. + * + * The shape whose constraint the test checks. + * * Test case reference * * User working on failure resolution. @@ -374,6 +384,68 @@ export interface TableExecutionSource { tableName: string; } +/** + * Present when the server generated this test from a shape constraint. A create or a patch + * that sends it is refused, and so is a change to the test definition, the entity link or + * the parameter values of such a test. + * + * Where a generated test comes from: the part of a shape constraint it checks on one table. + * Only a suggestion that creates the test and the server's own reconcile set it, and the + * test definition, the entity link and the parameter values of such a test cannot be edited. + */ +export interface GeneratedBy { + /** + * The class whose records the test counts violations of. + */ + class: EntityReference; + /** + * Id of the constraint within its shape. + */ + constraintId: string; + /** + * Lowercase hex SHA-256 of the canonical JSON of the test definition, the entity link and + * the parameter values. + */ + contentDigest: string; + /** + * Lowercase hex SHA-256 that names the check. It holds no test definition and no value of + * the constraint, so a changed bound keeps it. + */ + identity: string; + /** + * The part of the constraint the test checks: minCount, maxCount, class, datatype, range, + * in or pattern. + */ + part: string; + /** + * Every table binding the statement was built from. + */ + readBindings: GeneratedByBinding[]; + /** + * The shape whose constraint the test checks. + */ + shape: EntityReference; +} + +/** + * One table binding that the statement of a generated test was built from, with the binding + * revision of its class. + */ +export interface GeneratedByBinding { + /** + * Id of the bound table. + */ + assetId: string; + /** + * Id of the class that binds the table. + */ + conceptId: string; + /** + * Revision of the bindings of the class when the test was generated. + */ + revision: number; +} + /** * Latest incident resolution status for this test case. Inlined so clients can render the * current incident status without an additional lookup per test case. diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/suggestionPayload.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/suggestionPayload.ts index cef1a67ed4cd..7e504f109d7b 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/type/suggestionPayload.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/suggestionPayload.ts @@ -26,7 +26,8 @@ export interface SuggestionPayload { * Path to the property being updated. For a Description or Tag suggestion it is written as * .[....]., for example * 'columns.customer_id.description', or 'description' / 'tags' alone for the entity itself. - * A TableConstraint suggestion's path is 'tableConstraints'. + * A TableConstraint suggestion's path is 'tableConstraints'. A TestCase suggestion's path + * is 'testCases'. */ fieldPath: string; /** @@ -41,7 +42,9 @@ export interface SuggestionPayload { * Suggested new value for the field. For a TableConstraint suggestion it is one * tableConstraint object written as JSON: its constraintType (PRIMARY_KEY, UNIQUE or * FOREIGN_KEY), its columns, and for a foreign key its referredColumns as full column names - * and its relationshipType. + * and its relationshipType. For a TestCase suggestion it is a testCaseProposal written as + * JSON: the test case to create, with the statement that lists the records it counts and + * where it comes from. */ suggestedValue: string; /** @@ -70,5 +73,6 @@ export enum SuggestionType { Owner = "Owner", TableConstraint = "TableConstraint", Tag = "Tag", + TestCase = "TestCase", Tier = "Tier", } diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/type/testCaseProposal.ts b/openmetadata-ui/src/main/resources/ui/src/generated/type/testCaseProposal.ts new file mode 100644 index 000000000000..7e2bd754232a --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/type/testCaseProposal.ts @@ -0,0 +1,434 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The suggested value of a TestCase suggestion: the test case to create, the statement that + * lists the records it counts, and where it comes from. Approving the suggestion creates + * the test case with those values and nothing else. + */ +export interface TestCaseProposal { + /** + * Where the test comes from. It carries the identity of the check, the table bindings it + * was built from and the digest of its content. + */ + generatedBy: GeneratedBy; + /** + * The statement that lists the keys of the records the test counts, for a person to read. + * It is stored on the test case as it is, and no test runner executes it. + */ + inspectionQuery: string; + /** + * The test case to create, in the shape a request to create a test case takes. + */ + testCase: CreateTestCaseRequest; +} + +/** + * Where the test comes from. It carries the identity of the check, the table bindings it + * was built from and the digest of its content. + * + * Where a generated test comes from: the part of a shape constraint it checks on one table. + * Only a suggestion that creates the test and the server's own reconcile set it, and the + * test definition, the entity link and the parameter values of such a test cannot be edited. + */ +export interface GeneratedBy { + /** + * The class whose records the test counts violations of. + */ + class: EntityReference; + /** + * Id of the constraint within its shape. + */ + constraintId: string; + /** + * Lowercase hex SHA-256 of the canonical JSON of the test definition, the entity link and + * the parameter values. + */ + contentDigest: string; + /** + * Lowercase hex SHA-256 that names the check. It holds no test definition and no value of + * the constraint, so a changed bound keeps it. + */ + identity: string; + /** + * The part of the constraint the test checks: minCount, maxCount, class, datatype, range, + * in or pattern. + */ + part: string; + /** + * Every table binding the statement was built from. + */ + readBindings: GeneratedByBinding[]; + /** + * The shape whose constraint the test checks. + */ + shape: EntityReference; +} + +/** + * The class whose records the test counts violations of. + * + * This schema defines the EntityReference type used for referencing an entity. + * EntityReference is used for capturing relationships from one entity to another. For + * example, a table has an attribute called database of type EntityReference that captures + * the relationship of a table `belongs to a` database. + * + * The shape whose constraint the test checks. + * + * Owners of this test + * + * This schema defines the EntityReferenceList type used for referencing an entity. + * EntityReference is used for capturing relationships from one entity to another. For + * example, a table has an attribute called database of type EntityReference that captures + * the relationship of a table `belongs to a` database. + */ +export interface EntityReference { + /** + * If true the entity referred to has been soft-deleted. + */ + deleted?: boolean; + /** + * Optional description of entity. + */ + description?: string; + /** + * Display Name that identifies this entity. + */ + displayName?: string; + /** + * Fully qualified name of the entity instance. For entities such as tables, databases + * fullyQualifiedName is returned in this field. For entities that don't have name hierarchy + * such as `user` and `team` this will be same as the `name` field. + */ + fullyQualifiedName?: string; + /** + * Link to the entity resource. + */ + href?: string; + /** + * Unique identifier that identifies an entity instance. + */ + id: string; + /** + * If true the relationship indicated by this entity reference is inherited from the parent + * entity. + */ + inherited?: boolean; + /** + * Name of the entity instance. + */ + name?: string; + /** + * Entity type/class name - Examples: `database`, `table`, `metrics`, `databaseService`, + * `dashboardService`... + */ + type: string; +} + +/** + * One table binding that the statement of a generated test was built from, with the binding + * revision of its class. + */ +export interface GeneratedByBinding { + /** + * Id of the bound table. + */ + assetId: string; + /** + * Id of the class that binds the table. + */ + conceptId: string; + /** + * Revision of the bindings of the class when the test was generated. + */ + revision: number; +} + +/** + * The test case to create, in the shape a request to create a test case takes. + * + * Test is a test definition to capture data quality tests. + */ +export interface CreateTestCaseRequest { + /** + * Compute the passed and failed row count for the test case. + */ + computePassedFailedRowCount?: boolean; + /** + * Name of the data quality dimension this test case belongs to. When not set, it defaults + * to the dimension of the test definition. Any dimension registered in Settings > + * Preferences > Data Quality can be used, system and custom alike. + */ + dataQualityDimension?: string; + /** + * Description of the testcase. + */ + description?: string; + /** + * List of columns to group test results by dimensions. When specified, the test will be + * executed both overall and grouped by these columns to provide fine-grained data quality + * insights. + */ + dimensionColumns?: string[]; + /** + * Display Name that identifies this test. + */ + displayName?: string; + entityLink: string; + /** + * Name that identifies this test case. + */ + name: string; + /** + * Owners of this test + */ + owners?: EntityReference[]; + parameterValues?: TestCaseParameterValue[]; + /** + * Reviewers of this test + */ + reviewers?: EntityReference[]; + /** + * Tags for this test case. This is an inherited field from the parent entity and is not set + * directly on the test case. + */ + tags?: TagLabel[]; + /** + * Fully qualified name of the test definition. + */ + testDefinition: string; + /** + * Number of top dimension values to show before grouping the rest as Others. Controls the + * cardinality of dimensional test results. Defaults to 5 when not specified. + */ + topDimensions?: number; + /** + * If the test definition supports it, use dynamic assertion to evaluate the test case. + */ + useDynamicAssertion?: boolean; +} + +/** + * This schema defines the parameter values that can be passed for a Test Case. + */ +export interface TestCaseParameterValue { + /** + * name of the parameter. Must match the parameter names in testCaseParameterDefinition + */ + name?: string; + /** + * value to be passed for the Parameters. These are input from Users. We capture this in + * string and convert during the runtime. + */ + value?: string; + [property: string]: any; +} + +/** + * This schema defines the type for labeling an entity with a Tag. + */ +export interface TagLabel { + /** + * Timestamp when this tag was applied in ISO 8601 format + */ + appliedAt?: Date; + /** + * Who it is that applied this tag (e.g: a bot, AI or a human) + */ + appliedBy?: string; + /** + * Description for the tag label. + */ + description?: string; + /** + * Display Name that identifies this tag. + */ + displayName?: string; + /** + * Link to the tag resource. + */ + href?: string; + /** + * Label type describes how a tag label was applied. 'Manual' indicates the tag label was + * applied by a person. 'Derived' indicates a tag label was derived using the associated tag + * relationship (see Classification.json for more details). 'Propagated` indicates a tag + * label was propagated from upstream based on lineage. 'Automated' is used when a tool was + * used to determine the tag label. + */ + labelType: LabelType; + /** + * Additional metadata associated with this tag label, such as recognizer information for + * automatically applied tags. + */ + metadata?: TagLabelMetadata; + /** + * Name of the tag or glossary term. + */ + name?: string; + /** + * An explanation of why this tag was proposed, specially for autoclassification tags + */ + reason?: string; + /** + * Label is from Tags or Glossary. + */ + source: TagSource; + /** + * 'Suggested' state is used when a tag label is suggested by users or tools. Owner of the + * entity must confirm the suggested labels before it is marked as 'Confirmed'. + */ + state: State; + style?: Style; + tagFQN: string; +} + +/** + * Label type describes how a tag label was applied. 'Manual' indicates the tag label was + * applied by a person. 'Derived' indicates a tag label was derived using the associated tag + * relationship (see Classification.json for more details). 'Propagated` indicates a tag + * label was propagated from upstream based on lineage. 'Automated' is used when a tool was + * used to determine the tag label. + */ +export enum LabelType { + Automated = "Automated", + Derived = "Derived", + Generated = "Generated", + Manual = "Manual", + Propagated = "Propagated", +} + +/** + * Additional metadata associated with this tag label, such as recognizer information for + * automatically applied tags. + * + * Additional metadata associated with a tag label, including information about how the tag + * was applied. + */ +export interface TagLabelMetadata { + /** + * Epoch time in milliseconds when the certification tag expires + */ + expiryDate?: number; + /** + * Metadata about the recognizer that automatically applied this tag + */ + recognizer?: TagLabelRecognizerMetadata; +} + +/** + * Metadata about the recognizer that automatically applied this tag + * + * Metadata about the recognizer that applied a tag, including scoring and pattern + * information. + */ +export interface TagLabelRecognizerMetadata { + /** + * Details of patterns that matched during recognition + */ + patterns?: PatternMatch[]; + /** + * Unique identifier of the recognizer that applied this tag + */ + recognizerId: string; + /** + * Human-readable name of the recognizer + */ + recognizerName: string; + /** + * Confidence score assigned by the recognizer (0.0 to 1.0) + */ + score: number; + /** + * What the recognizer analyzed to apply this tag + */ + target?: Target; +} + +/** + * Information about a pattern that matched during recognition + */ +export interface PatternMatch { + /** + * Name of the pattern that matched + */ + name: string; + /** + * Regular expression or pattern definition + */ + regex?: string; + /** + * Confidence score for this specific pattern match + */ + score: number; +} + +/** + * What the recognizer analyzed to apply this tag + */ +export enum Target { + ColumnName = "column_name", + Content = "content", +} + +/** + * Label is from Tags or Glossary. + */ +export enum TagSource { + Classification = "Classification", + Glossary = "Glossary", +} + +/** + * 'Suggested' state is used when a tag label is suggested by users or tools. Owner of the + * entity must confirm the suggested labels before it is marked as 'Confirmed'. + */ +export enum State { + Confirmed = "Confirmed", + Suggested = "Suggested", +} + +/** + * UI Style is used to associate a color code and/or icon to entity to customize the look of + * that entity in UI. + */ +export interface Style { + /** + * Hex Color Code to mark an entity such as GlossaryTerm, Tag, Domain or Data Product. + */ + color?: string; + /** + * Cover image configuration for the entity. + */ + coverImage?: CoverImage; + /** + * An icon to associate with GlossaryTerm, Tag, Domain or Data Product. + */ + iconURL?: string; +} + +/** + * Cover image configuration for the entity. + * + * Cover image configuration for an entity. This is used to display a banner or header image + * for entities like Domain, Glossary, Data Product, etc. + */ +export interface CoverImage { + /** + * Position of the cover image in CSS background-position format. Supports keywords (top, + * center, bottom) or pixel values (e.g., '20px 30px'). + */ + position?: string; + /** + * URL of the cover image. + */ + url?: string; +} From 310956358a77a39fea0fa1565a10c457fd53d653 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 14:12:31 -0800 Subject: [PATCH 179/203] Mapping health names a sensitive key column and a column whose type cannot hold its property --- .../ontology/OntologyBindingAccess.java | 8 +- .../ontology/OntologyBindingRules.java | 22 +- .../ontology/OntologyColumnTypeFit.java | 117 +++ .../ontology/OntologyMappingHealthRules.java | 48 ++ .../OntologyMappingHealthService.java | 10 +- .../service/security/mask/PIIMasker.java | 13 +- .../OntologyMappingAdviceRulesTest.java | 689 ++++++++++++++++++ .../api/data/ontologyMappingHealth.json | 16 +- 8 files changed, 908 insertions(+), 15 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java index dbbb4b8f071e..b94520a234df 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java @@ -127,10 +127,16 @@ void require( /** The live entities of one type that the caller may view, by id, read in one statement. */ Map> viewable( final Access access, final String type, final Collection ids) { + return viewable(access, type, ids, Set.of()); + } + + /** As above, with the fields in {@code extra} loaded as well. */ + Map> viewable( + final Access access, final String type, final Collection ids, final Set extra) { final Map> viewable = new HashMap<>(); final EntityRepository repository = repositories.apply(type); loadViewable( - access, repository, ids.stream().distinct().toList(), viewable, fields(repository)); + access, repository, ids.stream().distinct().toList(), viewable, fields(repository, extra)); return viewable; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java index 872f23f3c517..28ebb3038627 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java @@ -4,6 +4,7 @@ import jakarta.ws.rs.ClientErrorException; import jakarta.ws.rs.core.Response; +import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -218,17 +219,30 @@ public static void requireColumnCapacity(final int boundColumns) { } public static Column resolveColumn(final Table table, final List path) { + final List resolved = resolveColumnPath(table, path); + return resolved.isEmpty() ? null : resolved.getLast(); + } + + /** + * The columns from a top-level column down to the one {@code path} names, one for each segment, + * or an empty list when a segment names no column. + */ + public static List resolveColumnPath(final Table table, final List path) { + final List resolved = new ArrayList<>(); List candidates = ChildFieldResolver.childrenOf(table, Entity.TABLE); - FieldInterface selected = null; for (final String segment : path) { - selected = + final FieldInterface selected = candidates.stream() .filter(column -> segment.equals(column.getName())) .findFirst() .orElse(null); - candidates = selected == null ? List.of() : listOrEmpty(selected.getChildren()); + if (!(selected instanceof Column column)) { + return List.of(); + } + resolved.add(column); + candidates = listOrEmpty(column.getChildren()); } - return selected instanceof Column column ? column : null; + return resolved; } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java new file mode 100644 index 000000000000..5f1728db43d7 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java @@ -0,0 +1,117 @@ +package org.openmetadata.service.ontology; + +import java.net.URI; +import java.util.EnumSet; +import java.util.Set; +import org.openmetadata.schema.type.ColumnDataType; + +/** + * Whether a column's type can hold the values of an XSD datatype. A datatype that is not listed + * here fits every column, and a column type that is neither numeric, text, a date or time, + * {@code BOOLEAN} nor {@code BIT} is never reported, since it may hold any value as text. + */ +final class OntologyColumnTypeFit { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + + private static final Set NUMERIC_DATATYPES = + Set.of( + "integer", + "int", + "long", + "short", + "byte", + "nonNegativeInteger", + "positiveInteger", + "negativeInteger", + "nonPositiveInteger", + "unsignedLong", + "unsignedInt", + "unsignedShort", + "unsignedByte", + "decimal", + "float", + "double"); + + private static final Set DATE_DATATYPES = Set.of("date", "dateTime", "dateTimeStamp"); + private static final String TIME_DATATYPE = "time"; + private static final String BOOLEAN_DATATYPE = "boolean"; + + private static final Set NUMERIC = + EnumSet.of( + ColumnDataType.NUMBER, + ColumnDataType.TINYINT, + ColumnDataType.SMALLINT, + ColumnDataType.INT, + ColumnDataType.BIGINT, + ColumnDataType.BYTEINT, + ColumnDataType.LONG, + ColumnDataType.LARGEINT, + ColumnDataType.UINT, + ColumnDataType.FLOAT, + ColumnDataType.DOUBLE, + ColumnDataType.DECIMAL, + ColumnDataType.NUMERIC, + ColumnDataType.MONEY); + + private static final Set TEXT = + EnumSet.of( + ColumnDataType.STRING, + ColumnDataType.CHAR, + ColumnDataType.VARCHAR, + ColumnDataType.TEXT, + ColumnDataType.MEDIUMTEXT, + ColumnDataType.NTEXT, + ColumnDataType.CLOB); + + private static final Set DATES = + EnumSet.of( + ColumnDataType.DATE, + ColumnDataType.TIMESTAMP, + ColumnDataType.TIMESTAMPZ, + ColumnDataType.DATETIME); + + private static final Set FLAGS = + EnumSet.of(ColumnDataType.BOOLEAN, ColumnDataType.BIT); + + private OntologyColumnTypeFit() {} + + /** Whether a column of {@code type} is one a value of {@code datatype} does not fit. */ + static boolean mismatched(final URI datatype, final ColumnDataType type) { + final Set accepted = accepted(datatype); + return accepted != null && judged(type) && !accepted.contains(type); + } + + /** The column types that hold the datatype, or null when the datatype fits every column. */ + private static Set accepted(final URI datatype) { + final String iri = datatype.toString(); + if (!iri.startsWith(XSD)) { + return null; + } + final String local = iri.substring(XSD.length()); + if (NUMERIC_DATATYPES.contains(local)) { + return NUMERIC; + } + if (DATE_DATATYPES.contains(local)) { + return DATES; + } + if (TIME_DATATYPE.equals(local)) { + return union(DATES, EnumSet.of(ColumnDataType.TIME)); + } + return BOOLEAN_DATATYPE.equals(local) ? union(FLAGS, NUMERIC) : null; + } + + private static boolean judged(final ColumnDataType type) { + return NUMERIC.contains(type) + || TEXT.contains(type) + || DATES.contains(type) + || type == ColumnDataType.TIME + || FLAGS.contains(type); + } + + private static Set union( + final Set left, final Set right) { + final Set union = EnumSet.copyOf(left); + union.addAll(right); + return union; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java index e67db9ace572..5cd97d0c64f6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java @@ -2,12 +2,14 @@ import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import java.net.URI; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.stream.IntStream; @@ -23,6 +25,7 @@ import org.openmetadata.schema.type.OntologyJoinStatus; import org.openmetadata.schema.type.OntologyPropertyKind; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.security.mask.PIIMasker; /** * What the table bindings of an ontology still need before their rows can be read as records. The @@ -147,9 +150,54 @@ private static List tableEntries( entries.addAll(keyEntries(bound, context.identities().get(bound.row().conceptId()))); listOrEmpty(bound.row().columns()) .forEach(column -> entries.addAll(columnEntries(bound, column, context))); + entries.addAll(sensitiveKeyEntries(bound)); + listOrEmpty(bound.row().columns()) + .forEach(column -> typeFitEntry(bound, column, context).ifPresent(entries::add)); return entries; } + /** A key column whose sample data and profile are masked, in key order. */ + private static List sensitiveKeyEntries(final BoundTable bound) { + if (bound.row().role() == null) { + return List.of(); + } + return listOrEmpty(bound.row().subjectKey()).stream() + .filter(path -> masked(bound.table(), path)) + .map( + path -> + entry(OntologyMappingHealthEntryType.SENSITIVE_KEY_COLUMN, bound) + .withColumnPath(path)) + .toList(); + } + + private static boolean masked(final Table table, final List path) { + final List resolved = OntologyBindingRules.resolveColumnPath(table, path); + return !resolved.isEmpty() && PIIMasker.isColumnMasked(table, resolved); + } + + /** A column bound to a DATA property whose one XSD datatype the column's type cannot hold. */ + private static Optional typeFitEntry( + final BoundTable bound, final OntologyColumnBinding column, final Context context) { + final OntologyProperty property = context.properties().get(column.getPropertyId()); + final Column resolved = + OntologyBindingRules.resolveColumn(bound.table(), column.getColumnPath()); + if (property == null + || resolved == null + || property.getKind() != OntologyPropertyKind.DATA + || listOrEmpty(property.getRange()).size() != 1) { + return Optional.empty(); + } + final URI datatype = property.getRange().getFirst(); + return OntologyColumnTypeFit.mismatched(datatype, resolved.getDataType()) + ? Optional.of( + entry(OntologyMappingHealthEntryType.COLUMN_TYPE_MISMATCH, bound) + .withProperty(property.getEntityReference()) + .withColumnPath(column.getColumnPath()) + .withDataType(resolved.getDataType()) + .withPropertyDatatype(datatype)) + : Optional.empty(); + } + /** A contributing table's key pairs with the identity table's key column by column. */ private static List keyEntries( final BoundTable bound, final Identity identity) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java index d3ab4226bfb5..6e50eaa180cc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java @@ -76,7 +76,7 @@ public OntologyMappingHealth page( /** The rows whose table and class are both live and viewable. Every other row says nothing. */ private List boundTables(final Access access, final List rows) { - final Map tables = viewableTables(access, rows); + final Map tables = viewableTables(access, rows, Set.of(Entity.FIELD_TAGS)); final var concepts = targets.viewable( access, @@ -129,7 +129,7 @@ private Map identities(final Access access, final List rows = store.identityRows(tables.stream().map(bound -> bound.row().conceptId()).toList()); final Set live = store.liveAssets(rows).keySet(); - final Map viewable = viewableTables(access, rows); + final Map viewable = viewableTables(access, rows, Set.of()); final Map identities = new HashMap<>(); rows.stream() .filter(row -> live.contains(row.assetId())) @@ -140,13 +140,15 @@ private Map identities(final Access access, final List viewableTables(final Access access, final List rows) { + private Map viewableTables( + final Access access, final List rows, final Set extra) { final Set live = store.liveAssets(rows).keySet(); return typed( targets.viewable( access, Entity.TABLE, - rows.stream().map(BindingRow::assetId).filter(live::contains).toList()), + rows.stream().map(BindingRow::assetId).filter(live::contains).toList(), + extra), Table.class); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/mask/PIIMasker.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/mask/PIIMasker.java index 542f6090662f..77c33f3e5f08 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/mask/PIIMasker.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/mask/PIIMasker.java @@ -333,6 +333,15 @@ private static String columnPathOf(String[] parts) { .collect(Collectors.joining(Entity.SEPARATOR)); } + /** + * Whether the sample data and profile of the last column of {@code columnPath}, a path from a + * top-level column of {@code table} down to the column, are masked: the table, the column or a + * column above it carries the sensitive tag. + */ + public static boolean isColumnMasked(Table table, List columnPath) { + return hasPiiSensitiveTag(table) || hasPiiSensitiveTagInPath(columnPath); + } + private static boolean hasPiiSensitiveTagInPath(List columnPath) { // The leaf's tag set covers itself and its descendants (getAllTags); ancestors only their own. if (hasPiiSensitiveTag(columnPath.getLast())) { @@ -528,7 +537,9 @@ private static boolean hasPiiSensitiveTag(Column column) { } private static boolean hasPiiSensitiveTag(Table table) { - return table.getTags().stream().map(TagLabel::getTagFQN).anyMatch(SENSITIVE_PII_TAG::equals); + return listOrEmpty(table.getTags()).stream() + .map(TagLabel::getTagFQN) + .anyMatch(SENSITIVE_PII_TAG::equals); } private static boolean hasPiiSensitiveTag(Container container) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java new file mode 100644 index 000000000000..0c2b241f5d15 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java @@ -0,0 +1,689 @@ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.BoundTable; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Context; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Identity; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Progress; + +/** The advice about sensitive key columns and about columns whose type cannot hold a property. */ +class OntologyMappingAdviceRulesTest { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + private static final EntityReference SALES = reference("database", "sales"); + private static final EntityReference CUSTOMER = reference("ontologyConcept", "Customer"); + + @Test + void aTaggedKeyColumnIsReportedAndAnUntaggedOneIsNot() { + final Table table = + table( + "customers", + column("id", ColumnDataType.BIGINT), + tagged(column("email", ColumnDataType.VARCHAR), "PII.Sensitive")); + + assertEquals( + List.of("sensitiveKeyColumn [email]"), + advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("email")), List.of())); + assertEquals( + List.of(), advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("id")), List.of())); + } + + @Test + void aKeyColumnUnderATaggedParentIsReportedAndSoIsAKeyThatCoversATaggedChild() { + final Table table = + table( + "customers", + tagged( + column("contact", ColumnDataType.STRUCT) + .withChildren(List.of(column("phone", ColumnDataType.VARCHAR))), + "PII.Sensitive"), + column("profile", ColumnDataType.STRUCT) + .withChildren( + List.of(tagged(column("ssn", ColumnDataType.VARCHAR), "PII.Sensitive")))); + + assertEquals( + List.of("sensitiveKeyColumn [contact, phone]"), + advice( + table, OntologyBindingRole.IDENTITY, List.of(List.of("contact", "phone")), List.of())); + assertEquals( + List.of("sensitiveKeyColumn [profile]"), + advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("profile")), List.of())); + assertEquals( + List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("profile", "missing")), + List.of())); + } + + @Test + void aTaggedTableReportsEveryKeyColumnInKeyOrder() { + final Table table = + tagged( + table( + "customers", + column("tenant", ColumnDataType.VARCHAR), + column("id", ColumnDataType.BIGINT)), + "PII.Sensitive"); + + assertEquals( + List.of("sensitiveKeyColumn [id]", "sensitiveKeyColumn [tenant]"), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("id"), List.of("tenant")), + List.of())); + } + + @Test + void aKeyOfTwoColumnsWithOneTaggedReportsThatColumnOnly() { + final Table table = + table( + "customers", + column("tenant", ColumnDataType.VARCHAR), + tagged(column("id", ColumnDataType.BIGINT), "PII.Sensitive")); + + assertEquals( + List.of("sensitiveKeyColumn [id]"), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("tenant"), List.of("id")), + List.of())); + } + + @Test + void aContributingTableIsCheckedAndABindingWithNoRoleIsNot() { + final Table table = + table("customers", tagged(column("id", ColumnDataType.BIGINT), "PII.Sensitive")); + + assertEquals( + List.of("sensitiveKeyColumn [id]"), + advice(table, OntologyBindingRole.CONTRIBUTING, List.of(List.of("id")), List.of())); + assertEquals(List.of(), advice(table, null, List.of(List.of("id")), List.of())); + } + + @Test + void aKeyColumnThatWasDroppedIsNoFinding() { + final Table table = + tagged(table("customers", column("id", ColumnDataType.BIGINT)), "PII.Sensitive"); + + assertEquals( + List.of(), + advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("gone")), List.of())); + } + + @Test + void otherTagsAreNotSensitive() { + final Table table = + tagged( + table( + "customers", + tagged( + column("id", ColumnDataType.BIGINT), + "PII.NonSensitive", + "Tier.Tier1", + "PII.SensitiveData")), + "PII.NonSensitive"); + + assertEquals( + List.of(), advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("id")), List.of())); + } + + @ParameterizedTest(name = "{0} against {1} is a mismatch: {2}") + @CsvSource( + delimiter = ',', + value = { + "integer,INT,false", + "integer,VARCHAR,true", + "integer,DATE,true", + "integer,TIMESTAMP,true", + "integer,TIME,true", + "integer,BOOLEAN,true", + "integer,BIT,true", + "integer,JSON,false", + "integer,UNKNOWN,false", + "int,INT,false", + "int,VARCHAR,true", + "int,DATE,true", + "int,TIMESTAMP,true", + "int,TIME,true", + "int,BOOLEAN,true", + "int,BIT,true", + "int,JSON,false", + "int,UNKNOWN,false", + "long,INT,false", + "long,VARCHAR,true", + "long,DATE,true", + "long,TIMESTAMP,true", + "long,TIME,true", + "long,BOOLEAN,true", + "long,BIT,true", + "long,JSON,false", + "long,UNKNOWN,false", + "short,INT,false", + "short,VARCHAR,true", + "short,DATE,true", + "short,TIMESTAMP,true", + "short,TIME,true", + "short,BOOLEAN,true", + "short,BIT,true", + "short,JSON,false", + "short,UNKNOWN,false", + "byte,INT,false", + "byte,VARCHAR,true", + "byte,DATE,true", + "byte,TIMESTAMP,true", + "byte,TIME,true", + "byte,BOOLEAN,true", + "byte,BIT,true", + "byte,JSON,false", + "byte,UNKNOWN,false", + "nonNegativeInteger,INT,false", + "nonNegativeInteger,VARCHAR,true", + "nonNegativeInteger,DATE,true", + "nonNegativeInteger,TIMESTAMP,true", + "nonNegativeInteger,TIME,true", + "nonNegativeInteger,BOOLEAN,true", + "nonNegativeInteger,BIT,true", + "nonNegativeInteger,JSON,false", + "nonNegativeInteger,UNKNOWN,false", + "positiveInteger,INT,false", + "positiveInteger,VARCHAR,true", + "positiveInteger,DATE,true", + "positiveInteger,TIMESTAMP,true", + "positiveInteger,TIME,true", + "positiveInteger,BOOLEAN,true", + "positiveInteger,BIT,true", + "positiveInteger,JSON,false", + "positiveInteger,UNKNOWN,false", + "negativeInteger,INT,false", + "negativeInteger,VARCHAR,true", + "negativeInteger,DATE,true", + "negativeInteger,TIMESTAMP,true", + "negativeInteger,TIME,true", + "negativeInteger,BOOLEAN,true", + "negativeInteger,BIT,true", + "negativeInteger,JSON,false", + "negativeInteger,UNKNOWN,false", + "nonPositiveInteger,INT,false", + "nonPositiveInteger,VARCHAR,true", + "nonPositiveInteger,DATE,true", + "nonPositiveInteger,TIMESTAMP,true", + "nonPositiveInteger,TIME,true", + "nonPositiveInteger,BOOLEAN,true", + "nonPositiveInteger,BIT,true", + "nonPositiveInteger,JSON,false", + "nonPositiveInteger,UNKNOWN,false", + "unsignedLong,INT,false", + "unsignedLong,VARCHAR,true", + "unsignedLong,DATE,true", + "unsignedLong,TIMESTAMP,true", + "unsignedLong,TIME,true", + "unsignedLong,BOOLEAN,true", + "unsignedLong,BIT,true", + "unsignedLong,JSON,false", + "unsignedLong,UNKNOWN,false", + "unsignedInt,INT,false", + "unsignedInt,VARCHAR,true", + "unsignedInt,DATE,true", + "unsignedInt,TIMESTAMP,true", + "unsignedInt,TIME,true", + "unsignedInt,BOOLEAN,true", + "unsignedInt,BIT,true", + "unsignedInt,JSON,false", + "unsignedInt,UNKNOWN,false", + "unsignedShort,INT,false", + "unsignedShort,VARCHAR,true", + "unsignedShort,DATE,true", + "unsignedShort,TIMESTAMP,true", + "unsignedShort,TIME,true", + "unsignedShort,BOOLEAN,true", + "unsignedShort,BIT,true", + "unsignedShort,JSON,false", + "unsignedShort,UNKNOWN,false", + "unsignedByte,INT,false", + "unsignedByte,VARCHAR,true", + "unsignedByte,DATE,true", + "unsignedByte,TIMESTAMP,true", + "unsignedByte,TIME,true", + "unsignedByte,BOOLEAN,true", + "unsignedByte,BIT,true", + "unsignedByte,JSON,false", + "unsignedByte,UNKNOWN,false", + "decimal,INT,false", + "decimal,VARCHAR,true", + "decimal,DATE,true", + "decimal,TIMESTAMP,true", + "decimal,TIME,true", + "decimal,BOOLEAN,true", + "decimal,BIT,true", + "decimal,JSON,false", + "decimal,UNKNOWN,false", + "float,INT,false", + "float,VARCHAR,true", + "float,DATE,true", + "float,TIMESTAMP,true", + "float,TIME,true", + "float,BOOLEAN,true", + "float,BIT,true", + "float,JSON,false", + "float,UNKNOWN,false", + "double,INT,false", + "double,VARCHAR,true", + "double,DATE,true", + "double,TIMESTAMP,true", + "double,TIME,true", + "double,BOOLEAN,true", + "double,BIT,true", + "double,JSON,false", + "double,UNKNOWN,false", + "date,INT,true", + "date,VARCHAR,true", + "date,DATE,false", + "date,TIMESTAMP,false", + "date,TIME,true", + "date,BOOLEAN,true", + "date,BIT,true", + "date,JSON,false", + "date,UNKNOWN,false", + "dateTime,INT,true", + "dateTime,VARCHAR,true", + "dateTime,DATE,false", + "dateTime,TIMESTAMP,false", + "dateTime,TIME,true", + "dateTime,BOOLEAN,true", + "dateTime,BIT,true", + "dateTime,JSON,false", + "dateTime,UNKNOWN,false", + "dateTimeStamp,INT,true", + "dateTimeStamp,VARCHAR,true", + "dateTimeStamp,DATE,false", + "dateTimeStamp,TIMESTAMP,false", + "dateTimeStamp,TIME,true", + "dateTimeStamp,BOOLEAN,true", + "dateTimeStamp,BIT,true", + "dateTimeStamp,JSON,false", + "dateTimeStamp,UNKNOWN,false", + "time,INT,true", + "time,VARCHAR,true", + "time,DATE,false", + "time,TIMESTAMP,false", + "time,TIME,false", + "time,BOOLEAN,true", + "time,BIT,true", + "time,JSON,false", + "time,UNKNOWN,false", + "boolean,INT,false", + "boolean,VARCHAR,true", + "boolean,DATE,true", + "boolean,TIMESTAMP,true", + "boolean,TIME,true", + "boolean,BOOLEAN,false", + "boolean,BIT,false", + "boolean,JSON,false", + "boolean,UNKNOWN,false", + "string,INT,false", + "string,VARCHAR,false", + "string,DATE,false", + "string,TIMESTAMP,false", + "string,TIME,false", + "string,BOOLEAN,false", + "string,BIT,false", + "string,JSON,false", + "string,UNKNOWN,false", + "anyURI,INT,false", + "anyURI,VARCHAR,false", + "anyURI,DATE,false", + "anyURI,TIMESTAMP,false", + "anyURI,TIME,false", + "anyURI,BOOLEAN,false", + "anyURI,BIT,false", + "anyURI,JSON,false", + "anyURI,UNKNOWN,false", + "duration,INT,false", + "duration,VARCHAR,false", + "duration,DATE,false", + "duration,TIMESTAMP,false", + "duration,TIME,false", + "duration,BOOLEAN,false", + "duration,BIT,false", + "duration,JSON,false", + "duration,UNKNOWN,false", + "hexBinary,INT,false", + "hexBinary,VARCHAR,false", + "hexBinary,DATE,false", + "hexBinary,TIMESTAMP,false", + "hexBinary,TIME,false", + "hexBinary,BOOLEAN,false", + "hexBinary,BIT,false", + "hexBinary,JSON,false", + "hexBinary,UNKNOWN,false", + "gYear,INT,false", + "gYear,VARCHAR,false", + "gYear,DATE,false", + "gYear,TIMESTAMP,false", + "gYear,TIME,false", + "gYear,BOOLEAN,false", + "gYear,BIT,false", + "gYear,JSON,false", + "gYear,UNKNOWN,false", + }) + void aColumnTypeIsCheckedAgainstTheDatatypeOfItsProperty( + final String datatype, final ColumnDataType type, final boolean mismatch) { + final Table table = table("customers", column("c", type)); + final OntologyProperty property = dataProperty("p", XSD + datatype); + + assertEquals( + mismatch ? List.of("columnTypeMismatch [c] " + type + " " + XSD + datatype) : List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(property, "c")), + property)); + } + + @Test + void aPropertyWithNoSingleDatatypeIsNeverChecked() { + final Table table = table("customers", column("c", ColumnDataType.VARCHAR)); + final OntologyProperty noRange = dataProperty("noRange"); + final OntologyProperty twoRanges = dataProperty("twoRanges", XSD + "integer", XSD + "decimal"); + final OntologyProperty classRange = dataProperty("classRange", "urn:Customer"); + final OntologyProperty relation = + property("relation", OntologyPropertyKind.OBJECT) + .withRange(List.of(URI.create(XSD + "integer"))); + + for (final OntologyProperty property : List.of(noRange, twoRanges, classRange, relation)) { + assertEquals( + List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(property, "c")), + property), + property.getName()); + } + } + + @Test + void aColumnThatWasDroppedAndADeprecatedPropertyAreHandledLikeAnyOther() { + final Table table = table("customers", column("c", ColumnDataType.VARCHAR)); + final OntologyProperty deprecated = dataProperty("old", XSD + "integer").withDeprecated(true); + + assertEquals( + List.of("columnTypeMismatch [c] VARCHAR " + XSD + "integer"), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(deprecated, "c")), + deprecated)); + assertEquals( + List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(deprecated, "gone")), + deprecated)); + } + + @Test + void aPropertyTheCallerMayNotViewGivesNoTypeFinding() { + final Table table = table("customers", column("c", ColumnDataType.VARCHAR)); + final OntologyProperty hidden = dataProperty("hidden", XSD + "integer"); + + assertEquals( + List.of(), + advice(table, OntologyBindingRole.IDENTITY, List.of(), List.of(binding(hidden, "c")))); + } + + @Test + void theFindingsOfOneTableComeInTheOrderExistingThenSensitiveKeysThenTypes() { + final Table customers = table("customers", column("id", ColumnDataType.BIGINT)); + final Table table = + tagged( + table( + "orders", + column("tenant", ColumnDataType.VARCHAR), + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT), + column("placed", ColumnDataType.VARCHAR), + column("quantity", ColumnDataType.VARCHAR)), + "PII.Sensitive"); + final OntologyProperty placedBy = property("placedBy", OntologyPropertyKind.OBJECT); + final OntologyProperty placedOn = dataProperty("placedOn", XSD + "dateTime"); + final OntologyProperty quantity = dataProperty("quantity", XSD + "integer"); + final OntologyColumnJoin inferred = + new OntologyColumnJoin() + .withTargetAssetId(customers.getId()) + .withStatus(OntologyJoinStatus.INFERRED) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of("customer_id")) + .withParent(List.of("id")))); + final BindingRow row = + row( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("tenant"), List.of("order_id")), + List.of( + binding(placedOn, "placed"), + binding(placedBy, "customer_id").withJoin(inferred), + binding(quantity, "quantity"))); + + final var entries = + OntologyMappingHealthRules.check( + List.of(new BoundTable(row, CUSTOMER, table)), + new Context( + null, + Map.of(CUSTOMER.getId(), new Identity(row, table)), + Map.of( + placedBy.getId(), + placedBy, + placedOn.getId(), + placedOn, + quantity.getId(), + quantity), + Map.of(customers.getId(), customers)), + Progress.start()) + .entries(); + + assertEquals( + List.of( + "joinNotConfirmed [customer_id]", + "sensitiveKeyColumn [tenant]", + "sensitiveKeyColumn [order_id]", + "columnTypeMismatch [placed]", + "columnTypeMismatch [quantity]"), + entries.stream() + .map(entry -> entry.getType().value() + " " + entry.getColumnPath()) + .toList()); + } + + @Test + void theEntriesCarryTheFieldsTheirTypesPromise() { + final Table table = + table( + "customers", + tagged(column("id", ColumnDataType.BIGINT), "PII.Sensitive"), + column("age", ColumnDataType.VARCHAR)); + final OntologyProperty age = dataProperty("age", XSD + "integer"); + final BindingRow row = + row( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("id")), + List.of(binding(age, "age"))); + + final List entries = + OntologyMappingHealthRules.check( + List.of(new BoundTable(row, CUSTOMER, table)), + new Context( + null, + Map.of(CUSTOMER.getId(), new Identity(row, table)), + Map.of(age.getId(), age), + Map.of()), + Progress.start()) + .entries(); + + assertEquals( + "{\"type\":\"sensitiveKeyColumn\",\"concept\":\"Customer\",\"asset\":\"customers\"," + + "\"columnPath\":[\"id\"]}", + render(entries.get(0))); + assertEquals( + "{\"type\":\"columnTypeMismatch\",\"concept\":\"Customer\",\"asset\":\"customers\"," + + "\"property\":\"age\",\"columnPath\":[\"age\"],\"dataType\":\"VARCHAR\"," + + "\"propertyDatatype\":\"http://www.w3.org/2001/XMLSchema#integer\"}", + render(entries.get(1))); + } + + private static String render(final OntologyMappingHealthEntry entry) { + final StringBuilder json = new StringBuilder("{\"type\":\"" + entry.getType().value() + "\""); + json.append(",\"concept\":\"").append(entry.getConcept().getName()).append("\""); + json.append(",\"asset\":\"").append(entry.getAsset().getName()).append("\""); + if (entry.getProperty() != null) { + json.append(",\"property\":\"").append(entry.getProperty().getName()).append("\""); + } + json.append(",\"columnPath\":[\"") + .append(String.join("\",\"", entry.getColumnPath())) + .append("\"]"); + if (entry.getDataType() != null) { + json.append(",\"dataType\":\"").append(entry.getDataType()).append("\""); + } + if (entry.getPropertyDatatype() != null) { + json.append(",\"propertyDatatype\":\"").append(entry.getPropertyDatatype()).append("\""); + } + return json.append("}").toString(); + } + + /** + * The sensitive-key and type findings of one table bound to Customer, as the type, the column + * path, and for a type finding the column type and the datatype. Properties listed in {@code + * visible} are the ones the caller may view. + */ + private static List advice( + final Table table, + final OntologyBindingRole role, + final List> key, + final List columns, + final OntologyProperty... visible) { + final BindingRow row = row(table, role, key, columns); + final Map properties = new java.util.HashMap<>(); + for (final OntologyProperty property : visible) { + properties.put(property.getId(), property); + } + return OntologyMappingHealthRules.check( + List.of(new BoundTable(row, CUSTOMER, table)), + new Context( + null, Map.of(CUSTOMER.getId(), new Identity(row, table)), properties, Map.of()), + Progress.start()) + .entries() + .stream() + .filter( + entry -> + entry.getType().value().equals("sensitiveKeyColumn") + || entry.getType().value().equals("columnTypeMismatch")) + .map( + entry -> + entry.getPropertyDatatype() == null + ? entry.getType().value() + " " + entry.getColumnPath() + : entry.getType().value() + + " " + + entry.getColumnPath() + + " " + + entry.getDataType() + + " " + + entry.getPropertyDatatype()) + .toList(); + } + + private static BindingRow row( + final Table table, + final OntologyBindingRole role, + final List> key, + final List columns) { + return new BindingRow( + CUSTOMER.getId(), + table.getId(), + OntologyBindingAssetType.TABLE, + "hash", + columns, + role, + key, + null); + } + + private static OntologyColumnBinding binding( + final OntologyProperty property, final String column) { + return new OntologyColumnBinding() + .withPropertyId(property.getId()) + .withColumnPath(List.of(column)); + } + + private static OntologyProperty dataProperty(final String name, final String... range) { + return property(name, OntologyPropertyKind.DATA) + .withRange(java.util.Arrays.stream(range).map(URI::create).toList()); + } + + private static OntologyProperty property(final String name, final OntologyPropertyKind kind) { + return new OntologyProperty() + .withId(UUID.randomUUID()) + .withName(name) + .withKind(kind) + .withFullyQualifiedName("ontology." + name); + } + + private static Table table(final String name, final Column... columns) { + return new Table() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName("service.sales.public." + name) + .withDatabase(SALES) + .withColumns(List.of(columns)) + .withTags(List.of()); + } + + private static Table tagged(final Table table, final String tag) { + return table.withTags(List.of(new TagLabel().withTagFQN(tag))); + } + + private static Column tagged(final Column column, final String... tags) { + return column.withTags( + java.util.Arrays.stream(tags).map(tag -> new TagLabel().withTagFQN(tag)).toList()); + } + + private static Column column(final String name, final ColumnDataType type) { + return new Column().withName(name).withDataType(type); + } + + private static EntityReference reference(final String type, final String name) { + return new EntityReference().withId(UUID.randomUUID()).withType(type).withName(name); + } +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json index 11acd50e7e66..d5d072ba88dd 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json @@ -13,7 +13,7 @@ "default": null }, "entryType": { - "description": "What is wrong. `noIdentityTable`: the class has table bindings and none is its identity table. `unassignedBinding`: the table binding has no role. `relationColumnWithoutJoin`: a column bound to an OBJECT property has no join. `joinNotConfirmed`: a join is still `inferred`. `keyLengthMismatch`: a contributing table's subject key has a different number of columns than the identity table's. `keyTypeMismatch`: a contributing table's key column and the identity table's key column at the same position hold different kinds of data. `joinTypeMismatch`: the two columns of a join pair hold different kinds of data. `outsideMappingSource`: the bound table sits outside the ontology's mapping source. `multipleDatabases`: the ontology names no mapping source and its bound tables sit in more than one database. It is reported on each page that finds a database no earlier page found, once two are known.", + "description": "What is wrong. `noIdentityTable`: the class has table bindings and none is its identity table. `unassignedBinding`: the table binding has no role. `relationColumnWithoutJoin`: a column bound to an OBJECT property has no join. `joinNotConfirmed`: a join is still `inferred`. `keyLengthMismatch`: a contributing table's subject key has a different number of columns than the identity table's. `keyTypeMismatch`: a contributing table's key column and the identity table's key column at the same position hold different kinds of data. `joinTypeMismatch`: the two columns of a join pair hold different kinds of data. `outsideMappingSource`: the bound table sits outside the ontology's mapping source. `multipleDatabases`: the ontology names no mapping source and its bound tables sit in more than one database. It is reported on each page that finds a database no earlier page found, once two are known. `sensitiveKeyColumn`: a subject key column of a table that has a role is tagged `PII.Sensitive`, or sits under a column that is, or its table is, so its sample data and profile are masked. `columnTypeMismatch`: a column bound to a DATA property whose range is one XSD datatype holds a kind of data that datatype does not fit, for example a text column for an integer property. Both are advice and refuse nothing.", "type": "string", "javaType": "org.openmetadata.schema.api.data.OntologyMappingHealthEntryType", "enum": [ @@ -25,7 +25,9 @@ "keyTypeMismatch", "joinTypeMismatch", "outsideMappingSource", - "multipleDatabases" + "multipleDatabases", + "sensitiveKeyColumn", + "columnTypeMismatch" ] }, "entry": { @@ -47,11 +49,11 @@ "$ref": "../../type/entityReference.json" }, "property": { - "description": "The property of the bound column on the relation column and join findings, when the caller may view it.", + "description": "The property of the bound column on the relation column, join and `columnTypeMismatch` findings, when the caller may view it.", "$ref": "../../type/entityReference.json" }, "columnPath": { - "description": "A column of `asset`: the bound column on `relationColumnWithoutJoin` and `joinNotConfirmed`, the key column on `keyTypeMismatch`, and the child column on `joinTypeMismatch`.", + "description": "A column of `asset`: the bound column on `relationColumnWithoutJoin`, `joinNotConfirmed` and `columnTypeMismatch`, the key column on `keyTypeMismatch` and `sensitiveKeyColumn`, and the child column on `joinTypeMismatch`.", "$ref": "#/definitions/columnPath" }, "relatedColumnPath": { @@ -59,13 +61,17 @@ "$ref": "#/definitions/columnPath" }, "dataType": { - "description": "Data type of `columnPath` on the type findings.", + "description": "Data type of `columnPath` on the type findings and on `columnTypeMismatch`.", "$ref": "../../entity/data/table.json#/definitions/dataType" }, "relatedDataType": { "description": "Data type of `relatedColumnPath` on the type findings.", "$ref": "../../entity/data/table.json#/definitions/dataType" }, + "propertyDatatype": { + "description": "The IRI of the XSD datatype that is the range of `property`, on `columnTypeMismatch`.", + "$ref": "../../type/ontologyIri.json" + }, "keyLength": { "description": "Number of subject key columns of `asset`, on `keyLengthMismatch`.", "type": "integer" From 17d992fcb3e4158e539266fff45a306b42146bbc Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 14:59:28 -0800 Subject: [PATCH 180/203] Mapping health reads each table once and tests the new findings over HTTP --- ...dependentOntologyMappingAdviceCountIT.java | 126 +++++++++ .../IndependentOntologyMappingAdviceIT.java | 241 ++++++++++++++++++ .../OntologyMappingHealthService.java | 66 +++-- 3 files changed, 407 insertions(+), 26 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java new file mode 100644 index 000000000000..5dc2f94621cc --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java @@ -0,0 +1,126 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.health; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.SqlQueryCounter; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.service.Entity; + +/** + * What the mapping health read costs, counted in the SQL statements one request runs. A page of + * one hundred bindings, each with a sensitive key and a column type finding, runs the same + * statements as a page of five, whether or not the identity table of the class is on the page. + */ +@Isolated("Counts SQL statements while serving the mapping health read over HTTP") +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyMappingAdviceCountIT extends BaseOntologyApprovalIT { + private static final int FULL_PAGE = 100; + private static final int SMALL_PAGE = 5; + + private static final int SELECTS_WITH_IDENTITY_ON_PAGE = 50; + private static final int SELECTS_WITH_IDENTITY_OFF_PAGE = 50; + + @Test + void aPageOfOneHundredBindingsRunsNoMoreStatementsThanAPageOfFive(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + bindTables(ns, ontology, customer, FULL_PAGE, false); + + final int small = selects(ontology, SMALL_PAGE); + final int full = selects(ontology, FULL_PAGE); + + assertEquals(SELECTS_WITH_IDENTITY_ON_PAGE, full); + assertEquals(small, full); + assertEquals( + 3 * FULL_PAGE, health(admin(), ontology, "?limit=" + FULL_PAGE).getEntries().size()); + } + + @Test + void aPageWhoseIdentityTableIsOnAnotherPageRunsTheSameStatementsAsAPageOfFive( + final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + bindTables(ns, ontology, customer, FULL_PAGE + 1, true); + + final int small = selects(ontology, SMALL_PAGE); + final int full = selects(ontology, FULL_PAGE); + + assertEquals(SELECTS_WITH_IDENTITY_OFF_PAGE, full); + assertEquals(small, full); + assertEquals( + 2 * FULL_PAGE, + health(admin(), ontology, "?limit=" + FULL_PAGE).getEntries().stream() + .filter(entry -> entry.getType().value().equals("sensitiveKeyColumn")) + .count()); + } + + /** + * Binds {@code count} tables to the class, each with a table tag and a text column bound to an + * integer property. The identity table is the first by table id, or the last when {@code + * identityLast}, and the rest contribute. + */ + private static void bindTables( + final TestNamespace ns, + final Ontology ontology, + final OntologyConcept concept, + final int count, + final boolean identityLast) { + final var age = IndependentOntologyMappingAdviceIT.integerProperty(ontology, concept, "age"); + final var schema = schema(ns); + final List

    tables = new ArrayList<>(); + for (int i = 0; i < count; i++) { + tables.add( + IndependentOntologyMappingAdviceIT.customers( + schema, "customers_" + i, IndependentOntologyMappingAdviceIT.tag("PII.Sensitive"))); + } + tables.sort(Comparator.comparing(table -> table.getId().toString())); + final Table identity = identityLast ? tables.getLast() : tables.getFirst(); + for (int i = 0; i < count; i++) { + final Table table = tables.get(i); + put( + admin(), + concept, + binding( + table, + table == identity + ? OntologyBindingRole.IDENTITY + : OntologyBindingRole.CONTRIBUTING, + "email", + "id") + .withColumns(List.of(column(age, "age"))), + i); + } + } + + /** Asks once to fill what the server caches between requests, then counts the next request. */ + private static int selects(final Ontology ontology, final int limit) { + health(admin(), ontology, "?limit=" + limit); + try (var queries = + SqlQueryCounter.forRequests( + Entity.getJdbi(), + "select", + statement -> statement.getRenderedSql().toLowerCase(Locale.ROOT).contains("select"))) { + health(admin(), ontology, "?limit=" + limit); + return queries.count(); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java new file mode 100644 index 000000000000..53d55a638e2c --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java @@ -0,0 +1,241 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.health; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.summary; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateTable; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.schema.type.TagLabel.TagSource; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; + +/** + * The mapping health read advises on a key column whose data is masked and on a column whose type + * cannot hold the datatype of its property, for the tables and properties the caller may view. + */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyMappingAdviceIT extends BaseOntologyApprovalIT { + private static final String INTEGER = "http://www.w3.org/2001/XMLSchema#integer"; + private static final String SENSITIVE = "PII.Sensitive"; + + @Test + void anEditorSeesTheSensitiveKeyAndTheColumnTypeThatCannotHoldItsProperty( + final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table customers = customers(schema(ns), "customers", tag(SENSITIVE)); + final var age = integerProperty(ontology, customer, "age"); + put( + admin(), + customer, + binding(customers, OntologyBindingRole.IDENTITY, "email") + .withColumns(List.of(column(age, "age"))), + 0L); + + final var entries = health(admin(), ontology, "").getEntries(); + + assertEquals( + List.of("sensitiveKeyColumn Customer customers", "columnTypeMismatch Customer customers"), + summary(entries)); + assertEquals( + "{\"type\":\"sensitiveKeyColumn\",\"concept\":\"Customer\",\"asset\":\"customers\"," + + "\"columnPath\":[\"email\"]}", + json(entries.get(0))); + assertEquals( + "{\"type\":\"columnTypeMismatch\",\"concept\":\"Customer\",\"asset\":\"customers\"," + + "\"property\":\"age\",\"columnPath\":[\"age\"],\"dataType\":\"VARCHAR\"," + + "\"propertyDatatype\":\"" + + INTEGER + + "\"}", + json(entries.get(1))); + } + + @Test + void aTableTagIsEnoughAndRemovingTheTagRemovesTheFinding(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table customers = customers(schema(ns), "customers", tag(SENSITIVE)); + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "email", "id"), 0L); + + assertEquals( + List.of("sensitiveKeyColumn Customer customers", "sensitiveKeyColumn Customer customers"), + summary(health(admin(), ontology, "").getEntries())); + + admin() + .tables() + .patch( + customers.getId(), + JsonUtils.getObjectMapper() + .createArrayNode() + .add(JsonUtils.valueToTree(Map.of("op", "remove", "path", "/tags/0")))); + + assertEquals(List.of(), summary(health(admin(), ontology, "").getEntries())); + } + + @Test + void aBindingWithATaggedKeyStillWritesAndTheFindingFollowsTheTag(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table customers = customers(schema(ns), "customers"); + + final var written = + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "email"), 0L); + + assertEquals(OntologyBindingRole.IDENTITY, written.getAssets().getFirst().getRole()); + assertEquals(List.of(List.of("email")), written.getAssets().getFirst().getSubjectKey()); + assertEquals(List.of(), summary(health(admin(), ontology, "").getEntries())); + + admin() + .tables() + .patch( + customers.getId(), + JsonUtils.getObjectMapper() + .createArrayNode() + .add( + JsonUtils.valueToTree( + Map.of( + "op", "add", "path", "/columns/0/tags/-", "value", tag(SENSITIVE))))); + final var rewritten = + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "email"), 1L); + + assertEquals(OntologyBindingRole.IDENTITY, rewritten.getAssets().getFirst().getRole()); + assertEquals( + List.of("sensitiveKeyColumn Customer customers"), + summary(health(admin(), ontology, "").getEntries())); + + admin() + .tables() + .patch( + customers.getId(), + JsonUtils.getObjectMapper() + .createArrayNode() + .add(JsonUtils.valueToTree(Map.of("op", "remove", "path", "/columns/0/tags/0")))); + + assertEquals(List.of(), summary(health(admin(), ontology, "").getEntries())); + } + + @Test + void aReaderDeniedTheTableSeesNeitherFinding(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var age = integerProperty(ontology, customer, "age"); + final DatabaseSchema schema = schema(ns); + try (var fixtures = new RdfAccessFixtures("adviceTable" + ns.shortPrefix())) { + final var reader = OntologyBindingFixtures.ownerReader(fixtures, Entity.TABLE); + final Table hidden = customers(schema, "customers", tag(SENSITIVE)); + put( + admin(), + customer, + binding(hidden, OntologyBindingRole.IDENTITY, "email") + .withColumns(List.of(column(age, "age"))), + 0L); + + assertEquals(List.of(), health(reader, ontology, "").getEntries()); + assertEquals( + List.of("sensitiveKeyColumn Customer customers", "columnTypeMismatch Customer customers"), + summary(health(admin(), ontology, "").getEntries())); + } + } + + @Test + void aReaderDeniedThePropertySeesTheSensitiveKeyAndNoColumnTypeFinding(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table customers = customers(schema(ns), "customers", tag(SENSITIVE)); + try (var fixtures = new RdfAccessFixtures("adviceProperty" + ns.shortPrefix())) { + final var reader = OntologyBindingFixtures.ownerReader(fixtures, Entity.ONTOLOGY_PROPERTY); + final var age = integerProperty(ontology, customer, "age"); + put( + admin(), + customer, + binding(customers, OntologyBindingRole.IDENTITY, "email") + .withColumns(List.of(column(age, "age"))), + 0L); + + final var seen = summary(health(reader, ontology, "").getEntries()); + + assertEquals(List.of("sensitiveKeyColumn Customer customers"), seen); + assertEquals( + List.of("sensitiveKeyColumn Customer customers", "columnTypeMismatch Customer customers"), + summary(health(admin(), ontology, "").getEntries())); + } + } + + /** A table with an {@code id}, an {@code email} and an {@code age} column, the last two text. */ + static Table customers( + final DatabaseSchema schema, final String name, final TagLabel... tableTags) { + return admin() + .tables() + .create( + new CreateTable() + .withName(name) + .withDatabaseSchema(schema.getFullyQualifiedName()) + .withTags(List.of(tableTags)) + .withColumns( + List.of( + column("email", ColumnDataType.VARCHAR), + column("id", ColumnDataType.BIGINT), + column("age", ColumnDataType.VARCHAR)))); + } + + static TagLabel tag(final String fqn) { + return new TagLabel() + .withTagFQN(fqn) + .withSource(TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL) + .withState(TagLabel.State.CONFIRMED); + } + + static OntologyProperty integerProperty( + final Ontology ontology, final OntologyConcept domain, final String name) { + return admin() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName(name) + .withOntology(ontology.getFullyQualifiedName()) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(domain.getIri())) + .withRange(List.of(URI.create(INTEGER)))); + } + + /** The entry with its class, table and property references reduced to their names. */ + private static String json(final OntologyMappingHealthEntry entry) { + final ObjectNode node = (ObjectNode) JsonUtils.valueToTree(entry); + for (final String field : List.of("concept", "asset", "property")) { + if (node.has(field)) { + node.put(field, node.get(field).get("name").asText()); + } + } + return node.toString(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java index 6e50eaa180cc..ba83f48c2d91 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java @@ -10,6 +10,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.Function; +import java.util.stream.Stream; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.api.data.OntologyMappingHealth; import org.openmetadata.schema.entity.data.Ontology; @@ -63,10 +64,11 @@ public OntologyMappingHealth page( final List scanned = store.tableRows(ontology.getId(), cursor.position(), limit + 1); final List rows = scanned.subList(0, Math.min(limit, scanned.size())); - final List tables = boundTables(access, rows); + final Loaded loaded = load(access, rows); + final List tables = boundTables(access, rows, loaded); final var page = OntologyMappingHealthRules.check( - tables, context(access, ontology, tables), progress(access, cursor)); + tables, context(access, ontology, tables, loaded), progress(access, cursor)); return new OntologyMappingHealth() .withMappingSource(ontology.getMappingSource()) .withEntries(page.entries()) @@ -75,8 +77,9 @@ public OntologyMappingHealth page( } /** The rows whose table and class are both live and viewable. Every other row says nothing. */ - private List boundTables(final Access access, final List rows) { - final Map tables = viewableTables(access, rows, Set.of(Entity.FIELD_TAGS)); + private List boundTables( + final Access access, final List rows, final Loaded loaded) { + final Map tables = loaded.tables(); final var concepts = targets.viewable( access, @@ -97,12 +100,15 @@ private List boundTables(final Access access, final List } private Context context( - final Access access, final Ontology ontology, final List tables) { + final Access access, + final Ontology ontology, + final List tables, + final Loaded loaded) { final List columns = tables.stream().flatMap(bound -> listOrEmpty(bound.row().columns()).stream()).toList(); return new Context( ontology.getMappingSource(), - identities(access, tables), + identities(loaded), typed( targets.viewable( access, @@ -121,37 +127,45 @@ private Context context( Table.class)); } + /** + * The binding rows of a page and of the identity tables of their classes, with the live and + * viewable tables they name, read in one pass. {@code tables} carries tags and columns, which + * the sensitive key check reads, so no table is read again for its identity role. + */ + private record Loaded(List identityRows, Set live, Map tables) {} + + private Loaded load(final Access access, final List rows) { + final List identityRows = + store.identityRows(rows.stream().map(BindingRow::conceptId).toList()); + final List every = Stream.concat(rows.stream(), identityRows.stream()).toList(); + final Set live = store.liveAssets(every).keySet(); + return new Loaded( + identityRows, + live, + typed( + targets.viewable( + access, + Entity.TABLE, + every.stream().map(BindingRow::assetId).filter(live::contains).toList(), + Set.of(Entity.FIELD_TAGS)), + Table.class)); + } + /** * A class has an identity table when a live one is stored, whether or not the caller may view * it, so a hidden identity table never reads as a missing one. */ - private Map identities(final Access access, final List tables) { - final List rows = - store.identityRows(tables.stream().map(bound -> bound.row().conceptId()).toList()); - final Set live = store.liveAssets(rows).keySet(); - final Map viewable = viewableTables(access, rows, Set.of()); + private static Map identities(final Loaded loaded) { final Map identities = new HashMap<>(); - rows.stream() - .filter(row -> live.contains(row.assetId())) + loaded.identityRows().stream() + .filter(row -> loaded.live().contains(row.assetId())) .forEach( row -> identities.putIfAbsent( - row.conceptId(), new Identity(row, viewable.get(row.assetId())))); + row.conceptId(), new Identity(row, loaded.tables().get(row.assetId())))); return identities; } - private Map viewableTables( - final Access access, final List rows, final Set extra) { - final Set live = store.liveAssets(rows).keySet(); - return typed( - targets.viewable( - access, - Entity.TABLE, - rows.stream().map(BindingRow::assetId).filter(live::contains).toList(), - extra), - Table.class); - } - /** * The cursor names one table for each database found so far. Each is read again under the * caller's policies, so a cursor can only name what its holder may already view. From cba99b7dda4bca49b4d18d7225d60dedf1276c56 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 15:06:39 -0800 Subject: [PATCH 181/203] Read the table mapping of a whole ontology version as one value --- ...-table-mapping-of-a-version-is-one-read.md | 76 ++ .../jdbi3/OntologyConceptBindingStore.java | 21 + .../ontology/OntologyMappingReader.java | 25 +- .../ontology/OntologyTableMapping.java | 156 ++++ .../ontology/OntologyTableMappingRules.java | 285 +++++++ .../ontology/OntologyTableMappings.java | 201 +++++ .../service/ontology/OntologyVersion.java | 97 +++ .../OntologyTableMappingRulesTest.java | 738 ++++++++++++++++++ 8 files changed, 1595 insertions(+), 4 deletions(-) create mode 100644 docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMapping.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java diff --git a/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md b/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md new file mode 100644 index 000000000000..14702e82db73 --- /dev/null +++ b/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md @@ -0,0 +1,76 @@ +# The table mapping of a whole ontology version is one read that counts what the caller may not view + +- **Status:** Accepted +- **Revisions:** v1 2026-12-04 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyTableMappingRulesTest`, `OntologyTableMappingsIT` +- **Related:** ADR:2026-11-22-record-statements-start-from-the-identity-table (the identity table and the join a relation follows), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter) + +## Context + +A statement about the records of one class reads that class's bindings. Code in the server that +needs to reason about a whole version of an ontology, such as which table identifies each class and +which column joins which tables, had no way to ask for it. It could repeat the per-class reads for +every class, which costs queries in proportion to the classes and lets a binding change between two +of them, so it would see a mapping that never existed. It could also read the stored rows directly, +which skips the caller's rights. + +A value that omits what the caller may not view looks the same as a value for a version that has +nothing more to show. A caller that acts on the whole mapping, for example by deciding that two +classes are unrelated, would act on a gap it cannot see. + +## Decision + +**The mapping of a version is one read.** `OntologyTableMappings.read(access, ontologyId, version)` +returns an `OntologyTableMapping`: every class of the version that binds an existing table, each +with its tables, subject keys, row filters, data columns and relation columns. A `null` version +means the active release. A release with no active release is a 404 that says so. The draft goes +through the same gate as the statements, a 403 without the right to read the working draft. + +**One call reads the binding rows between two equal reads of the binding revisions** of all the +classes at once, as a statement does, and returns a 409 after the same three attempts. A change that +lands between the reads is either seen whole or refused, never half seen. + +**The number of queries does not depend on the number of classes or bindings.** One query reads +each kind, in chunks of ids when a list is longer than one IN list: the ontology and its state, the +ids of the classes, the revisions twice, the binding rows, the tables, the classes, the properties, +and the class hierarchy when a relation declares a range. + +**A part the caller may not view is counted and never named.** The answer carries `hiddenTables`, +`hiddenClasses` and `hiddenProperties`. A hidden part appears in no field and no id, name, column +path or IRI of it appears in the value, its text or its JSON. The read never fails for a hidden +part, so the caller decides what a non-zero count means for it. A caller that needs the whole +mapping refuses a value with a non-zero count. + +- `hiddenTables` counts the distinct existing tables that the classes of the version bind, and the + tables that a listed relation column joins, that the caller may not view. +- `hiddenClasses` counts the classes of the version that bind an existing table and that the caller + may not view. +- `hiddenProperties` counts the properties of the version that a column of a listed binding binds + and that the caller may not view. + +**What is left out silently.** A deleted table is left out and counted nowhere, as the list of the +bindings of a class leaves it out. A class with no existing bound table is left out. A column whose +property the version does not declare is listed by its path as absent from the version. A column +that the table no longer has is listed by its path apart. A row filter that no longer applies is +given as a reason, a sentence that names the table and the column and never a value. + +**A relation column lists the classes that identify its target.** They are the classes the caller +may view whose identity table is the join's target table. When the relation declares a range, only +those that are in the range or are subclasses of a class in it, as that version declares them. + +**This is a Java API and has no endpoint.** The first caller is code in the same server that +already holds the caller's identity, and it needs a value to reason over, not a page to render. An +endpoint would add a response schema, a page size and a cursor over a read that must be consistent +as a whole, and none of them has a user yet. + +## Consequences + +A caller gets a mapping it can trust to be complete when the three counts are zero, and it can tell +when it is not. The cost of a read grows with the size of the data it returns, not with the number +of classes it asks about. A binding write that races a read makes the read retry or fail with a 409 +and never return a mix. + +The value holds the columns of each viewable table as the catalog holds them, so a mapping of a +large version is large. A caller that needs one class reads it with the statements. If a client +outside the server ever needs the whole mapping, an endpoint can wrap `read` without changing it. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index fc4d7fa48c0b..6adac027986b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -230,6 +230,27 @@ public List shapesNamingClass( .toList(); } + /** The live properties with these ids, in one statement. */ + public List liveProperties(final Collection ids) { + return ids.isEmpty() + ? List.of() + : dao.ontologyPropertyDAO().findEntitiesByIds(List.copyOf(ids), Include.NON_DELETED); + } + + /** + * Every table row of these concepts, whether or not the table exists, in one statement for each + * chunk of ids. A concept's rows are never cut short. + */ + public List allTableRows(final Collection conceptIds) { + return conceptIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + conceptIds.stream().map(UUID::toString).distinct().toList(), + chunk -> + dao.ontologyConceptBindingDAO() + .listFirstTablesForConcepts(chunk, Integer.MAX_VALUE)); + } + /** The live classes with these ids, in one statement. */ public List liveConcepts(final Collection ids) { return ids.isEmpty() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java index 70d78d904497..d1d6221f071b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java @@ -120,15 +120,32 @@ record IdentityTable(BindingRow row) implements SearchStart {} * @param withContributing the classes whose contributing table rows the statement reads */ Bindings bindings(final Collection classes, final Collection withContributing) { + return between( + classes, + "The table bindings changed while the statement was built. Ask again", + revisions -> + new Bindings(revisions, identityRows(classes), contributingRows(withContributing))); + } + + /** + * Runs {@code read} between two reads of the binding revisions of {@code classes} and returns + * its result when the two reads agree. After {@value #BINDING_READ_ATTEMPTS} attempts that never + * agree, it is a 409 with {@code refusal}. + * + * @param read takes the first revision read + */ + T between( + final Collection classes, + final String refusal, + final Function, T> read) { for (int attempt = 0; attempt < BINDING_READ_ATTEMPTS; attempt++) { final Map revisions = store.revisions(classes); - final Bindings read = - new Bindings(revisions, identityRows(classes), contributingRows(withContributing)); + final T result = read.apply(revisions); if (revisions.equals(store.revisions(classes))) { - return read; + return result; } } - throw conflict("The table bindings changed while the statement was built. Ask again"); + throw conflict(refusal); } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMapping.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMapping.java new file mode 100644 index 000000000000..dc827ca96afa --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMapping.java @@ -0,0 +1,156 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.service.ontology.sql.TypedRowFilter; + +/** + * The table mapping of one version of an ontology, as one caller may see it: every class of the + * version that binds an existing table, with the tables, keys, row filters, data columns and + * relation joins of its bindings. + * + *

    Parts the caller may not view are left out and counted. A caller that needs the whole mapping + * checks the three counts, and a mapping with any count above zero is not the whole mapping. No + * field names, identifies or points at a part that is hidden from the caller. + * + * @param version the version that was read + * @param classes the classes the caller may view, by IRI + * @param hiddenTables the number of distinct existing tables that the classes of the version bind, + * or that a relation column of a listed binding joins, and that the caller may not view + * @param hiddenClasses the number of classes of the version that bind an existing table and that + * the caller may not view + * @param hiddenProperties the number of properties of the version that a column of a listed + * binding binds and that the caller may not view + */ +public record OntologyTableMapping( + OntologyStatementVersionRead version, + List classes, + int hiddenTables, + int hiddenClasses, + int hiddenProperties) { + + /** + * One class and the tables it binds that the caller may view. + * + * @param iri the IRI of the class in the version + * @param id the id of the class + * @param tables identity table first, then contributing tables by name, then tables with no role + * by name. Empty when the caller may view none of the tables the class binds. + */ + public record ClassMapping(URI iri, UUID id, List tables) {} + + /** + * One table of a class, with how the class reads it. + * + * @param table the table + * @param role the role of the binding, or null for a binding with no role + * @param subjectKey the column paths that identify one record, in key order. Empty when the + * binding names none. + * @param rowFilter the row filter of the binding, or null when it has none + * @param dataColumns the columns bound to data properties, in binding order + * @param relationColumns the columns bound to relations, in binding order + * @param absentFromVersion the paths of the columns whose property the version does not declare, + * in binding order + * @param missingColumns the paths of the binding's columns that the table no longer has, in + * binding order + */ + public record TableBinding( + TableRef table, + OntologyBindingRole role, + List> subjectKey, + RowFilterState rowFilter, + List dataColumns, + List relationColumns, + List> absentFromVersion, + List> missingColumns) {} + + /** + * A table the caller may view. + * + * @param id the id of the table + * @param fullyQualifiedName the fully qualified name of the table + * @param serviceType the value of the service type of the table, or null when it has none + * @param columns the columns of the table as the catalog holds them + */ + public record TableRef( + UUID id, String fullyQualifiedName, String serviceType, List columns) {} + + /** What a stored row filter is now: a filter that applies, or the reason it does not. */ + public sealed interface RowFilterState {} + + /** + * A row filter whose column exists and whose values parse as the data type of that column. + * + * @param filter the parsed filter + */ + public record Applies(TypedRowFilter filter) implements RowFilterState {} + + /** + * A row filter that no longer applies. + * + * @param reason one sentence in the style of a 409 that says why. It holds no value of the + * filter. + */ + public record Broken(String reason) implements RowFilterState {} + + /** + * A column that holds the values of a data property. + * + * @param propertyIri the IRI of the property + * @param columnPath the path of the column + */ + public record DataColumn(URI propertyIri, List columnPath) {} + + /** + * A column bound to a relation. + * + * @param relationIri the IRI of the relation + * @param columnPath the path of the column + * @param join where the column leads, or null when the binding stores no join. Columns bound + * before joins existed store none. + */ + public record RelationColumn(URI relationIri, List columnPath, Join join) {} + + /** + * The join of a relation column onto the table that holds the related records. A join onto a + * table the caller may not view, or onto a table that no longer exists, is not listed. + * + * @param status whether a person confirmed the join + * @param targetTableId the id of the target table, which the caller may view + * @param on the pairs of the join, in stored order + * @param objectClasses the IRIs of the classes the caller may view whose identity table is the + * target table, by IRI. When the relation declares a range, only the classes that are in the + * range or are subclasses of a class in it, in that version. Empty when no class qualifies. + */ + public record Join( + OntologyJoinStatus status, + UUID targetTableId, + List on, + List objectClasses) {} + + /** + * One equality of a join. + * + * @param child the path of a column of the table that holds the relation column + * @param parent the path of a column of the target table + */ + public record ColumnPair(List child, List parent) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java new file mode 100644 index 000000000000..e871ab71d7cb --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java @@ -0,0 +1,285 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyTableMapping.Applies; +import org.openmetadata.service.ontology.OntologyTableMapping.Broken; +import org.openmetadata.service.ontology.OntologyTableMapping.ClassMapping; +import org.openmetadata.service.ontology.OntologyTableMapping.ColumnPair; +import org.openmetadata.service.ontology.OntologyTableMapping.DataColumn; +import org.openmetadata.service.ontology.OntologyTableMapping.Join; +import org.openmetadata.service.ontology.OntologyTableMapping.RelationColumn; +import org.openmetadata.service.ontology.OntologyTableMapping.RowFilterState; +import org.openmetadata.service.ontology.OntologyTableMapping.TableBinding; +import org.openmetadata.service.ontology.OntologyTableMapping.TableRef; +import org.openmetadata.service.ontology.sql.TypedValues; + +/** + * Turns what one read found into the table mapping a caller may see. Nothing here reads a database + * or a policy. The caller passes what exists and which of it the reader may view, and this decides + * what is listed and what is counted. + */ +final class OntologyTableMappingRules { + private static final String FILTER_COLUMN_GONE = + "The row filter of table %s names a column that the table no longer has"; + private static final String FILTER_VALUE_UNPARSED = + "A value of the row filter of table %s no longer parses as the data type of column %s"; + + private OntologyTableMappingRules() {} + + /** + * What one read found. + * + * @param rows the table rows of the classes, whether or not their tables exist + * @param tables every existing table that a row binds or a column joins, by id + * @param viewableTables the ids among {@code tables} that the reader may view + * @param classes the classes that the version declares, by id + * @param viewableClasses the ids among {@code classes} that the reader may view + * @param properties the properties that the version declares, by id + * @param viewableProperties the ids among {@code properties} that the reader may view + * @param parents the named parents of each class by IRI, as far up as the version declares them + */ + record Facts( + OntologyStatementVersionRead version, + List rows, + Map tables, + Set viewableTables, + Map classes, + Set viewableClasses, + Map properties, + Set viewableProperties, + Map> parents) {} + + /** What a build leaves out, collected as it goes. */ + private static final class Hidden { + private final Set tables = new HashSet<>(); + private final Set properties = new HashSet<>(); + } + + static OntologyTableMapping build(final Facts facts) { + final List bound = + facts.rows().stream() + .filter(row -> facts.tables().containsKey(row.assetId())) + .filter(row -> facts.classes().containsKey(row.conceptId())) + .toList(); + final Map> byClass = + bound.stream().collect(Collectors.groupingBy(BindingRow::conceptId)); + final Hidden hidden = new Hidden(); + bound.stream() + .map(BindingRow::assetId) + .filter(id -> !facts.viewableTables().contains(id)) + .forEach(hidden.tables::add); + final Map> identityClasses = identityClasses(facts, bound); + final List classes = + byClass.entrySet().stream() + .filter(entry -> facts.viewableClasses().contains(entry.getKey())) + .map(entry -> mapped(facts, entry, identityClasses, hidden)) + .sorted(Comparator.comparing(mapping -> mapping.iri().toString())) + .toList(); + final int hiddenClasses = + (int) byClass.keySet().stream().filter(id -> !facts.viewableClasses().contains(id)).count(); + return new OntologyTableMapping( + facts.version(), classes, hidden.tables.size(), hiddenClasses, hidden.properties.size()); + } + + /** The viewable classes whose identity table is each table, in IRI order. */ + private static Map> identityClasses( + final Facts facts, final List bound) { + return bound.stream() + .filter(row -> row.role() == OntologyBindingRole.IDENTITY) + .filter(row -> facts.viewableClasses().contains(row.conceptId())) + .collect( + Collectors.groupingBy( + BindingRow::assetId, + Collectors.mapping( + row -> facts.classes().get(row.conceptId()).getIri(), + Collectors.collectingAndThen( + Collectors.toList(), + iris -> + iris.stream().sorted(Comparator.comparing(URI::toString)).toList())))); + } + + private static ClassMapping mapped( + final Facts facts, + final Map.Entry> entry, + final Map> identityClasses, + final Hidden hidden) { + final OntologyConcept type = facts.classes().get(entry.getKey()); + final List tables = + entry.getValue().stream() + .filter(row -> facts.viewableTables().contains(row.assetId())) + .sorted(byRoleThenName(facts)) + .map(row -> binding(facts, row, identityClasses, hidden)) + .toList(); + return new ClassMapping(type.getIri(), type.getId(), tables); + } + + private static Comparator byRoleThenName(final Facts facts) { + return Comparator.comparingInt((BindingRow row) -> rank(row.role())) + .thenComparing(row -> facts.tables().get(row.assetId()).getFullyQualifiedName()); + } + + private static int rank(final OntologyBindingRole role) { + if (role == OntologyBindingRole.IDENTITY) { + return 0; + } + return role == OntologyBindingRole.CONTRIBUTING ? 1 : 2; + } + + private static TableBinding binding( + final Facts facts, + final BindingRow row, + final Map> identityClasses, + final Hidden hidden) { + final Table table = facts.tables().get(row.assetId()); + final List data = new ArrayList<>(); + final List relations = new ArrayList<>(); + final List> absent = new ArrayList<>(); + final List> missing = new ArrayList<>(); + for (final OntologyColumnBinding column : listOrEmpty(row.columns())) { + final OntologyProperty property = facts.properties().get(column.getPropertyId()); + if (property != null && !facts.viewableProperties().contains(property.getId())) { + hidden.properties.add(property.getId()); + } + if (OntologyBindingRules.resolveColumn(table, column.getColumnPath()) == null) { + missing.add(column.getColumnPath()); + } else if (property == null) { + absent.add(column.getColumnPath()); + } else if (facts.viewableProperties().contains(property.getId())) { + listed(facts, column, property, identityClasses, hidden, data, relations); + } + } + return new TableBinding( + new TableRef( + table.getId(), + table.getFullyQualifiedName(), + table.getServiceType() == null ? null : table.getServiceType().value(), + listOrEmpty(table.getColumns())), + row.role(), + listOrEmpty(row.subjectKey()), + filterState(table, row.rowFilter()), + List.copyOf(data), + List.copyOf(relations), + List.copyOf(absent), + List.copyOf(missing)); + } + + private static void listed( + final Facts facts, + final OntologyColumnBinding column, + final OntologyProperty property, + final Map> identityClasses, + final Hidden hidden, + final List data, + final List relations) { + if (property.getKind() == OntologyPropertyKind.DATA) { + data.add(new DataColumn(property.getIri(), column.getColumnPath())); + } else if (property.getKind() == OntologyPropertyKind.OBJECT) { + relation(facts, column, property, identityClasses, hidden).ifPresent(relations::add); + } + } + + private static Optional relation( + final Facts facts, + final OntologyColumnBinding column, + final OntologyProperty property, + final Map> identityClasses, + final Hidden hidden) { + final OntologyColumnJoin join = column.getJoin(); + if (join == null) { + return Optional.of(new RelationColumn(property.getIri(), column.getColumnPath(), null)); + } + final UUID target = join.getTargetAssetId(); + if (!facts.tables().containsKey(target)) { + return Optional.empty(); + } + if (!facts.viewableTables().contains(target)) { + hidden.tables.add(target); + return Optional.empty(); + } + final List objects = + identityClasses.getOrDefault(target, List.of()).stream() + .filter(iri -> inRange(facts, property, iri)) + .toList(); + return Optional.of( + new RelationColumn( + property.getIri(), + column.getColumnPath(), + new Join( + join.getStatus(), + target, + join.getOn().stream() + .map(pair -> new ColumnPair(pair.getChild(), pair.getParent())) + .toList(), + objects))); + } + + /** A class is in the range of a relation when it is named there or sits below a named class. */ + private static boolean inRange( + final Facts facts, final OntologyProperty relation, final URI iri) { + final List range = listOrEmpty(relation.getRange()); + if (range.isEmpty()) { + return true; + } + final Set above = + OntologyClassHierarchy.reachable(facts.parents(), Set.of(iri.toString())); + return range.stream().map(URI::toString).anyMatch(above::contains); + } + + /** + * The filter as a statement would parse it now, or why it no longer applies. The reason names + * the table and the column and never a value. + */ + static RowFilterState filterState(final Table table, final OntologyRowFilter filter) { + if (filter == null) { + return null; + } + final var column = OntologyBindingRules.resolveColumn(table, filter.getColumn()); + if (column == null) { + return new Broken(String.format(FILTER_COLUMN_GONE, table.getFullyQualifiedName())); + } + try { + return new Applies(TypedValues.rowFilter(column, filter)); + } catch (final BadRequestException unparsed) { + return new Broken( + String.format( + FILTER_VALUE_UNPARSED, + table.getFullyQualifiedName(), + String.join(".", filter.getColumn()))); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java new file mode 100644 index 000000000000..8abebf6167b7 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java @@ -0,0 +1,201 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyBindingAccess.TableViews; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyStatementService.DraftGate; +import org.openmetadata.service.ontology.OntologyTableMappingRules.Facts; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.util.FreshReadScope; + +/** + * Reads the table mapping of a whole version of an ontology as one value, for code in this server + * (ADR:2026-12-04-the-table-mapping-of-a-version-is-one-read). There is no endpoint. A caller that + * needs the whole mapping checks the three counts of the answer: a part the caller may not view is + * counted, never named, and never makes the read fail. + * + *

    A call makes a fixed number of batched reads whatever the version holds: the ontology, its + * state and release, the ids of the classes, the binding revisions twice around the binding rows, + * the tables, the classes, the properties and, when a relation declares a range, the class + * hierarchy. A list of ids longer than one IN list is read in chunks. + */ +@Slf4j +public final class OntologyTableMappings { + private static final String CHANGED = + "The table bindings changed while the mapping was read. Ask again"; + + private final OntologyConceptBindingStore store; + private final CollectionDAO dao; + private final OntologyBindingAccess catalog; + private final OntologyMappingReader mapping; + private final DraftGate draftGate; + + public OntologyTableMappings( + final OntologyConceptBindingStore store, + final CollectionDAO dao, + final Authorizer authorizer, + final Function> repositories, + final DraftGate draftGate) { + this.store = store; + this.dao = dao; + this.catalog = new OntologyBindingAccess(authorizer, repositories); + this.mapping = new OntologyMappingReader(store, catalog); + this.draftGate = draftGate; + } + + /** + * The table mapping of {@code version} of an ontology as {@code access} may see it. + * + * @param version the version to read. Null means the active release, which a 404 refuses when + * the ontology has none. The draft needs the right to read the working draft, and a 403 + * refuses a caller without it. + * @throws jakarta.ws.rs.ClientErrorException with 409 when the bindings keep changing while they + * are read + */ + public OntologyTableMapping read( + final Access access, final UUID ontologyId, final OntologyStatementVersion version) { + try (final var ignored = FreshReadScope.enter()) { + final EntityReference ontology = ontology(access, ontologyId); + final OntologyVersion read = + version == OntologyStatementVersion.DRAFT + ? draft(access, ontology) + : OntologyVersion.release(dao, ontology); + final OntologyTableMapping mapped = mapped(access, ontologyId, read); + LOG.debug( + "Read the table mapping of ontology {}: {} classes, {} hidden tables, {} hidden classes," + + " {} hidden properties", + ontologyId, + mapped.classes().size(), + mapped.hiddenTables(), + mapped.hiddenClasses(), + mapped.hiddenProperties()); + return mapped; + } + } + + private EntityReference ontology(final Access access, final UUID ontologyId) { + return ((Ontology) + catalog.authorized(access, Entity.ONTOLOGY, ontologyId, MetadataOperation.VIEW_BASIC)) + .getEntityReference(); + } + + private OntologyVersion draft(final Access access, final EntityReference ontology) { + draftGate.require(access.securityContext(), ontology.getId()); + return OntologyVersion.draft(dao, ontology); + } + + private OntologyTableMapping mapped( + final Access access, final UUID ontologyId, final OntologyVersion version) { + final Set candidates = version.boundClassIds(store, ontologyId); + final List rows = + mapping.between(candidates, CHANGED, revisions -> store.allTableRows(candidates)); + final TableViews tables = catalog.tableViews(access, tableIds(rows)); + final Set bound = + rows.stream() + .filter(row -> tables.live().containsKey(row.assetId())) + .map(BindingRow::conceptId) + .collect(Collectors.toSet()); + final Map classes = + byId(version.classes(store, ontologyId, bound), OntologyConcept::getId); + final Map properties = + byId( + version.properties(store, ontologyId, propertyIds(rows, tables)), + OntologyProperty::getId); + return OntologyTableMappingRules.build( + new Facts( + version.read(), + rows, + tables.live(), + tables.viewable(), + classes, + version.viewable( + catalog, access, Entity.ONTOLOGY_CONCEPT, List.copyOf(classes.values())), + properties, + version.viewable( + catalog, access, Entity.ONTOLOGY_PROPERTY, List.copyOf(properties.values())), + parents(version, ontologyId, classes, properties))); + } + + /** The tables that the rows bind and that their columns join. */ + private static Set tableIds(final List rows) { + final Set ids = new HashSet<>(); + for (final BindingRow row : rows) { + ids.add(row.assetId()); + listOrEmpty(row.columns()).stream() + .filter(column -> column.getJoin() != null) + .forEach(column -> ids.add(column.getJoin().getTargetAssetId())); + } + return ids; + } + + private static Set propertyIds(final List rows, final TableViews tables) { + return rows.stream() + .filter(row -> tables.live().containsKey(row.assetId())) + .flatMap(row -> listOrEmpty(row.columns()).stream()) + .map(OntologyColumnBinding::getPropertyId) + .collect(Collectors.toSet()); + } + + /** The class hierarchy, read only when a relation of the mapping declares a range. */ + private Map> parents( + final OntologyVersion version, + final UUID ontologyId, + final Map classes, + final Map properties) { + final boolean ranged = + properties.values().stream() + .anyMatch( + property -> + property.getKind() == OntologyPropertyKind.OBJECT + && !listOrEmpty(property.getRange()).isEmpty()); + if (!ranged) { + return Map.of(); + } + return version.namedParents( + store, + ontologyId, + classes.values().stream().map(type -> type.getIri().toString()).toList()); + } + + private static Map byId( + final List definitions, final Function id) { + return definitions.stream() + .collect(Collectors.toMap(id, Function.identity(), (first, second) -> first)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java index 9861f1fe6932..f4e4984671ce 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -42,6 +42,7 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.jdbi3.EntityDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.ConceptAssetCount; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; @@ -131,6 +132,27 @@ Set withSubclassAmong( UUID ontologyId, Map> candidatesByIri); + /** + * The ids of the classes of this version that may bind tables: for a release, every class it + * holds, and for the working draft, the live classes that bind any asset. + */ + Set boundClassIds(OntologyConceptBindingStore store, UUID ontologyId); + + /** The classes among {@code ids} that this version declares, as it declares them. */ + List classes( + OntologyConceptBindingStore store, UUID ontologyId, Collection ids); + + /** The properties among {@code ids} that this version declares, as it declares them. */ + List properties( + OntologyConceptBindingStore store, UUID ontologyId, Collection ids); + + /** + * The named parents, by IRI, of the classes that a walk up from {@code iris} reaches in this + * version. + */ + Map> namedParents( + OntologyConceptBindingStore store, UUID ontologyId, Collection iris); + /** The active release of {@code ontology}, or a 404 that says it has none. */ static OntologyVersion release(final CollectionDAO dao, final EntityReference ontology) { final OntologyState state = dao.ontologyStateDAO().get(ontology.getId()); @@ -221,6 +243,41 @@ public List classesNamed( return store.liveConcepts(ontologyId, iris); } + @Override + public Set boundClassIds(final OntologyConceptBindingStore store, final UUID ontologyId) { + return store.boundConcepts(ontologyId, Integer.MAX_VALUE, 0).stream() + .map(ConceptAssetCount::conceptId) + .collect(Collectors.toSet()); + } + + @Override + public List classes( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection ids) { + return store.liveConcepts(ids).stream() + .filter(concept -> ontologyId.equals(concept.getOntology().getId())) + .toList(); + } + + @Override + public List properties( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection ids) { + return store.liveProperties(ids).stream() + .filter(property -> ontologyId.equals(property.getOntology().getId())) + .toList(); + } + + @Override + public Map> namedParents( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return store.namedParentsAbove(ontologyId, iris); + } + @Override public Set withSubclassAmong( final OntologyConceptBindingStore store, @@ -327,6 +384,46 @@ public List classesNamed( concept -> iris.contains(concept.getIri())); } + @Override + public Set boundClassIds(final OntologyConceptBindingStore store, final UUID ontologyId) { + return dao + .ontologyReleaseDAO() + .listAllMemberVersions(List.of(release.getId().toString())) + .stream() + .filter(member -> MemberKind.CONCEPT.value().equals(member.memberKind())) + .map(member -> UUID.fromString(member.memberId())) + .collect(Collectors.toSet()); + } + + @Override + public List classes( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection ids) { + return released(MemberKind.CONCEPT, List.copyOf(ids), OntologyConcept.class, concept -> true); + } + + @Override + public List properties( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection ids) { + return released( + MemberKind.PROPERTY, List.copyOf(ids), OntologyProperty.class, property -> true); + } + + @Override + public Map> namedParents( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return OntologyClassHierarchy.namedEdges( + new OntologyReleaseReader(dao) + .read(release, unchecked -> {}).stream() + .map(member -> OntologyReleaseReader.definition(release, member)) + .toList()); + } + /** * The subclass steps come from the axioms of the release, so the answer is the released one * whatever the draft changed since. The release is read whole, through the cache that every diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java new file mode 100644 index 000000000000..23ba39c67e51 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java @@ -0,0 +1,738 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyTableMapping.Applies; +import org.openmetadata.service.ontology.OntologyTableMapping.Broken; +import org.openmetadata.service.ontology.OntologyTableMapping.ClassMapping; +import org.openmetadata.service.ontology.OntologyTableMapping.TableBinding; +import org.openmetadata.service.ontology.OntologyTableMappingRules.Facts; + +class OntologyTableMappingRulesTest { + private static final String NS = "https://example.org/"; + private static final OntologyStatementVersionRead VERSION = + new OntologyStatementVersionRead().withKind(OntologyStatementVersion.DRAFT); + + /** A small world that each test fills in and reads through {@link #build}. */ + private static final class World { + private long next = 1; + private final List rows = new ArrayList<>(); + private final Map tables = new HashMap<>(); + private final Set viewableTables = new HashSet<>(); + private final Map classes = new HashMap<>(); + private final Set viewableClasses = new HashSet<>(); + private final Map properties = new HashMap<>(); + private final Set viewableProperties = new HashSet<>(); + private final Map> parents = new HashMap<>(); + + UUID id() { + return new UUID(0, next++); + } + + OntologyConcept type(final String name) { + final OntologyConcept type = + new OntologyConcept().withId(id()).withName(name).withIri(URI.create(NS + name)); + classes.put(type.getId(), type); + viewableClasses.add(type.getId()); + return type; + } + + OntologyConcept hiddenType(final String name) { + final OntologyConcept type = type(name); + viewableClasses.remove(type.getId()); + return type; + } + + Table table(final String name, final String... columns) { + final List list = new ArrayList<>(); + for (final String column : columns) { + list.add(new Column().withName(column).withDataType(ColumnDataType.INT)); + } + final Table table = + new Table() + .withId(id()) + .withName(name) + .withFullyQualifiedName("svc.db.public." + name) + .withColumns(list); + tables.put(table.getId(), table); + viewableTables.add(table.getId()); + return table; + } + + Table hiddenTable(final String name, final String... columns) { + final Table table = table(name, columns); + viewableTables.remove(table.getId()); + return table; + } + + OntologyProperty data(final String name) { + return property(name, OntologyPropertyKind.DATA, List.of()); + } + + OntologyProperty relation(final String name, final String... range) { + return property( + name, + OntologyPropertyKind.OBJECT, + List.of(range).stream().map(iri -> URI.create(NS + iri)).toList()); + } + + private OntologyProperty property( + final String name, final OntologyPropertyKind kind, final List range) { + final OntologyProperty property = + new OntologyProperty() + .withId(id()) + .withName(name) + .withIri(URI.create(NS + name)) + .withKind(kind) + .withRange(range); + properties.put(property.getId(), property); + viewableProperties.add(property.getId()); + return property; + } + + OntologyProperty hiddenProperty(final String name) { + final OntologyProperty property = data(name); + viewableProperties.remove(property.getId()); + return property; + } + + void bind( + final OntologyConcept type, + final Table table, + final OntologyBindingRole role, + final String key, + final OntologyColumnBinding... columns) { + bind(type, table, role, key, null, columns); + } + + void bind( + final OntologyConcept type, + final Table table, + final OntologyBindingRole role, + final String key, + final OntologyRowFilter filter, + final OntologyColumnBinding... columns) { + rows.add( + new BindingRow( + type.getId(), + table.getId(), + OntologyBindingAssetType.TABLE, + "hash", + List.of(columns), + role, + key == null ? null : List.of(List.of(key)), + filter)); + } + + OntologyTableMapping build() { + return OntologyTableMappingRules.build( + new Facts( + VERSION, + rows, + tables, + viewableTables, + classes, + viewableClasses, + properties, + viewableProperties, + parents)); + } + } + + private static OntologyColumnBinding column(final OntologyProperty property, final String path) { + return new OntologyColumnBinding() + .withPropertyId(property.getId()) + .withColumnPath(List.of(path)); + } + + private static OntologyColumnBinding link( + final OntologyProperty relation, + final String path, + final Table target, + final OntologyJoinStatus status) { + return column(relation, path) + .withJoin( + new OntologyColumnJoin() + .withTargetAssetId(target.getId()) + .withStatus(status) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(path)) + .withParent(List.of("id"))))); + } + + private static List names(final ClassMapping mapping) { + return mapping.tables().stream().map(bound -> bound.table().fullyQualifiedName()).toList(); + } + + @Test + void aClassListsItsIdentityTableThenContributingTablesByNameThenUnassignedTablesByName() { + final World world = new World(); + final OntologyConcept customer = world.type("Customer"); + world.bind(customer, world.table("zeta", "id"), OntologyBindingRole.IDENTITY, "id"); + world.bind(customer, world.table("mid", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + world.bind(customer, world.table("beta", "id"), null, null); + world.bind(customer, world.table("alpha", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + world.bind(customer, world.table("aaa", "id"), null, null); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(1, mapping.classes().size()); + assertEquals(NS + "Customer", mapping.classes().getFirst().iri().toString()); + assertEquals( + List.of( + "svc.db.public.zeta", + "svc.db.public.alpha", + "svc.db.public.mid", + "svc.db.public.aaa", + "svc.db.public.beta"), + names(mapping.classes().getFirst())); + assertEquals( + Arrays.asList( + OntologyBindingRole.IDENTITY, + OntologyBindingRole.CONTRIBUTING, + OntologyBindingRole.CONTRIBUTING, + null, + null), + mapping.classes().getFirst().tables().stream().map(TableBinding::role).toList()); + assertEquals(0, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + assertEquals(0, mapping.hiddenProperties()); + } + + @Test + void classesComeInIriOrderAndColumnsInBindingOrder() { + final World world = new World(); + final OntologyProperty name = world.data("name"); + final OntologyProperty age = world.data("age"); + final Table people = world.table("people", "id", "age", "name"); + world.bind( + world.type("Zebra"), + people, + OntologyBindingRole.IDENTITY, + "id", + column(name, "name"), + column(age, "age")); + world.bind(world.type("Ant"), world.table("ants", "id"), OntologyBindingRole.IDENTITY, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals( + List.of(NS + "Ant", NS + "Zebra"), + mapping.classes().stream().map(type -> type.iri().toString()).toList()); + assertEquals( + List.of(NS + "name", NS + "age"), + mapping.classes().get(1).tables().getFirst().dataColumns().stream() + .map(data -> data.propertyIri().toString()) + .toList()); + assertEquals( + List.of(List.of("name"), List.of("age")), + mapping.classes().get(1).tables().getFirst().dataColumns().stream() + .map(data -> data.columnPath()) + .toList()); + assertEquals(List.of(List.of("id")), mapping.classes().get(1).tables().getFirst().subjectKey()); + } + + @Test + void aHiddenIdentityTableIsCountedAndTheContributingTableStaysListed() { + final World world = new World(); + final OntologyConcept customer = world.type("Customer"); + world.bind(customer, world.hiddenTable("hidden_id", "id"), OntologyBindingRole.IDENTITY, "id"); + world.bind(customer, world.table("notes", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(List.of("svc.db.public.notes"), names(mapping.classes().getFirst())); + assertEquals(1, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + assertEquals(0, mapping.hiddenProperties()); + } + + @Test + void aHiddenContributingTableIsCountedAndTheIdentityTableStaysListed() { + final World world = new World(); + final OntologyConcept customer = world.type("Customer"); + world.bind(customer, world.table("customers", "id"), OntologyBindingRole.IDENTITY, "id"); + world.bind(customer, world.hiddenTable("secret", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(List.of("svc.db.public.customers"), names(mapping.classes().getFirst())); + assertEquals(1, mapping.hiddenTables()); + } + + @Test + void aClassWhoseTablesAreAllHiddenIsListedWithNoTables() { + final World world = new World(); + world.bind( + world.type("Customer"), + world.hiddenTable("secret", "id"), + OntologyBindingRole.IDENTITY, + "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(1, mapping.classes().size()); + assertEquals(List.of(), mapping.classes().getFirst().tables()); + assertEquals(1, mapping.hiddenTables()); + } + + @Test + void aHiddenClassIsCountedLeftOutAndItsTablesAreCountedWhenHidden() { + final World world = new World(); + world.bind( + world.type("Customer"), world.table("customers", "id"), OntologyBindingRole.IDENTITY, "id"); + final OntologyConcept secret = world.hiddenType("Secret"); + world.bind(secret, world.table("secrets", "id"), OntologyBindingRole.IDENTITY, "id"); + world.bind(secret, world.hiddenTable("vault", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals( + List.of(NS + "Customer"), + mapping.classes().stream().map(type -> type.iri().toString()).toList()); + assertEquals(1, mapping.hiddenClasses()); + assertEquals(1, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenProperties()); + } + + @Test + void aHiddenPropertyIsCountedOnceWhateverNumberOfColumnsBindItAndLeftOutOfTheColumns() { + final World world = new World(); + final OntologyProperty visible = world.data("name"); + final OntologyProperty secret = world.hiddenProperty("salary"); + final OntologyConcept customer = world.type("Customer"); + world.bind( + customer, + world.table("customers", "id", "name", "pay", "bonus"), + OntologyBindingRole.IDENTITY, + "id", + column(visible, "name"), + column(secret, "pay"), + column(secret, "bonus")); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding bound = mapping.classes().getFirst().tables().getFirst(); + assertEquals(List.of(NS + "name"), iris(bound)); + assertEquals(List.of(), bound.absentFromVersion()); + assertEquals(1, mapping.hiddenProperties()); + assertEquals(0, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + } + + private static List iris(final TableBinding bound) { + return bound.dataColumns().stream().map(data -> data.propertyIri().toString()).toList(); + } + + @Test + void aPropertyOfAHiddenTableIsNotCounted() { + final World world = new World(); + final OntologyProperty secret = world.hiddenProperty("salary"); + world.bind( + world.type("Customer"), + world.hiddenTable("customers", "id", "pay"), + OntologyBindingRole.IDENTITY, + "id", + column(secret, "pay")); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(0, mapping.hiddenProperties()); + assertEquals(1, mapping.hiddenTables()); + } + + @Test + void nothingHiddenAppearsInTheValueItsTextOrItsJson() { + final World world = new World(); + final OntologyProperty secretProperty = world.hiddenProperty("salary"); + final OntologyConcept secretClass = world.hiddenType("Classified"); + final OntologyConcept customer = world.type("Customer"); + final Table secretTable = world.hiddenTable("vault_ledger", "id", "pay"); + world.bind( + customer, + world.table("customers", "id", "pay"), + OntologyBindingRole.IDENTITY, + "id", + column(secretProperty, "pay")); + world.bind(customer, secretTable, OntologyBindingRole.CONTRIBUTING, "id"); + world.bind( + secretClass, world.table("classified_rows", "id"), OntologyBindingRole.IDENTITY, "id"); + + final OntologyTableMapping mapping = world.build(); + final String text = mapping.toString(); + final String json = JsonUtils.pojoToJson(mapping); + + assertEquals(1, mapping.hiddenTables()); + assertEquals(1, mapping.hiddenClasses()); + assertEquals(1, mapping.hiddenProperties()); + for (final String shown : List.of(text, json)) { + assertFalse(shown.contains("vault_ledger")); + assertFalse(shown.contains(secretTable.getId().toString())); + assertFalse(shown.contains("Classified")); + assertFalse(shown.contains(secretClass.getId().toString())); + assertFalse(shown.contains("salary")); + assertFalse(shown.contains(secretProperty.getId().toString())); + assertFalse(shown.contains("classified_rows")); + } + } + + @Test + void aFilterWhoseColumnWasDroppedGivesTheReasonAndNoValue() { + final World world = new World(); + world.bind( + world.type("Customer"), + world.table("customers", "id"), + OntologyBindingRole.IDENTITY, + "id", + new OntologyRowFilter() + .withColumn(List.of("region")) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue("eu-secret")); + + final OntologyTableMapping mapping = world.build(); + + final Broken broken = + assertInstanceOf( + Broken.class, mapping.classes().getFirst().tables().getFirst().rowFilter()); + assertEquals( + "The row filter of table svc.db.public.customers names a column that the table no longer" + + " has", + broken.reason()); + assertFalse(mapping.toString().contains("eu-secret")); + assertFalse(JsonUtils.pojoToJson(mapping).contains("eu-secret")); + } + + @Test + void aFilterWhoseValueNoLongerParsesGivesTheReasonAndNoValue() { + final World world = new World(); + world.bind( + world.type("Customer"), + world.table("customers", "id", "region"), + OntologyBindingRole.IDENTITY, + "id", + new OntologyRowFilter() + .withColumn(List.of("region")) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue("not-a-number-secret")); + + final OntologyTableMapping mapping = world.build(); + + final Broken broken = + assertInstanceOf( + Broken.class, mapping.classes().getFirst().tables().getFirst().rowFilter()); + assertEquals( + "A value of the row filter of table svc.db.public.customers no longer parses as the data" + + " type of column region", + broken.reason()); + assertFalse(mapping.toString().contains("not-a-number-secret")); + assertFalse(JsonUtils.pojoToJson(mapping).contains("not-a-number-secret")); + } + + @Test + void aFilterThatStillAppliesIsParsedAndABindingWithNoFilterHasNone() { + final World world = new World(); + final OntologyConcept customer = world.type("Customer"); + world.bind( + customer, + world.table("customers", "id", "region"), + OntologyBindingRole.IDENTITY, + "id", + new OntologyRowFilter() + .withColumn(List.of("region")) + .withOperator(OntologyRowFilterOperator.GREATER_THAN) + .withValue(7)); + world.bind(customer, world.table("notes", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + + final OntologyTableMapping mapping = world.build(); + + final List tables = mapping.classes().getFirst().tables(); + final Applies applies = assertInstanceOf(Applies.class, tables.get(0).rowFilter()); + assertEquals(List.of("region"), applies.filter().column()); + assertEquals(OntologyRowFilterOperator.GREATER_THAN, applies.filter().operator()); + assertEquals(1, applies.filter().values().size()); + assertNull(tables.get(1).rowFilter()); + } + + @Test + void aRelationColumnCarriesItsJoinStatusTargetPairsAndTheClassesThatIdentifyTheTarget() { + final World world = new World(); + final OntologyProperty placed = world.relation("placedBy"); + final OntologyProperty approved = world.relation("approvedBy"); + final Table customers = world.table("customers", "id"); + world.bind(world.type("Customer"), customers, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Order"), + world.table("orders", "id", "customer_id", "approver_id"), + OntologyBindingRole.IDENTITY, + "id", + link(placed, "customer_id", customers, OntologyJoinStatus.CONFIRMED), + link(approved, "approver_id", customers, OntologyJoinStatus.INFERRED)); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding orders = mapping.classes().get(1).tables().getFirst(); + assertEquals(NS + "Order", mapping.classes().get(1).iri().toString()); + assertEquals(2, orders.relationColumns().size()); + final var first = orders.relationColumns().get(0); + assertEquals(NS + "placedBy", first.relationIri().toString()); + assertEquals(List.of("customer_id"), first.columnPath()); + assertEquals(OntologyJoinStatus.CONFIRMED, first.join().status()); + assertEquals(customers.getId(), first.join().targetTableId()); + assertEquals( + List.of(List.of("customer_id")), first.join().on().stream().map(p -> p.child()).toList()); + assertEquals(List.of(List.of("id")), first.join().on().stream().map(p -> p.parent()).toList()); + assertEquals( + List.of(NS + "Customer"), + first.join().objectClasses().stream().map(URI::toString).toList()); + assertEquals(OntologyJoinStatus.INFERRED, orders.relationColumns().get(1).join().status()); + assertEquals(List.of(), orders.dataColumns()); + } + + @Test + void aTableThatIdentifiesTwoClassesGivesOnlyTheOnesInTheDeclaredRange() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy", "Customer"); + final Table parties = world.table("parties", "id"); + world.bind(world.type("Customer"), parties, OntologyBindingRole.IDENTITY, "id"); + world.bind(world.type("Supplier"), parties, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Order"), + world.table("orders", "id", "party_id"), + OntologyBindingRole.IDENTITY, + "id", + link(placedBy, "party_id", parties, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding orders = mapping.classes().get(1).tables().getFirst(); + assertEquals( + List.of(NS + "Customer"), + orders.relationColumns().getFirst().join().objectClasses().stream() + .map(URI::toString) + .toList()); + } + + @Test + void aRelationWithNoDeclaredRangeGivesEveryClassThatIdentifiesTheTargetInIriOrder() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy"); + final Table parties = world.table("parties", "id"); + world.bind(world.type("Supplier"), parties, OntologyBindingRole.IDENTITY, "id"); + world.bind(world.type("Customer"), parties, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Order"), + world.table("orders", "id", "party_id"), + OntologyBindingRole.IDENTITY, + "id", + link(placedBy, "party_id", parties, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding orders = mapping.classes().get(1).tables().getFirst(); + assertEquals( + List.of(NS + "Customer", NS + "Supplier"), + orders.relationColumns().getFirst().join().objectClasses().stream() + .map(URI::toString) + .toList()); + } + + @Test + void aRangeThatNamesASuperclassKeepsItsSubclassesAndDropsTheUnrelated() { + final World world = new World(); + final OntologyProperty managedBy = world.relation("managedBy", "Person"); + world.parents.put(NS + "Employee", Set.of(NS + "Person")); + final Table staff = world.table("staff", "id"); + world.bind(world.type("Employee"), staff, OntologyBindingRole.IDENTITY, "id"); + world.bind(world.type("Robot"), staff, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Team"), + world.table("teams", "id", "manager_id"), + OntologyBindingRole.IDENTITY, + "id", + link(managedBy, "manager_id", staff, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding teams = mapping.classes().get(2).tables().getFirst(); + assertEquals(NS + "Team", mapping.classes().get(2).iri().toString()); + assertEquals( + List.of(NS + "Employee"), + teams.relationColumns().getFirst().join().objectClasses().stream() + .map(URI::toString) + .toList()); + } + + @Test + void aRangeClassWithNoIdentityBindingOnTheTargetGivesAnEmptyList() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy", "Customer"); + final Table parties = world.table("parties", "id"); + world.bind(world.type("Customer"), parties, OntologyBindingRole.CONTRIBUTING, "id"); + world.bind( + world.type("Order"), + world.table("orders", "id", "party_id"), + OntologyBindingRole.IDENTITY, + "id", + link(placedBy, "party_id", parties, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + assertEquals( + List.of(), + mapping + .classes() + .get(1) + .tables() + .getFirst() + .relationColumns() + .getFirst() + .join() + .objectClasses()); + } + + @Test + void aJoinOntoAHiddenTableIsCountedAndNotListedAndOntoADeletedTableIsNeither() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy"); + final OntologyProperty shippedTo = world.relation("shippedTo"); + final Table vault = world.hiddenTable("vault", "id"); + final Table gone = world.table("gone", "id"); + world.tables.remove(gone.getId()); + world.bind( + world.type("Order"), + world.table("orders", "id", "a", "b"), + OntologyBindingRole.IDENTITY, + "id", + link(placedBy, "a", vault, OntologyJoinStatus.CONFIRMED), + link(shippedTo, "b", gone, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(List.of(), mapping.classes().getFirst().tables().getFirst().relationColumns()); + assertEquals(1, mapping.hiddenTables()); + assertFalse(JsonUtils.pojoToJson(mapping).contains(vault.getId().toString())); + } + + @Test + void aRelationColumnStoredBeforeJoinsExistedIsListedWithNoJoin() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy"); + world.bind( + world.type("Order"), + world.table("orders", "id", "a"), + OntologyBindingRole.IDENTITY, + "id", + column(placedBy, "a")); + + final OntologyTableMapping mapping = world.build(); + + final var relation = + mapping.classes().getFirst().tables().getFirst().relationColumns().getFirst(); + assertEquals(NS + "placedBy", relation.relationIri().toString()); + assertNull(relation.join()); + } + + @Test + void aClassWithNoBoundTableIsLeftOutAndADeletedTableIsCountedNowhere() { + final World world = new World(); + world.type("Unbound"); + final Table gone = world.table("gone", "id"); + world.tables.remove(gone.getId()); + world.bind(world.type("OnlyDeleted"), gone, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Customer"), world.table("customers", "id"), OntologyBindingRole.IDENTITY, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals( + List.of(NS + "Customer"), + mapping.classes().stream().map(type -> type.iri().toString()).toList()); + assertEquals(0, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + } + + @Test + void aPropertyTheVersionLacksIsListedByColumnPathAndAColumnTheTableLostIsListedApart() { + final World world = new World(); + final OntologyProperty lacking = world.data("retired"); + world.properties.remove(lacking.getId()); + final OntologyProperty name = world.data("name"); + world.bind( + world.type("Customer"), + world.table("customers", "id", "old"), + OntologyBindingRole.IDENTITY, + "id", + column(lacking, "old"), + column(name, "dropped")); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding bound = mapping.classes().getFirst().tables().getFirst(); + assertEquals(List.of(List.of("old")), bound.absentFromVersion()); + assertEquals(List.of(List.of("dropped")), bound.missingColumns()); + assertEquals(List.of(), bound.dataColumns()); + assertEquals(0, mapping.hiddenProperties()); + assertFalse(JsonUtils.pojoToJson(mapping).contains(lacking.getId().toString())); + } + + @Test + void theTableCarriesItsIdNameServiceTypeAndColumns() { + final World world = new World(); + final Table customers = world.table("customers", "id", "name"); + world.bind(world.type("Customer"), customers, OntologyBindingRole.IDENTITY, "id"); + + final OntologyTableMapping.TableRef ref = + world.build().classes().getFirst().tables().getFirst().table(); + + assertEquals(customers.getId(), ref.id()); + assertEquals("svc.db.public.customers", ref.fullyQualifiedName()); + assertNull(ref.serviceType()); + assertEquals(List.of("id", "name"), ref.columns().stream().map(Column::getName).toList()); + } +} From 0cae8d30b0d3eb48cff9776d227ba92319c8e8e7 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 15:34:43 -0800 Subject: [PATCH 182/203] Test the table mapping of a version as three callers read it, and count its statements --- ...-table-mapping-of-a-version-is-one-read.md | 4 +- .../it/tests/OntologyTableMappingsIT.java | 609 ++++++++++++++++++ 2 files changed, 611 insertions(+), 2 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java diff --git a/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md b/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md index 14702e82db73..a6cfa5526e3c 100644 --- a/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md +++ b/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md @@ -24,7 +24,7 @@ classes are unrelated, would act on a gap it cannot see. **The mapping of a version is one read.** `OntologyTableMappings.read(access, ontologyId, version)` returns an `OntologyTableMapping`: every class of the version that binds an existing table, each with its tables, subject keys, row filters, data columns and relation columns. A `null` version -means the active release. A release with no active release is a 404 that says so. The draft goes +means the active release. A read of the release of an ontology with no active release is a 404 that says so. The draft goes through the same gate as the statements, a 403 without the right to read the working draft. **One call reads the binding rows between two equal reads of the binding revisions** of all the @@ -34,7 +34,7 @@ lands between the reads is either seen whole or refused, never half seen. **The number of queries does not depend on the number of classes or bindings.** One query reads each kind, in chunks of ids when a list is longer than one IN list: the ontology and its state, the ids of the classes, the revisions twice, the binding rows, the tables, the classes, the properties, -and the class hierarchy when a relation declares a range. +and the class hierarchy when a relation declares a range. A read runs 42 statements on MySQL for a version with 3 classes and for one with 300 classes and 600 bindings, for the release and for the draft alike. **A part the caller may not view is counted and never named.** The answer carries `hiddenTables`, `hiddenClasses` and `hiddenProperties`. A hidden part appears in no field and no id, name, column diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java new file mode 100644 index 000000000000..b7e440862fdf --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java @@ -0,0 +1,609 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.dataProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import jakarta.ws.rs.ClientErrorException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.statement.SqlLogger; +import org.jdbi.v3.core.statement.StatementContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.SqlQueryCounter; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyTableMapping; +import org.openmetadata.service.ontology.OntologyTableMapping.ClassMapping; +import org.openmetadata.service.ontology.OntologyTableMapping.TableBinding; +import org.openmetadata.service.ontology.OntologyTableMappings; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.auth.CatalogSecurityContext; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.slf4j.LoggerFactory; + +/** + * The table mapping of a whole version of an ontology, read in the server as three callers read it: + * an administrator, a reader who may not view some of the tables, classes or properties, and a + * person who may not read the working draft. It also counts the statements of a read of 300 classes + * with 600 bindings, and changes a binding while the read is in flight. + */ +@Isolated("Counts SQL statements and writes bindings in the middle of a read") +@ExtendWith(TestNamespaceExtension.class) +class OntologyTableMappingsIT extends BaseOntologyApprovalIT { + private static final URI CUSTOMER = URI.create("urn:Customer"); + private static final URI ORDER = URI.create("urn:Order"); + private static final URI PRODUCT = URI.create("urn:Product"); + private static final String NOT_THE_OWNER = "!isOwner()"; + private static final String EVERY_RESOURCE = "All"; + private static final int CLASSES = 300; + + /** Three classes and a relation: Customer with a contributing table, Order, and Product. */ + private record Scene( + Ontology ontology, + OntologyConcept customer, + OntologyConcept order, + OntologyConcept product, + OntologyProperty name, + OntologyProperty total, + OntologyProperty placedBy, + Table customers, + Table notes, + Table orders, + Table products) {} + + private static Scene scene(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept customer = declareClass(ontology, "Customer", CUSTOMER); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final OntologyConcept product = declareClass(ontology, "Product", PRODUCT); + final DatabaseSchema schema = schema(ns); + final Table customers = + table( + schema, + "customers", + column("id", ColumnDataType.BIGINT), + column("name", ColumnDataType.VARCHAR)); + final Table notes = + table( + schema, + "customer_notes", + column("customer_id", ColumnDataType.BIGINT), + column("note", ColumnDataType.VARCHAR)); + final Table orders = + table( + schema, + "orders", + column("id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT), + column("total", ColumnDataType.DECIMAL)); + final Table products = + table( + schema, + "products", + column("sku", ColumnDataType.VARCHAR), + column("alias", ColumnDataType.VARCHAR)); + final OntologyProperty name = dataProperty(ontology, "name", customer); + final OntologyProperty total = dataProperty(ontology, "total", order); + final OntologyProperty placedBy = objectProperty(ontology, "placedBy", order, customer); + put( + admin(), + customer, + binding(customers, OntologyBindingRole.IDENTITY, "id") + .withColumns(List.of(column(name, "name"))), + 0L); + put(admin(), customer, binding(notes, OntologyBindingRole.CONTRIBUTING, "customer_id"), 1L); + put( + admin(), + order, + binding(orders, OntologyBindingRole.IDENTITY, "id") + .withColumns( + List.of( + column(total, "total"), + column(placedBy, "customer_id") + .withJoin( + join(customers, OntologyJoinStatus.CONFIRMED, "customer_id", "id")))), + 0L); + put(admin(), product, binding(products, OntologyBindingRole.IDENTITY, "sku"), 0L); + return new Scene( + ontology, customer, order, product, name, total, placedBy, customers, notes, orders, + products); + } + + private static OntologyTableMappings service() { + final var dao = Entity.getCollectionDAO(); + final Authorizer authorizer = Entity.getAuthorizer(); + return new OntologyTableMappings( + new OntologyConceptBindingStore(dao, OntologyConceptBindingStore.registeredAssetTables()), + dao, + authorizer, + Entity::getEntityRepository, + (context, ontologyId) -> + authorizer.authorize( + context, + new OperationContext(Entity.ONTOLOGY, MetadataOperation.EDIT_ALL), + new ResourceContext<>(Entity.ONTOLOGY, ontologyId, null))); + } + + private static Access as(final String user) { + return new Access(null, new CatalogSecurityContext(() -> user, "https", "JWT", Set.of())); + } + + private static OntologyTableMapping read( + final String user, final Ontology ontology, final OntologyStatementVersion version) { + return service().read(as(user), ontology.getId(), version); + } + + /** A caller who holds every right but one: the right to view what they do not own. */ + private static String readerWhoViewsOnlyWhatTheyOwn( + final RdfAccessFixtures fixtures, final String resource) { + final var everything = fixtures.allowRole(MetadataOperation.ALL, EVERY_RESOURCE); + final var denied = fixtures.denyRole(MetadataOperation.VIEW_BASIC, resource, NOT_THE_OWNER); + final OpenMetadataClient client = + OntologyBindingFixtures.client( + fixtures.userToken("reader", List.of(everything.getId(), denied.getId()))); + return OntologyBindingFixtures.readerReference(client).getName(); + } + + private static EntityReference user(final String name) { + return admin().users().getByName(name).getEntityReference(); + } + + private static void owns(final String reader, final Table table) { + final String id = table.getId().toString(); + admin() + .tables() + .update(id, admin().tables().get(id, "owners").withOwners(List.of(user(reader)))); + } + + private static void owns(final String reader, final OntologyConcept type) { + final String id = type.getId().toString(); + admin() + .ontologyConcepts() + .update(id, admin().ontologyConcepts().get(id, "owners").withOwners(List.of(user(reader)))); + } + + private static void owns(final String reader, final OntologyProperty property) { + final String id = property.getId().toString(); + admin() + .ontologyProperties() + .update( + id, admin().ontologyProperties().get(id, "owners").withOwners(List.of(user(reader)))); + } + + private static List iris(final OntologyTableMapping mapping) { + return mapping.classes().stream().map(type -> type.iri().toString()).toList(); + } + + private static List tableNames(final ClassMapping type) { + return type.tables().stream() + .map(bound -> bound.table().fullyQualifiedName()) + .map(fqn -> fqn.substring(fqn.lastIndexOf('.') + 1)) + .toList(); + } + + private static ClassMapping of(final OntologyTableMapping mapping, final URI iri) { + return mapping.classes().stream() + .filter(type -> type.iri().equals(iri)) + .findFirst() + .orElseThrow(); + } + + @Test + void anAdministratorReadsTheWholeMappingOfTheReleaseAndOfTheDraft(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + + final OntologyTableMapping release = read("admin", scene.ontology(), null); + final OntologyTableMapping draft = + read("admin", scene.ontology(), OntologyStatementVersion.DRAFT); + + for (final OntologyTableMapping mapping : List.of(release, draft)) { + assertEquals(List.of("urn:Customer", "urn:Order", "urn:Product"), iris(mapping)); + assertEquals(List.of("customers", "customer_notes"), tableNames(of(mapping, CUSTOMER))); + assertEquals(List.of("orders"), tableNames(of(mapping, ORDER))); + assertEquals(List.of("products"), tableNames(of(mapping, PRODUCT))); + assertEquals(0, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + assertEquals(0, mapping.hiddenProperties()); + } + assertEquals(OntologyStatementVersion.RELEASE, release.version().getKind()); + assertEquals(OntologyStatementVersion.DRAFT, draft.version().getKind()); + final TableBinding orders = of(release, ORDER).tables().getFirst(); + assertEquals(OntologyBindingRole.IDENTITY, orders.role()); + assertEquals(List.of(List.of("id")), orders.subjectKey()); + assertNull(orders.rowFilter()); + assertEquals(1, orders.dataColumns().size()); + assertEquals(List.of("total"), orders.dataColumns().getFirst().columnPath()); + assertEquals(1, orders.relationColumns().size()); + final var relation = orders.relationColumns().getFirst(); + assertEquals(scene.placedBy().getIri(), relation.relationIri()); + assertEquals(List.of("customer_id"), relation.columnPath()); + assertEquals(OntologyJoinStatus.CONFIRMED, relation.join().status()); + assertEquals(scene.customers().getId(), relation.join().targetTableId()); + assertEquals( + List.of(List.of("customer_id")), + relation.join().on().stream().map(p -> p.child()).toList()); + assertEquals( + List.of(List.of("id")), relation.join().on().stream().map(p -> p.parent()).toList()); + assertEquals( + List.of("urn:Customer"), + relation.join().objectClasses().stream().map(URI::toString).toList()); + assertEquals(List.of(), orders.absentFromVersion()); + assertEquals(List.of(), orders.missingColumns()); + } + + @Test + void aReleaseNeedsAnActiveReleaseAndAnOntologyWithNoneIs404(final TestNamespace ns) { + final Scene scene = scene(ns); + + final EntityNotFoundException none = + assertThrows(EntityNotFoundException.class, () -> read("admin", scene.ontology(), null)); + assertEquals( + "Ontology " + scene.ontology().getFullyQualifiedName() + " has no active release", + none.getMessage()); + assertEquals( + 3, read("admin", scene.ontology(), OntologyStatementVersion.DRAFT).classes().size()); + } + + @Test + void aReaderWhoMayNotViewATableReadsTheRestAndOneHiddenTable(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapTb" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.TABLE); + for (final Table table : List.of(scene.customers(), scene.orders(), scene.products())) { + owns(reader, table); + } + + final OntologyTableMapping seen = read(reader, scene.ontology(), null); + + assertEquals(List.of("urn:Customer", "urn:Order", "urn:Product"), iris(seen)); + assertEquals(List.of("customers"), tableNames(of(seen, CUSTOMER))); + assertEquals(List.of("orders"), tableNames(of(seen, ORDER))); + assertEquals(List.of("products"), tableNames(of(seen, PRODUCT))); + assertEquals(1, seen.hiddenTables()); + assertEquals(0, seen.hiddenClasses()); + assertEquals(0, seen.hiddenProperties()); + assertNamesNothingOf(seen, scene.notes().getId().toString(), "customer_notes"); + } + } + + @Test + void aReaderWhoMayNotViewTheJoinTargetCountsItAndSeesNoRelationColumn(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapJn" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.TABLE); + owns(reader, scene.orders()); + owns(reader, scene.products()); + owns(reader, scene.notes()); + + final OntologyTableMapping seen = read(reader, scene.ontology(), null); + + assertEquals(List.of(), of(seen, ORDER).tables().getFirst().relationColumns()); + assertEquals(List.of("customer_notes"), tableNames(of(seen, CUSTOMER))); + assertEquals(1, seen.hiddenTables()); + assertNamesNothingOf(seen, scene.customers().getId().toString(), "\"customers\""); + } + } + + @Test + void aReaderWhoMayNotViewAClassReadsTheOthersAndOneHiddenClass(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapCl" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.ONTOLOGY_CONCEPT); + owns(reader, scene.customer()); + owns(reader, scene.order()); + + final OntologyTableMapping seen = read(reader, scene.ontology(), null); + + assertEquals(List.of("urn:Customer", "urn:Order"), iris(seen)); + assertEquals(1, seen.hiddenClasses()); + assertEquals(0, seen.hiddenTables()); + assertEquals(0, seen.hiddenProperties()); + assertNamesNothingOf(seen, scene.product().getId().toString(), "Product", "products"); + } + } + + @Test + void aReaderWhoMayNotViewAPropertyReadsTheOthersAndOneHiddenProperty(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapPr" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.ONTOLOGY_PROPERTY); + owns(reader, scene.total()); + owns(reader, scene.placedBy()); + + final OntologyTableMapping seen = read(reader, scene.ontology(), null); + + assertEquals(List.of(), of(seen, CUSTOMER).tables().getFirst().dataColumns()); + assertEquals(1, of(seen, ORDER).tables().getFirst().dataColumns().size()); + assertEquals(1, of(seen, ORDER).tables().getFirst().relationColumns().size()); + assertEquals(1, seen.hiddenProperties()); + assertEquals(0, seen.hiddenTables()); + assertEquals(0, seen.hiddenClasses()); + assertNamesNothingOf(seen, scene.name().getId().toString(), "urn:name"); + } + } + + private static void assertNamesNothingOf( + final OntologyTableMapping mapping, final String... hidden) { + final String text = mapping.toString(); + final String json = org.openmetadata.schema.utils.JsonUtils.pojoToJson(mapping); + for (final String name : hidden) { + assertFalse(text.contains(name), name); + assertFalse(json.contains(name), name); + } + } + + @Test + void theDraftNeedsTheRightToReadTheWorkingDraftAndTheReleaseDoesNot(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapDr" + ns.shortPrefix())) { + final var everything = fixtures.allowRole(MetadataOperation.ALL, EVERY_RESOURCE); + final var noEdit = fixtures.denyRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY); + final var viewer = + OntologyBindingFixtures.client( + fixtures.userToken("viewer", List.of(everything.getId(), noEdit.getId()))); + final String user = OntologyBindingFixtures.readerReference(viewer).getName(); + final var editor = + OntologyBindingFixtures.client(fixtures.userToken("editor", List.of(everything.getId()))); + final String editorName = OntologyBindingFixtures.readerReference(editor).getName(); + + assertThrows( + AuthorizationException.class, + () -> read(user, scene.ontology(), OntologyStatementVersion.DRAFT)); + assertEquals(3, read(user, scene.ontology(), null).classes().size()); + assertEquals( + 3, read(editorName, scene.ontology(), OntologyStatementVersion.DRAFT).classes().size()); + } + } + + @Test + void aReadLogsOnlyCountsAndNeverAHiddenName(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + final Logger logger = (Logger) LoggerFactory.getLogger(OntologyTableMappings.class); + final Level before = logger.getLevel(); + final ListAppender lines = new ListAppender<>(); + lines.start(); + logger.addAppender(lines); + logger.setLevel(Level.DEBUG); + try (var fixtures = new RdfAccessFixtures("mapLg" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.TABLE); + owns(reader, scene.customers()); + owns(reader, scene.orders()); + owns(reader, scene.products()); + + read(reader, scene.ontology(), null); + + assertEquals(1, lines.list.size()); + assertEquals( + "Read the table mapping of ontology " + + scene.ontology().getId() + + ": 3 classes, 1 hidden tables, 0 hidden classes, 0 hidden properties", + lines.list.getFirst().getFormattedMessage()); + } finally { + logger.detachAppender(lines); + logger.setLevel(before); + } + } + + /** Counts the table row reads of the reading thread and writes a binding after each. */ + private static final class WriteAfterBindingRows implements SqlLogger { + private final Thread reader = Thread.currentThread(); + private final AtomicInteger writes = new AtomicInteger(); + private final int most; + private final Runnable write; + + WriteAfterBindingRows(final int most, final Runnable write) { + this.most = most; + this.write = write; + } + + @Override + public void logAfterExecution(final StatementContext context) { + final String sql = context.getRenderedSql().toLowerCase(java.util.Locale.ROOT); + if (Thread.currentThread() == reader + && sql.contains("from ontology_concept_binding") + && sql.contains("bindingorder") + && writes.get() < most) { + writes.incrementAndGet(); + write.run(); + } + } + } + + private static Runnable flipProductKey(final Scene scene) { + final AtomicInteger flips = new AtomicInteger(); + return () -> { + final String key = flips.getAndIncrement() % 2 == 0 ? "alias" : "sku"; + put( + admin(), + scene.product(), + binding(scene.products(), OntologyBindingRole.IDENTITY, key), + bindings(admin(), scene.product()).getRevision()); + }; + } + + @Test + void aBindingChangedWhileTheRowsAreReadGivesTheNewMappingAndNeverAMix(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + final Jdbi jdbi = Entity.getJdbi(); + final SqlLogger previous = + jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); + final var changing = new WriteAfterBindingRows(1, flipProductKey(scene)); + jdbi.setSqlLogger(changing); + final OntologyTableMapping seen; + try { + seen = read("admin", scene.ontology(), null); + } finally { + jdbi.setSqlLogger(previous); + } + + assertEquals(1, changing.writes.get()); + assertEquals(List.of(List.of("alias")), of(seen, PRODUCT).tables().getFirst().subjectKey()); + assertEquals(List.of(List.of("id")), of(seen, ORDER).tables().getFirst().subjectKey()); + } + + @Test + void aBindingThatKeepsChangingIsA409AfterThreeReads(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + final Jdbi jdbi = Entity.getJdbi(); + final SqlLogger previous = + jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); + final var changing = new WriteAfterBindingRows(Integer.MAX_VALUE, flipProductKey(scene)); + jdbi.setSqlLogger(changing); + final ClientErrorException refused; + try { + refused = + assertThrows(ClientErrorException.class, () -> read("admin", scene.ontology(), null)); + } finally { + jdbi.setSqlLogger(previous); + } + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "The table bindings changed while the mapping was read. Ask again", refused.getMessage()); + assertEquals(3, changing.writes.get()); + } + + @Test + void aVersionOf300ClassesAndFilteredBindingsCostsTheSameStatementsAsOneOfThree( + final TestNamespace ns) { + final Scene small = scene(ns); + activate(ns, small.ontology()); + final Ontology ontology = createOntology(ns, "wide"); + final DatabaseSchema schema = schema(ns); + final Table rows = + table( + schema, + "rows", + column("id", ColumnDataType.BIGINT), + column("kind", ColumnDataType.VARCHAR)); + final Table extras = + table( + schema, + "extras", + column("row_id", ColumnDataType.BIGINT), + column("note", ColumnDataType.VARCHAR)); + final List classes = new ArrayList<>(); + IntStream.range(0, CLASSES) + .forEach( + index -> { + final OntologyConcept type = + declareClass(ontology, "Kind" + index, URI.create("urn:Kind" + index)); + classes.add(type); + put( + admin(), + type, + binding(rows, OntologyBindingRole.IDENTITY, "id") + .withRowFilter(filter("kind", OntologyRowFilterOperator.EQUALS, "k" + index)), + 0L); + put(admin(), type, binding(extras, OntologyBindingRole.CONTRIBUTING, "row_id"), 1L); + }); + final OntologyProperty follows = + objectProperty(ontology, "follows", classes.get(0), classes.get(1)); + put( + admin(), + classes.get(0), + binding(rows, OntologyBindingRole.IDENTITY, "id") + .withRowFilter(filter("kind", OntologyRowFilterOperator.EQUALS, "k0")) + .withColumns( + List.of( + column(follows, "id") + .withJoin(join(rows, OntologyJoinStatus.CONFIRMED, "id", "id")))), + 2L); + activate(ns, ontology); + + final int threeRelease = statements(small.ontology(), null); + final int threeDraft = statements(small.ontology(), OntologyStatementVersion.DRAFT); + final int release = statements(ontology, null); + final int draft = statements(ontology, OntologyStatementVersion.DRAFT); + + System.out.printf( + "TABLE-MAPPING-COST threeRelease=%d threeDraft=%d release300=%d draft300=%d%n", + threeRelease, threeDraft, release, draft); + assertEquals(CLASSES, read("admin", ontology, null).classes().size()); + assertEquals( + 2 * CLASSES, + read("admin", ontology, null).classes().stream() + .mapToInt(type -> type.tables().size()) + .sum()); + assertEquals(42, threeRelease); + assertEquals(42, threeDraft); + assertEquals(42, release); + assertEquals(42, draft); + } + + private static int statements(final Ontology ontology, final OntologyStatementVersion version) { + final SqlQueryCounter counter = new SqlQueryCounter(Entity.getJdbi(), ""); + try { + read("admin", ontology, version); + return counter.count(); + } finally { + counter.close(); + } + } +} From 61a037234a1af2ba3d79425a03a778d3ea24e227 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 17:14:03 -0800 Subject: [PATCH 183/203] Regenerate the UI types for mapping health findings --- .../api/data/ontologyMappingHealth.ts | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingHealth.ts b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingHealth.ts index da20c01dba93..217a7a751c9b 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingHealth.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/api/data/ontologyMappingHealth.ts @@ -39,9 +39,9 @@ export interface Entry { */ asset?: EntityReference; /** - * A column of `asset`: the bound column on `relationColumnWithoutJoin` and - * `joinNotConfirmed`, the key column on `keyTypeMismatch`, and the child column on - * `joinTypeMismatch`. + * A column of `asset`: the bound column on `relationColumnWithoutJoin`, `joinNotConfirmed` + * and `columnTypeMismatch`, the key column on `keyTypeMismatch` and `sensitiveKeyColumn`, + * and the child column on `joinTypeMismatch`. */ columnPath?: string[]; /** @@ -54,7 +54,7 @@ export interface Entry { */ databases?: EntityReference[]; /** - * Data type of `columnPath` on the type findings. + * Data type of `columnPath` on the type findings and on `columnTypeMismatch`. */ dataType?: DataType; /** @@ -62,10 +62,14 @@ export interface Entry { */ keyLength?: number; /** - * The property of the bound column on the relation column and join findings, when the - * caller may view it. + * The property of the bound column on the relation column, join and `columnTypeMismatch` + * findings, when the caller may view it. */ property?: EntityReference; + /** + * The IRI of the XSD datatype that is the range of `property`, on `columnTypeMismatch`. + */ + propertyDatatype?: string; /** * The identity table on the key findings, and the join target on the join findings when the * caller may view it. @@ -98,8 +102,8 @@ export interface Entry { * * The class the finding is about. Absent on `multipleDatabases`. * - * The property of the bound column on the relation column and join findings, when the - * caller may view it. + * The property of the bound column on the relation column, join and `columnTypeMismatch` + * findings, when the caller may view it. * * The identity table on the key findings, and the join target on the join findings when the * caller may view it. @@ -150,7 +154,7 @@ export interface EntityReference { } /** - * Data type of `columnPath` on the type findings. + * Data type of `columnPath` on the type findings and on `columnTypeMismatch`. * * This enum defines the type of data stored in a column. * @@ -256,9 +260,14 @@ export enum DataType { * `outsideMappingSource`: the bound table sits outside the ontology's mapping source. * `multipleDatabases`: the ontology names no mapping source and its bound tables sit in * more than one database. It is reported on each page that finds a database no earlier page - * found, once two are known. + * found, once two are known. `sensitiveKeyColumn`: a subject key column of a table that has + * a role is tagged `PII.Sensitive`, or sits under a column that is, or its table is, so its + * sample data and profile are masked. `columnTypeMismatch`: a column bound to a DATA + * property whose range is one XSD datatype holds a kind of data that datatype does not fit, + * for example a text column for an integer property. Both are advice and refuse nothing. */ export enum EntryType { + ColumnTypeMismatch = "columnTypeMismatch", JoinNotConfirmed = "joinNotConfirmed", JoinTypeMismatch = "joinTypeMismatch", KeyLengthMismatch = "keyLengthMismatch", @@ -267,5 +276,6 @@ export enum EntryType { NoIdentityTable = "noIdentityTable", OutsideMappingSource = "outsideMappingSource", RelationColumnWithoutJoin = "relationColumnWithoutJoin", + SensitiveKeyColumn = "sensitiveKeyColumn", UnassignedBinding = "unassignedBinding", } From 4e67b259ab5fdd51fd3c6cb06d85f150e47a3284 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Fri, 4 Dec 2026 17:45:16 -0800 Subject: [PATCH 184/203] Read a draft table mapping as one state, serialize an applied row filter, and count every hidden property of a viewable table --- ...-table-mapping-of-a-version-is-one-read.md | 10 +-- .../it/tests/OntologyTableMappingsIT.java | 81 ++++++++++++++++++- .../ontology/OntologyMappingReader.java | 2 +- .../ontology/OntologyTableMappingRules.java | 10 ++- .../ontology/OntologyTableMappings.java | 21 ++++- .../service/ontology/OntologyVersion.java | 13 +++ .../service/ontology/sql/TypedRowFilter.java | 4 + .../service/ontology/sql/TypedValue.java | 5 ++ .../OntologyTableMappingRulesTest.java | 23 ++++++ 9 files changed, 155 insertions(+), 14 deletions(-) diff --git a/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md b/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md index a6cfa5526e3c..66cdcbe5403b 100644 --- a/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md +++ b/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md @@ -29,12 +29,12 @@ through the same gate as the statements, a 403 without the right to read the wor **One call reads the binding rows between two equal reads of the binding revisions** of all the classes at once, as a statement does, and returns a 409 after the same three attempts. A change that -lands between the reads is either seen whole or refused, never half seen. +lands between the reads is either seen whole or refused, never half seen. The draft reads the ids of its classes again after the second revision read, and a changed set is a retry like a changed revision, because a class bound for the first time during the read has no revision to compare. **The number of queries does not depend on the number of classes or bindings.** One query reads each kind, in chunks of ids when a list is longer than one IN list: the ontology and its state, the -ids of the classes, the revisions twice, the binding rows, the tables, the classes, the properties, -and the class hierarchy when a relation declares a range. A read runs 42 statements on MySQL for a version with 3 classes and for one with 300 classes and 600 bindings, for the release and for the draft alike. +ids of the classes (twice for the draft), the revisions twice, the binding rows, the tables, the classes, the properties, +and the class hierarchy when a relation declares a range. A read runs 42 statements on MySQL for the release and 43 for the draft, for a version with 3 classes and for one with 300 classes and 600 bindings. A retry adds the statements of one attempt. **A part the caller may not view is counted and never named.** The answer carries `hiddenTables`, `hiddenClasses` and `hiddenProperties`. A hidden part appears in no field and no id, name, column @@ -46,8 +46,8 @@ mapping refuses a value with a non-zero count. tables that a listed relation column joins, that the caller may not view. - `hiddenClasses` counts the classes of the version that bind an existing table and that the caller may not view. -- `hiddenProperties` counts the properties of the version that a column of a listed binding binds - and that the caller may not view. +- `hiddenProperties` counts the properties of the version that a column of a viewable table binds + and that the caller may not view, whether or not the caller may view the class that binds the table. **What is left out silently.** A deleted table is left out and counted nowhere, as the list of the bindings of a class leaves it out. A class with no existing bound table is left out. A column whose diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java index b7e440862fdf..1ddb3d748250 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; @@ -506,6 +507,82 @@ void aBindingChangedWhileTheRowsAreReadGivesTheNewMappingAndNeverAMix(final Test assertEquals(List.of(List.of("id")), of(seen, ORDER).tables().getFirst().subjectKey()); } + /** Writes once, after the first statement of the reading thread that holds {@code fragment}. */ + private static final class WriteAfterStatement implements SqlLogger { + private final Thread reader = Thread.currentThread(); + private final AtomicInteger writes = new AtomicInteger(); + private final String fragment; + private final Runnable write; + + WriteAfterStatement(final String fragment, final Runnable write) { + this.fragment = fragment; + this.write = write; + } + + @Override + public void logAfterExecution(final StatementContext context) { + final String sql = context.getRenderedSql().toLowerCase(java.util.Locale.ROOT); + if (Thread.currentThread() == reader + && sql.contains(fragment) + && writes.getAndIncrement() == 0) { + write.run(); + } + } + } + + @Test + void aClassBoundForTheFirstTimeWhileTheDraftIsReadGivesBothClassesWithTheirNewKeysNeverAMix( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept bound = declareClass(ontology, "Bound", URI.create("urn:Bound")); + final OntologyConcept later = declareClass(ontology, "Later", URI.create("urn:Later")); + final DatabaseSchema schema = schema(ns); + final Table boundRows = + table( + schema, + "bound_rows", + column("id", ColumnDataType.BIGINT), + column("alt", ColumnDataType.BIGINT)); + final Table laterRows = table(schema, "later_rows", column("id", ColumnDataType.BIGINT)); + put(admin(), bound, binding(boundRows, OntologyBindingRole.IDENTITY, "id"), 0L); + final Runnable bindsThenRekeys = + () -> { + put(admin(), later, binding(laterRows, OntologyBindingRole.IDENTITY, "id"), 0L); + put( + admin(), + bound, + binding(boundRows, OntologyBindingRole.IDENTITY, "alt"), + bindings(admin(), bound).getRevision()); + }; + final Jdbi jdbi = Entity.getJdbi(); + final SqlLogger previous = + jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); + final var changing = new WriteAfterStatement("assetcount", bindsThenRekeys); + jdbi.setSqlLogger(changing); + OntologyTableMapping seen = null; + ClientErrorException refused = null; + try { + seen = read("admin", ontology, OntologyStatementVersion.DRAFT); + } catch (final ClientErrorException conflict) { + refused = conflict; + } finally { + jdbi.setSqlLogger(previous); + } + + assertTrue(changing.writes.get() >= 1); + if (refused != null) { + assertEquals(409, refused.getResponse().getStatus()); + } else { + assertEquals(List.of("urn:Bound", "urn:Later"), iris(seen)); + assertEquals( + List.of(List.of("alt")), + of(seen, URI.create("urn:Bound")).tables().getFirst().subjectKey()); + assertEquals( + List.of(List.of("id")), + of(seen, URI.create("urn:Later")).tables().getFirst().subjectKey()); + } + } + @Test void aBindingThatKeepsChangingIsA409AfterThreeReads(final TestNamespace ns) { final Scene scene = scene(ns); @@ -592,9 +669,9 @@ void aVersionOf300ClassesAndFilteredBindingsCostsTheSameStatementsAsOneOfThree( .mapToInt(type -> type.tables().size()) .sum()); assertEquals(42, threeRelease); - assertEquals(42, threeDraft); + assertEquals(43, threeDraft); assertEquals(42, release); - assertEquals(42, draft); + assertEquals(43, draft); } private static int statements(final Ontology ontology, final OntologyStatementVersion version) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java index d1d6221f071b..6064ce18d53e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java @@ -50,7 +50,7 @@ final class OntologyMappingReader { /** A statement reads at most this many contributing tables of one class. */ static final int MAX_CONTRIBUTING_TABLES = 32; - private static final int BINDING_READ_ATTEMPTS = 3; + static final int BINDING_READ_ATTEMPTS = 3; private static final int SEVERAL_TABLES = 2; private final OntologyConceptBindingStore store; private final OntologyBindingAccess catalog; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java index e871ab71d7cb..4c3c052387bb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java @@ -103,6 +103,13 @@ static OntologyTableMapping build(final Facts facts) { .map(BindingRow::assetId) .filter(id -> !facts.viewableTables().contains(id)) .forEach(hidden.tables::add); + bound.stream() + .filter(row -> facts.viewableTables().contains(row.assetId())) + .flatMap(row -> listOrEmpty(row.columns()).stream()) + .map(column -> facts.properties().get(column.getPropertyId())) + .filter( + property -> property != null && !facts.viewableProperties().contains(property.getId())) + .forEach(property -> hidden.properties.add(property.getId())); final Map> identityClasses = identityClasses(facts, bound); final List classes = byClass.entrySet().stream() @@ -172,9 +179,6 @@ private static TableBinding binding( final List> missing = new ArrayList<>(); for (final OntologyColumnBinding column : listOrEmpty(row.columns())) { final OntologyProperty property = facts.properties().get(column.getPropertyId()); - if (property != null && !facts.viewableProperties().contains(property.getId())) { - hidden.properties.add(property.getId()); - } if (OntologyBindingRules.resolveColumn(table, column.getColumnPath()) == null) { missing.add(column.getColumnPath()); } else if (property == null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java index 8abebf6167b7..51e249bb5cfc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java @@ -14,6 +14,7 @@ package org.openmetadata.service.ontology; import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyRecordMapping.conflict; import java.util.HashSet; import java.util.List; @@ -122,9 +123,7 @@ private OntologyVersion draft(final Access access, final EntityReference ontolog private OntologyTableMapping mapped( final Access access, final UUID ontologyId, final OntologyVersion version) { - final Set candidates = version.boundClassIds(store, ontologyId); - final List rows = - mapping.between(candidates, CHANGED, revisions -> store.allTableRows(candidates)); + final List rows = rows(version, ontologyId); final TableViews tables = catalog.tableViews(access, tableIds(rows)); final Set bound = rows.stream() @@ -152,6 +151,22 @@ private OntologyTableMapping mapped( parents(version, ontologyId, classes, properties))); } + /** + * The table rows of the classes that bind tables. A class set that moves while the rows are read + * is read again, as a binding revision that moves is, so the rows and the set are one state. + */ + private List rows(final OntologyVersion version, final UUID ontologyId) { + for (int attempt = 0; attempt < OntologyMappingReader.BINDING_READ_ATTEMPTS; attempt++) { + final Set candidates = version.boundClassIds(store, ontologyId); + final List rows = + mapping.between(candidates, CHANGED, revisions -> store.allTableRows(candidates)); + if (version.fixedClassSet() || candidates.equals(version.boundClassIds(store, ontologyId))) { + return rows; + } + } + throw conflict(CHANGED); + } + /** The tables that the rows bind and that their columns join. */ private static Set tableIds(final List rows) { final Set ids = new HashSet<>(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java index f4e4984671ce..65e562f502f8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -138,6 +138,9 @@ Set withSubclassAmong( */ Set boundClassIds(OntologyConceptBindingStore store, UUID ontologyId); + /** Whether {@link #boundClassIds} always answers the same: true for a release, false for the draft. */ + boolean fixedClassSet(); + /** The classes among {@code ids} that this version declares, as it declares them. */ List classes( OntologyConceptBindingStore store, UUID ontologyId, Collection ids); @@ -174,6 +177,11 @@ static OntologyVersion draft(final CollectionDAO dao, final EntityReference onto /** The working draft, whose definitions are the working rows themselves. */ record Draft(long workingRevision) implements OntologyVersion { + @Override + public boolean fixedClassSet() { + return false; + } + @Override public OntologyStatementVersionRead read() { return new OntologyStatementVersionRead() @@ -310,6 +318,11 @@ public Set withSubclassAmong( /** A sealed release, whose members are stored payloads that never change. */ record Release(CollectionDAO dao, OntologyRelease release, String ontologyName) implements OntologyVersion { + @Override + public boolean fixedClassSet() { + return true; + } + @Override public OntologyStatementVersionRead read() { return new OntologyStatementVersionRead() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedRowFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedRowFilter.java index bb38a6246675..a4e854c8d1f0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedRowFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedRowFilter.java @@ -13,6 +13,7 @@ package org.openmetadata.service.ontology.sql; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Objects; import org.openmetadata.schema.type.OntologyRowFilterOperator; @@ -37,14 +38,17 @@ public final class TypedRowFilter { } /** The path of the compared column. */ + @JsonProperty("column") public List column() { return column; } + @JsonProperty("operator") public OntologyRowFilterOperator operator() { return operator; } + @JsonProperty("values") public List values() { return values; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValue.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValue.java index 3416699ea206..e1dc7cdedb89 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValue.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValue.java @@ -13,6 +13,8 @@ package org.openmetadata.service.ontology.sql; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; import org.openmetadata.schema.type.ColumnDataType; @@ -33,11 +35,13 @@ public final class TypedValue { } /** The column's data type as the catalog records it. */ + @JsonProperty("type") public ColumnDataType type() { return type; } /** The value as its data type holds it. An engine family writes SQL from this and nothing else. */ + @JsonIgnore public ParsedValue parsed() { return parsed; } @@ -47,6 +51,7 @@ public ParsedValue parsed() { * a boolean as {@code true} or {@code false}. It can differ from the parsed value, as {@code -0} * differs from zero. */ + @JsonProperty("source") public String source() { return source; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java index 23ba39c67e51..0bd14c93eda6 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java @@ -370,6 +370,25 @@ private static List iris(final TableBinding bound) { return bound.dataColumns().stream().map(data -> data.propertyIri().toString()).toList(); } + @Test + void aHiddenPropertyBoundOnAViewableTableOfAHiddenClassIsCounted() { + final World world = new World(); + final OntologyProperty secret = world.hiddenProperty("secretValue"); + world.bind( + world.hiddenType("SecretKind"), + world.table("secret_rows", "id", "secret_val"), + OntologyBindingRole.IDENTITY, + "id", + column(secret, "secret_val")); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(List.of(), mapping.classes()); + assertEquals(0, mapping.hiddenTables()); + assertEquals(1, mapping.hiddenClasses()); + assertEquals(1, mapping.hiddenProperties()); + } + @Test void aPropertyOfAHiddenTableIsNotCounted() { final World world = new World(); @@ -497,6 +516,10 @@ void aFilterThatStillAppliesIsParsedAndABindingWithNoFilterHasNone() { assertEquals(OntologyRowFilterOperator.GREATER_THAN, applies.filter().operator()); assertEquals(1, applies.filter().values().size()); assertNull(tables.get(1).rowFilter()); + assertEquals( + "{\"filter\":{\"column\":[\"region\"],\"operator\":\"greaterThan\"," + + "\"values\":[{\"type\":\"INT\",\"source\":\"7\"}]}}", + JsonUtils.pojoToJson(tables.get(0).rowFilter())); } @Test From f1f372f2f66ee8b6395dbcf7d12a3055077ad037 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 12:56:47 -0800 Subject: [PATCH 185/203] Look up generated tests and the tasks that propose them by an indexed class column --- .../native/2.2.0/mysql/schemaChanges.sql | 75 ++++ .../native/2.2.0/postgres/schemaChanges.sql | 25 ++ ...ated-tests-and-their-tasks-use-an-index.md | 76 ++++ .../GeneratedLookupIndexMigrationIT.java | 331 ++++++++++++++++++ .../openmetadata/service/jdbi3/FeedDAOs.java | 31 +- .../service/jdbi3/TimeSeriesDAOs.java | 22 +- 6 files changed, 521 insertions(+), 39 deletions(-) create mode 100644 docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java diff --git a/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql index 6851cd73682e..f267c576434c 100644 --- a/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql @@ -56,3 +56,78 @@ CREATE TABLE IF NOT EXISTS ontology_declined_definition ( PRIMARY KEY (ontologyId, operationType, iriHash, payloadDigest), KEY ontology_declined_definition_listing_index (ontologyId, declinedAt) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- Generated tests and the suggestion tasks that propose a test case are looked up by the class +-- that generated them. The class is a stored column of its own, filled from the JSON of every +-- existing row, so each lookup reads an index instead of every row. +-- ADR:2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index +SET @test_case_generated_by_class_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'test_case' + AND column_name = 'generatedByClassId' + ), + 'SELECT 1', + 'ALTER TABLE test_case ADD COLUMN generatedByClassId VARCHAR(36) GENERATED ALWAYS AS (json_unquote(json_extract(`json`, _utf8mb4''$.generatedBy.class.id''))) STORED NULL' + ) +); +PREPARE test_case_generated_by_class_stmt FROM @test_case_generated_by_class_ddl; +EXECUTE test_case_generated_by_class_stmt; +DEALLOCATE PREPARE test_case_generated_by_class_stmt; + +SET @test_case_generated_by_class_idx_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'test_case' + AND index_name = 'idx_test_case_generated_by_class' + ), + 'SELECT 1', + 'ALTER TABLE test_case ADD KEY idx_test_case_generated_by_class (generatedByClassId)' + ) +); +PREPARE test_case_generated_by_class_idx_stmt FROM @test_case_generated_by_class_idx_ddl; +EXECUTE test_case_generated_by_class_idx_stmt; +DEALLOCATE PREPARE test_case_generated_by_class_idx_stmt; + +-- A task that proposes a test case carries a test case proposal, written as JSON text, in its +-- payload. The column holds the class that generated the proposal, and stays NULL for every other +-- task and for a payload that is not JSON. +SET @task_entity_test_case_class_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'task_entity' + AND column_name = 'testCaseClassId' + ), + 'SELECT 1', + 'ALTER TABLE task_entity ADD COLUMN testCaseClassId VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestionType'')) = ''TestCase'' AND json_valid(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue''))) THEN json_unquote(json_extract(CAST(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue'')) AS JSON), _utf8mb4''$.generatedBy.class.id'')) END) STORED NULL' + ) +); +PREPARE task_entity_test_case_class_stmt FROM @task_entity_test_case_class_ddl; +EXECUTE task_entity_test_case_class_stmt; +DEALLOCATE PREPARE task_entity_test_case_class_stmt; + +SET @task_entity_test_case_class_idx_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'task_entity' + AND index_name = 'idx_task_test_case_class' + ), + 'SELECT 1', + 'ALTER TABLE task_entity ADD KEY idx_task_test_case_class (testCaseClassId)' + ) +); +PREPARE task_entity_test_case_class_idx_stmt FROM @task_entity_test_case_class_idx_ddl; +EXECUTE task_entity_test_case_class_idx_stmt; +DEALLOCATE PREPARE task_entity_test_case_class_idx_stmt; diff --git a/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql index 639fb9132a7f..a2e30d2ab84e 100644 --- a/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql @@ -46,3 +46,28 @@ CREATE TABLE IF NOT EXISTS ontology_declined_definition ( CREATE INDEX IF NOT EXISTS ontology_declined_definition_listing_index ON ontology_declined_definition (ontologyId, declinedAt); + +-- Generated tests and the suggestion tasks that propose a test case are looked up by the class +-- that generated them. The class is a stored column of its own, filled from the JSON of every +-- existing row, so each lookup reads an index instead of every row. +-- ADR:2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index +ALTER TABLE test_case + ADD COLUMN IF NOT EXISTS generatedbyclassid VARCHAR(36) + GENERATED ALWAYS AS (json -> 'generatedBy' -> 'class' ->> 'id') STORED; + +CREATE INDEX IF NOT EXISTS idx_test_case_generated_by_class + ON test_case (generatedbyclassid) WHERE generatedbyclassid IS NOT NULL; + +-- A task that proposes a test case carries a test case proposal, written as JSON text, in its +-- payload. The column holds the class that generated the proposal, and stays NULL for every other +-- task. +ALTER TABLE task_entity + ADD COLUMN IF NOT EXISTS testcaseclassid VARCHAR(36) + GENERATED ALWAYS AS ( + CASE WHEN json -> 'payload' ->> 'suggestionType' = 'TestCase' + THEN ((json -> 'payload' ->> 'suggestedValue')::jsonb -> 'generatedBy' -> 'class' ->> 'id') + END + ) STORED; + +CREATE INDEX IF NOT EXISTS idx_task_test_case_class + ON task_entity (testcaseclassid) WHERE testcaseclassid IS NOT NULL; diff --git a/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md b/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md new file mode 100644 index 000000000000..fac3344b3809 --- /dev/null +++ b/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md @@ -0,0 +1,76 @@ +# The lookups of generated tests and of the tasks that propose them read an index on the generating class + +- **Status:** Accepted +- **Revisions:** v1 2026-12-05 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `GeneratedLookupIndexMigrationIT` +- **Related:** ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test (the generated tests, their suggestion tasks and the reconcile that reads both) + +## Context + +A test case that a shape check generated carries `generatedBy`, and the task that proposes one is a +suggestion task whose payload holds a test case proposal as JSON text. Four statements look them up: + +| Statement | Where | Filter before | +|---|---|---| +| Generated tests of one class | `TimeSeriesDAOs.TestCaseDAO.findGeneratedIdsOfClass` | `generatedBy.class.id` read inside the JSON | +| All generated tests | `TimeSeriesDAOs.TestCaseDAO.findGeneratedIds` | `generatedBy` present in the JSON | +| All test case tasks | `FeedDAOs.TaskDAO.findTestCaseSuggestionIds` | `payload.suggestionType` read inside the JSON | +| Test case tasks of one class | `FeedDAOs.TaskDAO.findTestCaseSuggestionIdsOfClass` | `payload.suggestionType` read inside the JSON, and the value `LIKE '%%'` | + +None of these filters is a column, so each statement read every row of `test_case` or +`task_entity`. The reconcile runs the first two kinds once per run, and every read of the proposal +state of a check runs the per-class ones, so each pays a full scan of two tables that grow with the +whole deployment. + +The per-class task statement was also wider than its name. A task of class A whose proposal lists +class B as a concept it read matched the `LIKE` for B. Its caller keeps only the tasks whose +generating class is B, so the extra rows were read and dropped. + +## Decision + +**The class that generated a row is a stored column of its own, with an index.** Both engines, in +the 2.2.0 migration: + +- `test_case.generatedByClassId` is `generatedBy.class.id`. It is NULL for every test case that no + shape generated. +- `task_entity.testCaseClassId` is `generatedBy.class.id` of the proposal in the payload, when the + payload's `suggestionType` is `TestCase`. It is NULL for every other task. MySQL also leaves it + NULL when the value is not JSON; PostgreSQL has no way to test that in a generated expression, so + it relies on the API, which refuses a test case suggestion that is not a valid proposal. +- `idx_test_case_generated_by_class` and `idx_task_test_case_class` index them. PostgreSQL's are + partial (`WHERE ... IS NOT NULL`), because all but a few hundred rows are NULL; MySQL has no + partial index. + +Each statement now filters on its column: `= :classId`, or `IS NOT NULL` for the two that list all. +Each column is added only if absent, so the migration is safe to run twice. A stored generated +column fills itself from the JSON of every existing row when it is added, so no data step is needed. + +**The per-class task statement returns the tasks whose proposal was generated by the class**, no +longer every `TestCase` task whose value mentions it. Every caller already kept only those, so what +a reconcile or a read of proposal states returns does not change. + +## Measurements + +50,000 test cases and 50,000 tasks, 300 of each generated by 30 classes (10 per class). MySQL 8.4.13 +(`EXPLAIN ANALYZE` and `Handler_read_*` of one session) and PostgreSQL 15 (`EXPLAIN (ANALYZE, +BUFFERS)`), after `ANALYZE`. + +| Statement | Answer | MySQL rows read before / after | PostgreSQL buffers before / after | +|---|---|---|---| +| Tests of one class | 10 | 50,001 / 11 | 8,334 / 11 | +| All generated tests | 300 | 50,001 / 301 | 8,334 / 299 | +| All test case tasks | 300 | 50,001 / 301 | 7,143 / 299 | +| Tasks of one class | 10 (18 before) | 50,001 / 11 | 7,143 / 11 | + +Before, MySQL took a table scan and PostgreSQL a sequential scan on every statement. After, MySQL +takes an index lookup or index range scan, and PostgreSQL a bitmap scan of the index. Adding the two +columns and their indexes to the 50,000-row tables took 3.9 s on MySQL and 1.2 s on PostgreSQL. + +## Consequences + +- A lookup reads rows in proportion to its answer, on both engines. +- Each of the two tables gains one stored column and one index. Adding a stored column rewrites the + table once, at the upgrade. +- A new lookup of generated tests or of their tasks filters on these columns. The test fails when a + statement goes back to reading the JSON, because it counts the rows the database reads. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java new file mode 100644 index 000000000000..355c13313e97 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java @@ -0,0 +1,331 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.MetricMigrationSqlFixture.currentConnectionType; +import static org.openmetadata.it.tests.MetricMigrationSqlFixture.readMigrationScripts; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.statement.PreparedBatch; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.FeedDAOs; +import org.openmetadata.service.jdbi3.TimeSeriesDAOs; +import org.openmetadata.service.jdbi3.locator.ConnectionType; + +/** + * Runs the 2.2.0 statements that add the class columns of generated test cases and of the tasks + * that propose one, on tables that already hold 20,000 rows each, then reads each of the four + * lookups and counts the rows the database reads for it. Drops the columns first, so the rows are + * the ones a database written before the migration holds, and restores them at the end. + */ +@Isolated("drops and adds the lookup columns of two tables that every test shares") +class GeneratedLookupIndexMigrationIT { + private static final int ROWS = 20_000; + private static final int CLASSES = 20; + private static final int GENERATED_PER_CLASS = 10; + private static final String PREFIX = "gli-"; + private static final String MARKER = "generatedbyclassid"; + private static final String TEST_CASE = "test_case"; + private static final String TASK = "task_entity"; + + @Test + void eachLookupReadsRowsInProportionToItsAnswerOnceTheMigrationRanOverExistingRows() + throws Exception { + final ConnectionType engine = currentConnectionType(); + final List migration = lookupMigration(engine); + final Jdbi jdbi = TestSuiteBootstrap.getJdbi(); + final List classes = classIds(); + final AtomicReference planted = new AtomicReference<>(); + try { + jdbi.useHandle(handle -> dropLookupColumns(handle, engine)); + jdbi.useHandle(handle -> planted.set(insertRows(handle, engine, classes))); + jdbi.useHandle(handle -> migration.forEach(handle::execute)); + jdbi.useHandle(handle -> migration.forEach(handle::execute)); + jdbi.useHandle(handle -> analyze(handle, engine)); + + assertAllLookups(jdbi, engine, planted.get(), classes.get(3)); + } finally { + jdbi.useHandle(handle -> deleteRows(handle)); + jdbi.useHandle(handle -> migration.forEach(handle::execute)); + } + } + + private static void assertAllLookups( + final Jdbi jdbi, final ConnectionType engine, final Planted planted, final String clazz) { + final Read testsOfClass = + measure(jdbi, engine, TEST_CASE, h -> testDao(h).findGeneratedIdsOfClass(clazz)); + assertEquals(planted.tests().get(clazz), Set.copyOf(testsOfClass.ids()), "tests of one class"); + assertBounded(testsOfClass, "generated tests of one class"); + + final Read allTests = measure(jdbi, engine, TEST_CASE, h -> testDao(h).findGeneratedIds()); + assertTrue(allTests.ids().containsAll(union(planted.tests())), "every generated test"); + assertBounded(allTests, "all generated tests"); + + final Read tasksOfClass = + measure(jdbi, engine, TASK, h -> taskDao(h).findTestCaseSuggestionIdsOfClass(clazz)); + assertEquals(planted.tasks().get(clazz), Set.copyOf(tasksOfClass.ids()), "tasks of one class"); + assertBounded(tasksOfClass, "tasks of one class"); + + final Read allTasks = measure(jdbi, engine, TASK, h -> taskDao(h).findTestCaseSuggestionIds()); + assertTrue(allTasks.ids().containsAll(union(planted.tasks())), "every test case task"); + assertTrue( + Collections.disjoint(allTasks.ids(), planted.imitators()), + "a task that proposes a description is not a test case task"); + assertBounded(allTasks, "all test case tasks"); + } + + private static Set union(final Map> byClass) { + final Set all = new HashSet<>(); + byClass.values().forEach(all::addAll); + return all; + } + + private static void assertBounded(final Read read, final String what) { + assertEquals(0, read.scans(), what + " scans the table"); + assertTrue( + read.rowsRead() <= 2L * read.ids().size() + 10, + what + " read " + read.rowsRead() + " rows for " + read.ids().size() + " answers"); + } + + private static TimeSeriesDAOs.TestCaseDAO testDao(final Handle handle) { + return handle.attach(TimeSeriesDAOs.TestCaseDAO.class); + } + + private static FeedDAOs.TaskDAO taskDao(final Handle handle) { + return handle.attach(FeedDAOs.TaskDAO.class); + } + + // ---- what the database counted -------------------------------------------------------------- + + private record Read(List ids, long rowsRead, long scans) {} + + private static Read measure( + final Jdbi jdbi, + final ConnectionType engine, + final String table, + final Function> lookup) { + return jdbi.inTransaction( + handle -> { + final long[] before = counters(handle, engine, table); + final List ids = lookup.apply(handle); + final long[] after = counters(handle, engine, table); + return new Read(ids, after[0] - before[0], after[1] - before[1]); + }); + } + + /** Rows read so far in this transaction or session, and the table scans among them. */ + private static long[] counters( + final Handle handle, final ConnectionType engine, final String table) { + return engine == ConnectionType.MYSQL ? mysqlCounters(handle) : postgresCounters(handle, table); + } + + private static long[] mysqlCounters(final Handle handle) { + final Map status = new HashMap<>(); + handle + .createQuery("SHOW SESSION STATUS LIKE 'Handler_read%'") + .map((rs, ctx) -> Map.entry(rs.getString(1), rs.getLong(2))) + .forEach(entry -> status.put(entry.getKey(), entry.getValue())); + final long scans = status.get("Handler_read_rnd_next"); + final long indexed = status.get("Handler_read_next") + status.get("Handler_read_key"); + return new long[] {scans + indexed + status.get("Handler_read_rnd"), scans}; + } + + private static long[] postgresCounters(final Handle handle, final String table) { + final long[] counted = + handle + .createQuery( + "SELECT seq_scan, seq_tup_read + idx_tup_fetch FROM pg_stat_xact_user_tables " + + "WHERE relname = :table") + .bind("table", table) + .map((rs, ctx) -> new long[] {rs.getLong(2), rs.getLong(1)}) + .findOne() + .orElse(new long[] {0, 0}); + return counted; + } + + // ---- the migration and the rows it runs over ------------------------------------------------ + + /** The statements of the 2.2.0 file from the first one that names a lookup column to the end. */ + private static List lookupMigration(final ConnectionType engine) throws Exception { + final List all = readMigrationScripts(engine, "2.2.0").schemaStatements(); + int first = -1; + for (int index = 0; index < all.size() && first < 0; index++) { + if (all.get(index).toLowerCase(Locale.ROOT).contains(MARKER)) { + first = index; + } + } + assertTrue(first >= 0, "no 2.2.0 statement adds the generated test class column"); + return all.subList(first, all.size()); + } + + private static void dropLookupColumns(final Handle handle, final ConnectionType engine) { + if (engine == ConnectionType.MYSQL) { + handle.execute( + "ALTER TABLE test_case DROP INDEX idx_test_case_generated_by_class, " + + "DROP COLUMN generatedByClassId"); + handle.execute( + "ALTER TABLE task_entity DROP INDEX idx_task_test_case_class, " + + "DROP COLUMN testCaseClassId"); + } else { + handle.execute("DROP INDEX IF EXISTS idx_test_case_generated_by_class"); + handle.execute("ALTER TABLE test_case DROP COLUMN IF EXISTS generatedbyclassid"); + handle.execute("DROP INDEX IF EXISTS idx_task_test_case_class"); + handle.execute("ALTER TABLE task_entity DROP COLUMN IF EXISTS testcaseclassid"); + } + } + + private static void analyze(final Handle handle, final ConnectionType engine) { + if (engine == ConnectionType.MYSQL) { + handle.createQuery("ANALYZE TABLE test_case, task_entity").mapToMap().list(); + } else { + handle.execute("ANALYZE test_case"); + handle.execute("ANALYZE task_entity"); + } + } + + private static void deleteRows(final Handle handle) { + handle.execute("DELETE FROM test_case WHERE fqnHash LIKE '" + PREFIX + "%'"); + handle.execute("DELETE FROM task_entity WHERE fqnHash LIKE '" + PREFIX + "%'"); + } + + private static List classIds() { + final List classes = new ArrayList<>(); + for (int index = 0; index < CLASSES; index++) { + classes.add(UUID.randomUUID().toString()); + } + return classes; + } + + /** + * Fills each table with {@link #ROWS} rows. Of the test cases, {@link #GENERATED_PER_CLASS} per + * class carry a generating class. Of the tasks, the same number per class propose a test case, + * and as many more propose another change with the same JSON in their value, which no lookup may + * return. + */ + private static Planted insertRows( + final Handle handle, final ConnectionType engine, final List classes) { + final String cast = engine == ConnectionType.MYSQL ? ":json" : "CAST(:json AS jsonb)"; + final PreparedBatch tests = + handle.prepareBatch( + "INSERT INTO test_case (json, fqnHash) VALUES (" + cast + ", :fqnHash)"); + final PreparedBatch tasks = + handle.prepareBatch( + "INSERT INTO task_entity (id, json, fqnHash) VALUES (:id, " + cast + ", :fqnHash)"); + final Planted planted = new Planted(new HashMap<>(), new HashMap<>(), new HashSet<>()); + for (int index = 0; index < ROWS; index++) { + final String clazz = classes.get(index % CLASSES); + final boolean generates = index < CLASSES * GENERATED_PER_CLASS; + final String testId = UUID.randomUUID().toString(); + tests + .bind("json", testCaseJson(testId, index, generates ? clazz : null)) + .bind("fqnHash", PREFIX + "t" + index) + .add(); + final String taskId = UUID.randomUUID().toString(); + tasks + .bind("id", taskId) + .bind("json", taskJson(taskId, index, clazz)) + .bind("fqnHash", PREFIX + "k" + index) + .add(); + planted.note(index, clazz, testId, taskId); + } + tests.execute(); + tasks.execute(); + return planted; + } + + /** The ids this test wrote, by the class they name. */ + private record Planted( + Map> tests, Map> tasks, Set imitators) { + void note(final int index, final String clazz, final String testId, final String taskId) { + final int span = CLASSES * GENERATED_PER_CLASS; + if (index < span) { + tests.computeIfAbsent(clazz, key -> new HashSet<>()).add(testId); + tasks.computeIfAbsent(clazz, key -> new HashSet<>()).add(taskId); + } else if (index < 2 * span) { + imitators.add(taskId); + } + } + } + + private static String testCaseJson(final String id, final int index, final String clazz) { + final Map test = new LinkedHashMap<>(); + test.put("id", id); + test.put("name", PREFIX + "t" + index); + test.put("entityLink", "<#E::table::gli.db.schema.t" + index + ">"); + test.put("entityFQN", "gli.db.schema.t" + index); + test.put("updatedAt", 1L); + test.put("updatedBy", "admin"); + test.put("deleted", false); + if (clazz != null) { + test.put("generatedBy", Map.of("identity", "i" + index, "class", Map.of("id", clazz))); + } + return JsonUtils.pojoToJson(test); + } + + /** + * Tasks 0 to 199 propose a test case, 200 to 399 propose a description whose value reads like a + * test case proposal of the same class, the rest propose a description. + */ + private static String taskJson(final String id, final int index, final String clazz) { + final int span = CLASSES * GENERATED_PER_CLASS; + final boolean proposes = index < span; + final boolean imitates = index >= span && index < 2 * span; + final String value = + proposes || imitates + ? JsonUtils.pojoToJson( + Map.of( + "generatedBy", + Map.of("identity", "i" + index, "class", Map.of("id", clazz)), + "testCase", + Map.of("name", "n" + index))) + : "a description " + index; + final Map task = new LinkedHashMap<>(); + task.put("id", id); + task.put("taskId", "GLI-" + index); + task.put("name", PREFIX + "k" + index); + task.put("category", "MetadataUpdate"); + task.put("type", "Suggestion"); + task.put("status", "Open"); + task.put("createdAt", 1L); + task.put("updatedAt", 1L); + task.put( + "payload", + Map.of( + "suggestionType", + proposes ? "TestCase" : "Description", + "fieldPath", + proposes ? "testCases" : "description", + "suggestedValue", + value)); + return JsonUtils.pojoToJson(task); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java index 0fbf2480d1c6..f8df5ba93321 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java @@ -144,31 +144,16 @@ default void insert(org.openmetadata.schema.EntityInterface entity, String fq insertTask(task.getId().toString(), JsonUtils.pojoToJson(task), task.getFullyQualifiedName()); } - /** The ids of the suggestion tasks that propose a test case, closed ones included. */ - @ConnectionAwareSqlQuery( - value = - "SELECT id FROM task_entity WHERE " - + "JSON_UNQUOTE(JSON_EXTRACT(json, '$.payload.suggestionType')) = 'TestCase'", - connectionType = MYSQL) - @ConnectionAwareSqlQuery( - value = - "SELECT id FROM task_entity WHERE json -> 'payload' ->> 'suggestionType' = 'TestCase'", - connectionType = POSTGRES) + /** + * The ids of the suggestion tasks that propose a test case, closed ones included. Reads the + * index on {@code testCaseClassId}, which is the class named by the proposal and is empty for + * every other task. + */ + @SqlQuery("SELECT id FROM task_entity WHERE testCaseClassId IS NOT NULL") List findTestCaseSuggestionIds(); - /** The ids of the suggestion tasks that propose a test case and name the class. */ - @ConnectionAwareSqlQuery( - value = - "SELECT id FROM task_entity WHERE " - + "JSON_UNQUOTE(JSON_EXTRACT(json, '$.payload.suggestionType')) = 'TestCase' " - + "AND JSON_UNQUOTE(JSON_EXTRACT(json, '$.payload.suggestedValue')) " - + "LIKE CONCAT('%', :classId, '%')", - connectionType = MYSQL) - @ConnectionAwareSqlQuery( - value = - "SELECT id FROM task_entity WHERE json -> 'payload' ->> 'suggestionType' = 'TestCase' " - + "AND json -> 'payload' ->> 'suggestedValue' LIKE '%' || :classId || '%'", - connectionType = POSTGRES) + /** The ids of the suggestion tasks that propose a test case generated for the class. */ + @SqlQuery("SELECT id FROM task_entity WHERE testCaseClassId = :classId") List findTestCaseSuggestionIdsOfClass(@Bind("classId") String classId); @ConnectionAwareSqlUpdate( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java index 18aaf92d4ee9..e824f0272d32 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java @@ -840,25 +840,15 @@ int countOfTestCases( List findIdsByEntityFQN( @Bind("entityFQN") String entityFQN, @Bind("entityFQNPrefix") String entityFQNPrefix); - /** The ids of the test cases that a shape generated, deleted ones included. */ - @ConnectionAwareSqlQuery( - value = "SELECT id FROM test_case WHERE JSON_EXTRACT(json, '$.generatedBy') IS NOT NULL", - connectionType = MYSQL) - @ConnectionAwareSqlQuery( - value = "SELECT id FROM test_case WHERE json -> 'generatedBy' IS NOT NULL", - connectionType = POSTGRES) + /** + * The ids of the test cases that a shape generated, deleted ones included. Reads the index on + * {@code generatedByClassId}, the class that generated the test, which no other test case has. + */ + @SqlQuery("SELECT id FROM test_case WHERE generatedByClassId IS NOT NULL") List findGeneratedIds(); /** The ids of the test cases that a shape generated for one class, deleted ones included. */ - @ConnectionAwareSqlQuery( - value = - "SELECT id FROM test_case WHERE " - + "JSON_UNQUOTE(JSON_EXTRACT(json, '$.generatedBy.class.id')) = :classId", - connectionType = MYSQL) - @ConnectionAwareSqlQuery( - value = - "SELECT id FROM test_case WHERE json -> 'generatedBy' -> 'class' ->> 'id' = :classId", - connectionType = POSTGRES) + @SqlQuery("SELECT id FROM test_case WHERE generatedByClassId = :classId") List findGeneratedIdsOfClass(@Bind("classId") String classId); class TestCaseRecord { From 391bbbae3a145e2b8082895d87413214e8fb97bb Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 13:57:38 -0800 Subject: [PATCH 186/203] ontology: a declined table binding and shape are remembered by content --- ...ned-definition-is-remembered-by-content.md | 16 +- .../tests/OntologyDeclinedBindingShapeIT.java | 175 ++++++++++++++++++ .../ontology/OntologyDeclinedDefinitions.java | 32 ++++ .../ontology/OntologyDefinitionDigest.java | 29 +++ .../OntologyDeclinedBindingShapeKeysTest.java | 168 +++++++++++++++++ 5 files changed, 418 insertions(+), 2 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java diff --git a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md index 0b05faaf304d..73c027af1d39 100644 --- a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md +++ b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md @@ -1,11 +1,12 @@ # A declined definition is remembered by its content, and narrowing a draft keeps its classes - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-26 (canonical form stated in full and made stable for set order, empty lists and server-derived fields; narrowing checks every kept operation; a permanent delete removes the rows; declining asks the draft read right) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-26 (canonical form stated in full and made stable for set order, empty lists and server-derived fields; narrowing checks every kept operation; a permanent delete removes the rows; declining asks the draft read right); v3 2026-12-05 (a table binding and a shape can be declined) - **Deciders:** Ontology maintainers - **Guard:** `OntologyDefinitionDigestTest`, `OntologyDeclinedDefinitionsTest`, `OntologyDeclinedDefinitionDaoTest`, `OntologyDraftNarrowingTest`, - `OntologyDeclinedDefinitionRightsTest`, `OntologyDeclinedDefinitionIT`, + `OntologyDeclinedDefinitionRightsTest`, `OntologyDeclinedBindingShapeKeysTest`, + `OntologyDeclinedDefinitionIT`, `OntologyDeclinedBindingShapeIT`, `OntologyDeclinedDefinitionReadIT` and `OntologyRolesMigrationIT` - **Related:** ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights @@ -72,6 +73,17 @@ any other field gets a new digest, so it no longer matches and is proposed again so it uses its `subjectIri`, and several axioms of one subject differ by digest. An operation that carries no definition, such as a delete, cannot be declined. +**A table binding and a shape.** An `UPSERT_BINDING` operation stands under the binding's class +IRI, and an `UPSERT_SHAPE` operation under the shape's `targetConcept`. A binding's digest is the +SHA-256 of the canonical JSON of the binding without its `classIri`: its table, role, `subjectKey`, +row filter and columns, each column with its property IRI, column path and join. The steps 1, 4, 6 +and 7 above apply. Keys are sorted, and the columns and the column pairs of a join are sets, sorted +by the text of each element. The `subjectKey` keeps its order, because a contributing table pairs +its key with the identity table's by position. A shape's digest is the SHA-256 of the canonical +JSON of its constraints alone, in authored order, so a fresh id, name or description does not +change it and another constraint does. A changed binding or shape does not match. The digests of +the test fixtures are pinned in `OntologyDeclinedBindingShapeKeysTest`. + **Endpoints**, under `/v1/ontologies/{id}/declinedDefinitions`: - `POST` declines operations of one change set, named by change set id and operation ids, with an diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java new file mode 100644 index 000000000000..fe2e409fdacf --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java @@ -0,0 +1,175 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedDataProperty; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedShape; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.net.URI; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.DeclineOntologyDefinitions; +import org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyDeclinedDefinition; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatch; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; + +/** + * Declining a table binding and a shape of a draft, and matching later drafts against them. The + * same binding and shape under fresh ids match, and one that changed does not. + */ +@Execution(ExecutionMode.SAME_THREAD) +@ExtendWith(TestNamespaceExtension.class) +public class OntologyDeclinedBindingShapeIT extends BaseOntologyApprovalIT { + private static final URI TOTAL = URI.create("urn:total"); + + @Test + void aDeclinedBindingAndShapeMatchUnderFreshIdsAndAChangedOneDoesNot(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final DatabaseSchema schema = schema(ns); + final Table orders = orders(schema, "orders"); + final Table archive = orders(schema, "orders_archive"); + final OntologyChangeOperation binding = binds(keyed(orders, "order_id")); + final OntologyChangeOperation shape = shape(ontology, 1); + final OntologyChangeSet proposal = proposal(ns, ontology, binding, shape); + + final OntologyDeclinedDefinitionPage declined = + admin() + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(proposal, binding, shape)); + + assertEquals( + List.of( + OntologyChangeOperationType.UPSERT_BINDING, OntologyChangeOperationType.UPSERT_SHAPE), + declined.getRecords().stream().map(OntologyDeclinedDefinition::getOperationType).toList()); + assertEquals( + List.of(ORDER, ORDER), + declined.getRecords().stream().map(OntologyDeclinedDefinition::getIri).toList()); + final List matches = + match( + ontology, + binds(keyed(orders, "order_id")), + shape(ontology, 1), + binds(keyed(archive, "order_id")), + binds(keyed(orders, "customer_id")), + shape(ontology, 2)) + .getMatches(); + assertEquals( + List.of(true, true, false, false, false), + matches.stream().map(OntologyDeclinedDefinitionMatch::getDeclined).toList()); + assertEquals(binding.getId(), matches.get(0).getRecord().getOperationId()); + assertEquals(shape.getId(), matches.get(1).getRecord().getOperationId()); + assertNotEquals(matches.get(0).getPayloadDigest(), matches.get(2).getPayloadDigest()); + assertNull(matches.get(4).getRecord()); + } + + @Test + void decliningABindingTwiceKeepsOneRecord(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns), "orders"); + final OntologyChangeOperation binding = binds(keyed(orders, "order_id")); + final OntologyChangeSet proposal = proposal(ns, ontology, binding); + + admin().ontologyDeclinedDefinitions().decline(ontology.getId(), decline(proposal, binding)); + admin().ontologyDeclinedDefinitions().decline(ontology.getId(), decline(proposal, binding)); + + assertEquals( + 1, + admin() + .ontologyDeclinedDefinitions() + .list(ontology.getId(), null, null) + .getRecords() + .size()); + } + + private static OntologyChangeSet proposal( + final TestNamespace ns, final Ontology ontology, final OntologyChangeOperation... held) { + final var total = proposedDataProperty(ontology, "total", TOTAL, ORDER); + final OntologyChangeOperation[] operations = new OntologyChangeOperation[held.length + 1]; + operations[0] = creates(total); + System.arraycopy(held, 0, operations, 1, held.length); + return draft(admin(), ns, ontology, operations); + } + + private static OntologyChangeOperation shape(final Ontology ontology, final int minCount) { + final var shape = proposedShape(ontology, "orderShape", ORDER, TOTAL); + shape.getConstraints().getFirst().setMinCount(minCount); + return creates(shape); + } + + private static OntologyBindingChange keyed(final Table table, final String key) { + return bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(key))); + } + + private static Table orders(final DatabaseSchema schema, final String name) { + return table( + schema, + name, + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + } + + private static DeclineOntologyDefinitions decline( + final OntologyChangeSet draft, final OntologyChangeOperation... operations) { + final LinkedHashSet ids = new LinkedHashSet<>(); + for (final OntologyChangeOperation operation : operations) { + ids.add(operation.getId()); + } + return new DeclineOntologyDefinitions() + .withChangeSetId(draft.getId()) + .withOperationIds(ids) + .withReason("wrong table"); + } + + private static org.openmetadata.schema.type.OntologyDeclinedDefinitionMatches match( + final Ontology ontology, final OntologyChangeOperation... candidates) { + return admin() + .ontologyDeclinedDefinitions() + .match( + ontology.getId(), + new MatchOntologyDeclinedDefinitions().withCandidates(List.of(candidates))); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitions.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitions.java index f01838e40535..7f2e9e314913 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitions.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitions.java @@ -36,6 +36,8 @@ import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyBindingChange; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.type.OntologyDeclinedDefinition; @@ -71,6 +73,14 @@ String iriHash() { /** The key of the definition the operation carries, or null when it carries none. */ static Key keyOf(final OntologyChangeOperation operation) { + return switch (operation.getOperationType()) { + case UPSERT_BINDING -> bindingKey(operation); + case UPSERT_SHAPE -> shapeKey(operation); + default -> definitionKey(operation); + }; + } + + private static Key definitionKey(final OntologyChangeOperation operation) { final OntologyDefinition definition = NativeOntologyChanges.definition(operation); final URI iri = iriOf(definition); return iri == null @@ -78,6 +88,28 @@ static Key keyOf(final OntologyChangeOperation operation) { : new Key(operation.getOperationType(), iri, OntologyDefinitionDigest.of(definition)); } + /** A binding stands under its class, and its digest covers the table, role, keys and columns. */ + private static Key bindingKey(final OntologyChangeOperation operation) { + final OntologyBindingChange binding = operation.getBinding(); + return binding == null || binding.getClassIri() == null + ? null + : new Key( + operation.getOperationType(), + binding.getClassIri(), + OntologyDefinitionDigest.ofBinding(binding)); + } + + /** A shape stands under its target class, and its digest covers its constraints. */ + private static Key shapeKey(final OntologyChangeOperation operation) { + final OntologyShape shape = operation.getShape(); + return shape == null || shape.getTargetConcept() == null + ? null + : new Key( + operation.getOperationType(), + shape.getTargetConcept(), + OntologyDefinitionDigest.ofShapeConstraints(shape)); + } + /** * An axiom has no IRI of its own, so its subject stands in. Several axioms of one subject differ * by digest. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java index 544cff70d03c..d3d454688094 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java @@ -32,6 +32,8 @@ import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyBindingChange; import org.openmetadata.schema.utils.JsonUtils; /** @@ -89,6 +91,33 @@ public static String of(final OntologyDefinition definition) { return DigestUtils.sha256Hex(canonicalJson(definition)); } + /** + * The digest of a table binding, without its class, which a record keeps as its IRI. The columns + * and the column pairs of each join are sets and sort by their text. The subject key keeps its + * order, because a contributing table pairs its key with the identity table's by position. + */ + public static String ofBinding(final OntologyBindingChange binding) { + final ObjectNode content = + JsonUtils.valueToTree( + JsonUtils.readValue(JsonUtils.pojoToJson(binding), OntologyBindingChange.class)) + .deepCopy(); + content.remove("classIri"); + final JsonNode canonical = OntologyJson.canonical(withoutEmpty(content)); + sortAsSet(canonical, "columns"); + canonical.path("columns").forEach(column -> sortAsSet(column.path("join"), "on")); + return DigestUtils.sha256Hex(canonical.toString()); + } + + /** The digest of a shape's constraints, in the order they were authored. */ + public static String ofShapeConstraints(final OntologyShape shape) { + final JsonNode tree = + JsonUtils.valueToTree( + JsonUtils.readValue(JsonUtils.pojoToJson(shape), OntologyShape.class)); + final ObjectNode content = JsonUtils.getObjectNode(); + content.set("constraints", tree.path("constraints").deepCopy()); + return DigestUtils.sha256Hex(OntologyJson.canonical(withoutEmpty(content)).toString()); + } + static String canonicalJson(final OntologyDefinition definition) { final JsonNode tree = JsonUtils.valueToTree( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java new file mode 100644 index 000000000000..d2344a991857 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java @@ -0,0 +1,168 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; + +class OntologyDeclinedBindingShapeKeysTest { + private static final URI ORDER = URI.create("https://example.org/sales/Order"); + private static final URI TOTAL = URI.create("https://example.org/sales/total"); + private static final URI PLACED_BY = URI.create("https://example.org/sales/placedBy"); + private static final UUID ORDERS = UUID.fromString("00000000-0000-0000-0000-0000000000c1"); + private static final UUID ARCHIVE = UUID.fromString("00000000-0000-0000-0000-0000000000c2"); + private static final UUID CUSTOMERS = UUID.fromString("00000000-0000-0000-0000-0000000000c3"); + + @Test + void aBindingStandsUnderItsClassAndTheSameBindingGivesTheSameKey() { + final OntologyDeclinedDefinitions.Key key = OntologyDeclinedDefinitions.keyOf(bind(binding())); + + assertEquals(OntologyChangeOperationType.UPSERT_BINDING, key.type()); + assertEquals(ORDER, key.iri()); + assertEquals( + "3993fb92667097975f2d0bf71b5f1d64deb049cd20614bd7590571b0b90cee03", key.payloadDigest()); + assertEquals(key, OntologyDeclinedDefinitions.keyOf(bind(binding()))); + } + + @Test + void theOrderOfColumnsAndOfJoinPairsDoesNotChangeTheKey() { + final OntologyChangeOperation forward = bind(binding()); + final OntologyChangeOperation reversed = + bind( + binding() + .withColumns( + List.of( + column(PLACED_BY, "customer_id").withJoin(join(true)), + column(TOTAL, "total")))); + + assertEquals( + OntologyDeclinedDefinitions.keyOf(forward), OntologyDeclinedDefinitions.keyOf(reversed)); + } + + @Test + void anotherTableKeyRoleFilterOrColumnGivesAnotherKey() { + final String base = digest(bind(binding())); + + assertNotEquals(base, digest(bind(binding().withTableId(ARCHIVE)))); + assertNotEquals(base, digest(bind(binding().withSubjectKey(List.of(List.of("customer_id")))))); + assertNotEquals(base, digest(bind(binding().withRole(OntologyBindingRole.CONTRIBUTING)))); + assertNotEquals(base, digest(bind(binding().withColumns(List.of(column(TOTAL, "amount")))))); + } + + @Test + void aBindingWithoutAClassOrAPayloadHasNoKey() { + assertNull(OntologyDeclinedDefinitions.keyOf(bind(binding().withClassIri(null)))); + assertNull(OntologyDeclinedDefinitions.keyOf(bind(null))); + } + + @Test + void aShapeStandsUnderItsTargetAndTheSameConstraintsGiveTheSameKeyUnderFreshIds() { + final OntologyDeclinedDefinitions.Key key = OntologyDeclinedDefinitions.keyOf(shape(1)); + + assertEquals(OntologyChangeOperationType.UPSERT_SHAPE, key.type()); + assertEquals(ORDER, key.iri()); + assertEquals( + "af92f5f77002c55066295abe459c9a12c9a4541ba6dc491296552bd1c80c5a7e", key.payloadDigest()); + assertEquals(key, OntologyDeclinedDefinitions.keyOf(shape(1))); + } + + @Test + void anotherConstraintGivesAnotherShapeKey() { + assertNotEquals(digest(shape(1)), digest(shape(2))); + final OntologyChangeOperation otherPath = shape(1); + otherPath.getShape().getConstraints().getFirst().setPath(PLACED_BY); + assertNotEquals(digest(shape(1)), digest(otherPath)); + } + + @Test + void aShapeWithoutATargetHasNoKey() { + final OntologyChangeOperation untargeted = shape(1); + untargeted.getShape().setTargetConcept(null); + assertNull(OntologyDeclinedDefinitions.keyOf(untargeted)); + } + + private static String digest(final OntologyChangeOperation operation) { + return OntologyDeclinedDefinitions.keyOf(operation).payloadDigest(); + } + + private static OntologyChangeOperation bind(final OntologyBindingChange binding) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding(binding); + } + + private static OntologyBindingChange binding() { + return new OntologyBindingChange() + .withClassIri(ORDER) + .withTableId(ORDERS) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("order_id"))) + .withColumns( + List.of( + column(TOTAL, "total"), column(PLACED_BY, "customer_id").withJoin(join(false)))); + } + + private static OntologyColumnBindingChange column(final URI property, final String column) { + return new OntologyColumnBindingChange() + .withPropertyIri(property) + .withColumnPath(List.of(column)); + } + + private static OntologyJoinChange join(final boolean reversed) { + final List pairs = + List.of(pair("customer_id", "id"), pair("region", "region")); + return new OntologyJoinChange() + .withTargetAssetId(CUSTOMERS) + .withOn(reversed ? pairs.reversed() : pairs); + } + + private static OntologyJoinColumnPair pair(final String child, final String parent) { + return new OntologyJoinColumnPair().withChild(List.of(child)).withParent(List.of(parent)); + } + + private static OntologyChangeOperation shape(final int minCount) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_SHAPE) + .withShape( + new OntologyShape() + .withId(UUID.randomUUID()) + .withName("orderShape") + .withTargetConcept(ORDER) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("stated") + .withPath(TOTAL) + .withMinCount(minCount)))); + } +} From 8589497474bd76d92f1afdb13ef079591144dd40 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 14:08:29 -0800 Subject: [PATCH 187/203] Test that a generated column never fails a write or the migration --- .../GeneratedLookupIndexMigrationIT.java | 201 +++++++++++++++++- 1 file changed, 190 insertions(+), 11 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java index 355c13313e97..83365743089a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java @@ -65,16 +65,34 @@ void eachLookupReadsRowsInProportionToItsAnswerOnceTheMigrationRanOverExistingRo final Jdbi jdbi = TestSuiteBootstrap.getJdbi(); final List classes = classIds(); final AtomicReference planted = new AtomicReference<>(); + final String shapeClass = UUID.randomUUID().toString(); + final List shapes = shapes(shapeClass); + final List earlyTasks = new ArrayList<>(); + final List earlyTests = new ArrayList<>(); + final List lateTasks = new ArrayList<>(); + final List lateTests = new ArrayList<>(); try { jdbi.useHandle(handle -> dropLookupColumns(handle, engine)); jdbi.useHandle(handle -> planted.set(insertRows(handle, engine, classes))); + jdbi.useHandle( + handle -> insertShapesBeforeTheMigration(handle, engine, shapes, earlyTasks, earlyTests)); jdbi.useHandle(handle -> migration.forEach(handle::execute)); jdbi.useHandle(handle -> migration.forEach(handle::execute)); + jdbi.useHandle(handle -> insertShapesThroughTheDaos(handle, shapes, lateTasks, lateTests)); jdbi.useHandle(handle -> analyze(handle, engine)); assertAllLookups(jdbi, engine, planted.get(), classes.get(3)); + jdbi.useHandle( + handle -> { + assertShapeColumns( + handle, shapes, earlyTasks, earlyTests, "written before the migration"); + assertShapeColumns(handle, shapes, lateTasks, lateTests, "written through the DAOs"); + }); + assertShapeLookups( + jdbi, engine, shapes, shapeClass, earlyTasks, earlyTests, lateTasks, lateTests); } finally { - jdbi.useHandle(handle -> deleteRows(handle)); + jdbi.useHandle( + handle -> deleteRows(handle, allOf(earlyTasks, lateTasks), allOf(earlyTests, lateTests))); jdbi.useHandle(handle -> migration.forEach(handle::execute)); } } @@ -172,19 +190,177 @@ private static long[] postgresCounters(final Handle handle, final String table) return counted; } + // ---- rows a column cannot read --------------------------------------------------------------- + + /** A proposal or test case shape, and the class the columns must read from it, or null. */ + private record Shape(String name, String proposal, String testClass, String expected) {} + + private static List shapes(final String clazz) { + final String longId = "y".repeat(40); + return List.of( + new Shape("valid", proposalOf(clazz, "q"), clazz, clazz), + new Shape("nul-escape", proposalOf(clazz, "q\\u0000"), clazz, clazz), + new Shape("not-json", "this is not json", null, null), + new Shape("long-id", proposalOf(longId, "q"), longId, null)); + } + + private static String proposalOf(final String clazz, final String note) { + return "{\"note\":\"" + note + "\",\"generatedBy\":{\"class\":{\"id\":\"" + clazz + "\"}}}"; + } + + private static void insertShapesBeforeTheMigration( + final Handle handle, + final ConnectionType engine, + final List shapes, + final List taskIds, + final List testIds) { + final String cast = engine == ConnectionType.MYSQL ? ":json" : "CAST(:json AS jsonb)"; + for (final Shape shape : shapes) { + final String taskId = UUID.randomUUID().toString(); + handle + .createUpdate( + "INSERT INTO task_entity (id, json, fqnHash) VALUES (:id, " + cast + ", :hash)") + .bind("id", taskId) + .bind("json", shapeTaskJson(taskId, shape)) + .bind("hash", PREFIX + "early-k-" + shape.name()) + .execute(); + taskIds.add(taskId); + final String testId = UUID.randomUUID().toString(); + handle + .createUpdate("INSERT INTO test_case (json, fqnHash) VALUES (" + cast + ", :hash)") + .bind("json", shapeTestJson(testId, shape)) + .bind("hash", PREFIX + "early-t-" + shape.name()) + .execute(); + testIds.add(testId); + } + } + + private static void insertShapesThroughTheDaos( + final Handle handle, + final List shapes, + final List taskIds, + final List testIds) { + final FeedDAOs.TaskDAO tasks = taskDao(handle); + final TimeSeriesDAOs.TestCaseDAO tests = testDao(handle); + for (final Shape shape : shapes) { + final String taskId = UUID.randomUUID().toString(); + tasks.insert( + tasks.getTableName(), + tasks.getNameHashColumn(), + PREFIX + "late-k-" + shape.name(), + shapeTaskJson(taskId, shape)); + taskIds.add(taskId); + final String testId = UUID.randomUUID().toString(); + tests.insert( + tests.getTableName(), + tests.getNameHashColumn(), + PREFIX + "late-t-" + shape.name(), + shapeTestJson(testId, shape)); + testIds.add(testId); + } + } + + private static String shapeTaskJson(final String id, final Shape shape) { + final Map task = new LinkedHashMap<>(); + task.put("id", id); + task.put("taskId", "GLI-" + shape.name()); + task.put("name", PREFIX + "shape-" + shape.name()); + task.put("category", "MetadataUpdate"); + task.put("type", "Suggestion"); + task.put("status", "Open"); + task.put("createdAt", 1L); + task.put("updatedAt", 1L); + task.put( + "payload", + Map.of( + "suggestionType", "TestCase", + "fieldPath", "testCases", + "suggestedValue", shape.proposal())); + return JsonUtils.pojoToJson(task); + } + + private static String shapeTestJson(final String id, final Shape shape) { + return testCaseJson(id, 0, shape.testClass()) + .replace("gli.db.schema.t0", "gli.db.schema." + shape.name()); + } + + /** Reads the generated columns of the rows of each shape, which are in the order of the shapes. */ + private static void assertShapeColumns( + final Handle handle, + final List shapes, + final List taskIds, + final List testIds, + final String when) { + for (int index = 0; index < shapes.size(); index++) { + final Shape shape = shapes.get(index); + assertEquals( + shape.expected(), + column( + handle, "SELECT testCaseClassId FROM task_entity WHERE id = ?", taskIds.get(index)), + "task of shape " + shape.name() + " " + when); + assertEquals( + readableClass(shape.testClass()), + column( + handle, "SELECT generatedByClassId FROM test_case WHERE id = ?", testIds.get(index)), + "test case of shape " + shape.name() + " " + when); + } + } + + private static List allOf(final List first, final List second) { + final List both = new ArrayList<>(first); + both.addAll(second); + return both; + } + + private static String readableClass(final String clazz) { + return clazz != null && clazz.length() == 36 ? clazz : null; + } + + private static String column(final Handle handle, final String sql, final String id) { + return handle.createQuery(sql).bind(0, id).mapTo(String.class).one(); + } + + /** The lookups find the rows of the readable shapes, written either way, and read an index. */ + private static void assertShapeLookups( + final Jdbi jdbi, + final ConnectionType engine, + final List shapes, + final String clazz, + final List earlyTasks, + final List earlyTests, + final List lateTasks, + final List lateTests) { + final Set tasks = new HashSet<>(); + final Set tests = new HashSet<>(); + for (int index = 0; index < shapes.size(); index++) { + if (shapes.get(index).expected() != null) { + tasks.add(earlyTasks.get(index)); + tasks.add(lateTasks.get(index)); + } + if (readableClass(shapes.get(index).testClass()) != null) { + tests.add(earlyTests.get(index)); + tests.add(lateTests.get(index)); + } + } + final Read tasksOfClass = + measure(jdbi, engine, TASK, h -> taskDao(h).findTestCaseSuggestionIdsOfClass(clazz)); + assertEquals(tasks, Set.copyOf(tasksOfClass.ids()), "tasks of the class that shapes name"); + assertBounded(tasksOfClass, "tasks of the class that shapes name"); + final Read testsOfClass = + measure(jdbi, engine, TEST_CASE, h -> testDao(h).findGeneratedIdsOfClass(clazz)); + assertEquals(tests, Set.copyOf(testsOfClass.ids()), "tests of the class that shapes name"); + assertBounded(testsOfClass, "tests of the class that shapes name"); + } + // ---- the migration and the rows it runs over ------------------------------------------------ - /** The statements of the 2.2.0 file from the first one that names a lookup column to the end. */ + /** Every statement of the 2.2.0 file, as the migration runs them. */ private static List lookupMigration(final ConnectionType engine) throws Exception { final List all = readMigrationScripts(engine, "2.2.0").schemaStatements(); - int first = -1; - for (int index = 0; index < all.size() && first < 0; index++) { - if (all.get(index).toLowerCase(Locale.ROOT).contains(MARKER)) { - first = index; - } - } - assertTrue(first >= 0, "no 2.2.0 statement adds the generated test class column"); - return all.subList(first, all.size()); + assertTrue( + all.stream().anyMatch(sql -> sql.toLowerCase(Locale.ROOT).contains(MARKER)), + "no 2.2.0 statement adds the generated test class column"); + return all; } private static void dropLookupColumns(final Handle handle, final ConnectionType engine) { @@ -212,9 +388,12 @@ private static void analyze(final Handle handle, final ConnectionType engine) { } } - private static void deleteRows(final Handle handle) { + private static void deleteRows( + final Handle handle, final List taskIds, final List testIds) { handle.execute("DELETE FROM test_case WHERE fqnHash LIKE '" + PREFIX + "%'"); handle.execute("DELETE FROM task_entity WHERE fqnHash LIKE '" + PREFIX + "%'"); + taskIds.forEach(id -> handle.execute("DELETE FROM task_entity WHERE id = ?", id)); + testIds.forEach(id -> handle.execute("DELETE FROM test_case WHERE id = ?", id)); } private static List classIds() { From de4bc6ee4d1ebd46eb93395a0853970d2afc02d2 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 14:15:43 -0800 Subject: [PATCH 188/203] Make a generated lookup column NULL for a value it cannot read instead of failing the write --- .../native/2.2.0/mysql/schemaChanges.sql | 6 ++-- .../native/2.2.0/postgres/schemaChanges.sql | 29 +++++++++++++++---- ...ated-tests-and-their-tasks-use-an-index.md | 16 +++++++--- 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql index f267c576434c..f1a142a44e28 100644 --- a/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql @@ -71,7 +71,7 @@ SET @test_case_generated_by_class_ddl = ( AND column_name = 'generatedByClassId' ), 'SELECT 1', - 'ALTER TABLE test_case ADD COLUMN generatedByClassId VARCHAR(36) GENERATED ALWAYS AS (json_unquote(json_extract(`json`, _utf8mb4''$.generatedBy.class.id''))) STORED NULL' + 'ALTER TABLE test_case ADD COLUMN generatedByClassId VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN char_length(json_unquote(json_extract(`json`, _utf8mb4''$.generatedBy.class.id''))) = 36 THEN json_unquote(json_extract(`json`, _utf8mb4''$.generatedBy.class.id'')) END) STORED NULL' ) ); PREPARE test_case_generated_by_class_stmt FROM @test_case_generated_by_class_ddl; @@ -97,7 +97,7 @@ DEALLOCATE PREPARE test_case_generated_by_class_idx_stmt; -- A task that proposes a test case carries a test case proposal, written as JSON text, in its -- payload. The column holds the class that generated the proposal, and stays NULL for every other --- task and for a payload that is not JSON. +-- task, for a payload that is not JSON and for a class id that is not 36 characters. SET @task_entity_test_case_class_ddl = ( SELECT IF( EXISTS ( @@ -108,7 +108,7 @@ SET @task_entity_test_case_class_ddl = ( AND column_name = 'testCaseClassId' ), 'SELECT 1', - 'ALTER TABLE task_entity ADD COLUMN testCaseClassId VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestionType'')) = ''TestCase'' AND json_valid(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue''))) THEN json_unquote(json_extract(CAST(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue'')) AS JSON), _utf8mb4''$.generatedBy.class.id'')) END) STORED NULL' + 'ALTER TABLE task_entity ADD COLUMN testCaseClassId VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestionType'')) = ''TestCase'' AND json_valid(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue''))) AND char_length(json_unquote(json_extract(CAST(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue'')) AS JSON), _utf8mb4''$.generatedBy.class.id''))) = 36 THEN json_unquote(json_extract(CAST(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue'')) AS JSON), _utf8mb4''$.generatedBy.class.id'')) END) STORED NULL' ) ); PREPARE task_entity_test_case_class_stmt FROM @task_entity_test_case_class_ddl; diff --git a/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql index a2e30d2ab84e..a58dd6839f75 100644 --- a/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql @@ -49,23 +49,42 @@ CREATE INDEX IF NOT EXISTS ontology_declined_definition_listing_index -- Generated tests and the suggestion tasks that propose a test case are looked up by the class -- that generated them. The class is a stored column of its own, filled from the JSON of every --- existing row, so each lookup reads an index instead of every row. +-- existing row, so each lookup reads an index instead of every row. A value a column cannot read +-- (a class id that is not 36 characters, a proposal that is not JSON) leaves it NULL and never +-- fails the write. -- ADR:2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index ALTER TABLE test_case ADD COLUMN IF NOT EXISTS generatedbyclassid VARCHAR(36) - GENERATED ALWAYS AS (json -> 'generatedBy' -> 'class' ->> 'id') STORED; + GENERATED ALWAYS AS ( + CASE WHEN char_length(json -> 'generatedBy' -> 'class' ->> 'id') = 36 + THEN json -> 'generatedBy' -> 'class' ->> 'id' + END + ) STORED; CREATE INDEX IF NOT EXISTS idx_test_case_generated_by_class ON test_case (generatedbyclassid) WHERE generatedbyclassid IS NOT NULL; -- A task that proposes a test case carries a test case proposal, written as JSON text, in its --- payload. The column holds the class that generated the proposal, and stays NULL for every other --- task. +-- payload. A generated column cannot catch a cast error, so the function does: it drops the +-- escape of a NUL character, which jsonb refuses, reads the class, and returns NULL for text +-- that is not JSON or a class id that is not 36 characters. +CREATE OR REPLACE FUNCTION test_case_proposal_class_id(proposal text) RETURNS varchar(36) +LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE + class_id text; +BEGIN + class_id := replace(proposal, '\u0000', '')::jsonb -> 'generatedBy' -> 'class' ->> 'id'; + RETURN CASE WHEN char_length(class_id) = 36 THEN class_id END; +EXCEPTION WHEN others THEN + RETURN NULL; +END +$$; + ALTER TABLE task_entity ADD COLUMN IF NOT EXISTS testcaseclassid VARCHAR(36) GENERATED ALWAYS AS ( CASE WHEN json -> 'payload' ->> 'suggestionType' = 'TestCase' - THEN ((json -> 'payload' ->> 'suggestedValue')::jsonb -> 'generatedBy' -> 'class' ->> 'id') + THEN test_case_proposal_class_id(json -> 'payload' ->> 'suggestedValue') END ) STORED; diff --git a/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md b/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md index fac3344b3809..d08867ffc84a 100644 --- a/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md +++ b/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md @@ -1,7 +1,7 @@ # The lookups of generated tests and of the tasks that propose them read an index on the generating class - **Status:** Accepted -- **Revisions:** v1 2026-12-05 (initial) +- **Revisions:** v1 2026-12-05 (initial); v2 2026-12-05 (a value a column cannot read is NULL) - **Deciders:** Ontology Studio maintainers - **Guard:** `GeneratedLookupIndexMigrationIT` - **Related:** ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test (the generated tests, their suggestion tasks and the reconcile that reads both) @@ -35,9 +35,17 @@ the 2.2.0 migration: - `test_case.generatedByClassId` is `generatedBy.class.id`. It is NULL for every test case that no shape generated. - `task_entity.testCaseClassId` is `generatedBy.class.id` of the proposal in the payload, when the - payload's `suggestionType` is `TestCase`. It is NULL for every other task. MySQL also leaves it - NULL when the value is not JSON; PostgreSQL has no way to test that in a generated expression, so - it relies on the API, which refuses a test case suggestion that is not a valid proposal. + payload's `suggestionType` is `TestCase`. It is NULL for every other task. +- **A value a column cannot read is NULL, and never fails a write or the migration.** Both columns + keep the class id only when it is 36 characters, which is the width of a UUID and of the column. + `testCaseClassId` is also NULL when the proposal is not JSON. MySQL tests `json_valid` in the + expression. PostgreSQL cannot catch a cast error inside a generated expression, so the column + calls `test_case_proposal_class_id(text)`, an `IMMUTABLE` function the same 2.2.0 file creates + with `CREATE OR REPLACE FUNCTION` before the column. It removes the `\u0000` escape, which + `jsonb` refuses, casts the text to `jsonb`, reads the class, and returns NULL on any error + (`EXCEPTION WHEN others`). Without these guards a task whose value is not JSON, or a class id + longer than 36 characters, failed its own write, and the migration failed on a database that + already held such a row. - `idx_test_case_generated_by_class` and `idx_task_test_case_class` index them. PostgreSQL's are partial (`WHERE ... IS NOT NULL`), because all but a few hundred rows are NULL; MySQL has no partial index. From ca17409993d39ec9d6f5c7aeccb3ae7d29e54f27 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 14:24:36 -0800 Subject: [PATCH 189/203] Write the shapes of the lookup columns through the task insert --- .../it/tests/GeneratedLookupIndexMigrationIT.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java index 83365743089a..6b78f1171795 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java @@ -244,11 +244,7 @@ private static void insertShapesThroughTheDaos( final TimeSeriesDAOs.TestCaseDAO tests = testDao(handle); for (final Shape shape : shapes) { final String taskId = UUID.randomUUID().toString(); - tasks.insert( - tasks.getTableName(), - tasks.getNameHashColumn(), - PREFIX + "late-k-" + shape.name(), - shapeTaskJson(taskId, shape)); + tasks.insertTask(taskId, shapeTaskJson(taskId, shape), PREFIX + "late-k-" + shape.name()); taskIds.add(taskId); final String testId = UUID.randomUUID().toString(); tests.insert( From 48bbdaa00da375f5f38be70c1fa6b539d8f66246 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 15:02:45 -0800 Subject: [PATCH 190/203] Check date-typed properties against column types, show the mapping source only to a reader who may view it, refuse a test proposal with no class --- ...dependentOntologyMappingAdviceCountIT.java | 13 +++ .../IndependentOntologyMappingAdviceIT.java | 13 +++ ...ndependentOntologyMappingSourceReadIT.java | 109 ++++++++++++++++++ .../ontology/OntologyBindingAccess.java | 36 ++++-- .../ontology/OntologyColumnTypeFit.java | 16 +++ .../OntologyMappingHealthService.java | 19 ++- .../ontology/OntologyTableMappingRules.java | 4 +- .../resources/ontology/OntologyResource.java | 12 +- .../service/tasks/TestCaseSuggestion.java | 7 +- .../OntologyBindingAccessLogTest.java | 109 ++++++++++++++++++ .../OntologyMappingAdviceRulesTest.java | 32 +++++ .../OntologyTableMappingRulesTest.java | 20 ++++ .../service/tasks/TestCaseSuggestionTest.java | 30 +++++ 13 files changed, 405 insertions(+), 15 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceReadIT.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAccessLogTest.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java index 5dc2f94621cc..f06c8d170578 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java @@ -1,3 +1,16 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java index 53d55a638e2c..c378eabf81ca 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java @@ -1,3 +1,16 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceReadIT.java new file mode 100644 index 000000000000..d01f5231cdd0 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceReadIT.java @@ -0,0 +1,109 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.health; +import static org.openmetadata.it.tests.OntologyMappingFixtures.mappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.setMappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.summary; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.DenyPolicyPrincipals; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Database; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; + +/** The database an ontology names as its mapping source is shown only to a reader who may view it. */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyMappingSourceReadIT extends BaseOntologyApprovalIT { + private static final String PII_SENSITIVE = "PII.Sensitive"; + + @Test + void aReaderDeniedTheMappingSourceDatabaseSeesNoReferenceToIt(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var open = schema(ns); + final Database sensitive = tagged(schema(ns).getDatabase().getId().toString()); + put( + admin(), + order, + binding( + table(open, "orders", column("order_id", ColumnDataType.BIGINT)), + OntologyBindingRole.IDENTITY, + "order_id"), + 0L); + setMappingSource(admin(), ontology, sensitive.getEntityReference()); + final OpenMetadataClient reader = + DenyPolicyPrincipals.clientDeniedWhen( + ns.shortPrefix("mapSrc"), + "database", + MetadataOperation.VIEW_BASIC, + "matchAnyTag('" + PII_SENSITIVE + "')"); + + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> reader.databases().get(sensitive.getId().toString())) + .getStatusCode()); + + final var seenHealth = health(reader, ontology, ""); + final var seenOntology = reader.ontologies().get(ontology.getId().toString(), "mappingSource"); + + assertNull(seenHealth.getMappingSource()); + assertNull(mappingSource(reader, ontology)); + assertEquals(List.of("outsideMappingSource Order orders"), summary(seenHealth.getEntries())); + for (final String body : + List.of(JsonUtils.pojoToJson(seenHealth), JsonUtils.pojoToJson(seenOntology))) { + assertFalse(body.contains(sensitive.getId().toString()), body); + } + assertEquals(sensitive.getId(), health(admin(), ontology, "").getMappingSource().getId()); + assertEquals(sensitive.getId(), mappingSource(admin(), ontology).getId()); + } + + private static Database tagged(final String id) { + final Database database = admin().databases().get(id); + final TagLabel tag = + new TagLabel() + .withTagFQN(PII_SENSITIVE) + .withSource(TagLabel.TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL) + .withState(TagLabel.State.CONFIRMED); + database.setTags(List.of(tag)); + return admin().databases().update(id, database); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java index b94520a234df..ab6941f56fae 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java @@ -110,11 +110,22 @@ Optional> readable(final Access access, final String type, fi try { return Optional.of(authorized(access, type, id, MetadataOperation.VIEW_BASIC)); } catch (final AuthorizationException | EntityNotFoundException unavailable) { - LOG.debug("Binding target {} {} is unavailable to the current reader", type, id); + LOG.debug("A binding target of type {} is unavailable to the current reader", type); return Optional.empty(); } } + /** As above, and a deleted entity counts when the caller may view it. */ + boolean viewableEvenIfDeleted(final Access access, final String type, final UUID id) { + try { + authorizedWorking(access, type, id, MetadataOperation.VIEW_BASIC); + return true; + } catch (final AuthorizationException | EntityNotFoundException unavailable) { + LOG.debug("A binding target of type {} is unavailable to the current reader", type); + return false; + } + } + /** Applies one more operation to an entity of {@code type} already loaded for the caller. */ void require( final Access access, @@ -218,6 +229,7 @@ private > Map> authorizedB // Every attribute a condition reads; setFieldsInBulk clears the fields it is not asked for. repository.setFieldsInBulk(ResourceContext.authorizationFields(repository), batch); final Map> viewable = new HashMap<>(); + int hidden = 0; for (final T entity : batch) { try { permit( @@ -225,11 +237,11 @@ private > Map> authorizedB new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), new ResourceContext<>(repository.getEntityType(), entity, repository)); viewable.put(entity.getId(), entity); - } catch (final AuthorizationException hidden) { - LOG.debug( - "Released {} {} is hidden from the reader", repository.getEntityType(), entity.getId()); + } catch (final AuthorizationException denied) { + hidden++; } } + logHidden("Released", repository.getEntityType(), hidden, batch.size()); return viewable; } @@ -252,6 +264,7 @@ private > List viewableAmong( final Access access, final EntityRepository repository, final List entities) { final var tags = BulkFieldHydrator.forTags(repository, entities); final List viewable = new ArrayList<>(); + int hidden = 0; for (final T entity : entities) { try { permit( @@ -259,16 +272,21 @@ private > List viewableAmong( new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), new ResourceContext<>(repository.getEntityType(), entity, repository, tags)); viewable.add(entity); - } catch (final AuthorizationException hidden) { - LOG.debug( - "Binding target {} {} is hidden from the reader", - repository.getEntityType(), - entity.getId()); + } catch (final AuthorizationException denied) { + hidden++; } } + logHidden("Binding target", repository.getEntityType(), hidden, entities.size()); return viewable; } + private static void logHidden( + final String what, final String type, final int hidden, final int total) { + if (hidden > 0) { + LOG.debug("{} of type {}: {} of {} are hidden from the reader", what, type, hidden, total); + } + } + private > T authorized( final Access access, final EntityRepository repository, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java index 5f1728db43d7..ef4439bb0625 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java @@ -1,3 +1,16 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.openmetadata.service.ontology; import java.net.URI; @@ -84,6 +97,9 @@ static boolean mismatched(final URI datatype, final ColumnDataType type) { /** The column types that hold the datatype, or null when the datatype fits every column. */ private static Set accepted(final URI datatype) { final String iri = datatype.toString(); + if (OwlDatatypeSupport.isDate(iri)) { + return DATES; + } if (!iri.startsWith(XSD)) { return null; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java index ba83f48c2d91..3b6491a64be6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java @@ -16,6 +16,7 @@ import org.openmetadata.schema.entity.data.Ontology; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyColumnBinding; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; @@ -56,6 +57,18 @@ public OntologyMappingHealthService( this.targets = new OntologyBindingAccess(authorizer, repositories); } + /** + * The ontology with the mapping source it names only when the caller may view that database. The + * findings of a health page use the stored source whoever reads them. + */ + public Ontology withViewableMappingSource(final Access access, final Ontology ontology) { + final EntityReference source = ontology.getMappingSource(); + if (source != null && !targets.viewableEvenIfDeleted(access, Entity.DATABASE, source.getId())) { + ontology.setMappingSource(null); + } + return ontology; + } + /** {@code ontology} is one the caller may view, read with its mapping source. */ public OntologyMappingHealth page( final Access access, final Ontology ontology, final String after, final int limit) { @@ -70,12 +83,16 @@ public OntologyMappingHealth page( OntologyMappingHealthRules.check( tables, context(access, ontology, tables, loaded), progress(access, cursor)); return new OntologyMappingHealth() - .withMappingSource(ontology.getMappingSource()) + .withMappingSource(withViewableMappingSource(access, copyOf(ontology)).getMappingSource()) .withEntries(page.entries()) .withAfter(scanned.size() > limit ? Cursor.next(rows.getLast(), page.progress()) : null); } } + private static Ontology copyOf(final Ontology ontology) { + return new Ontology().withMappingSource(ontology.getMappingSource()); + } + /** The rows whose table and class are both live and viewable. Every other row says nothing. */ private List boundTables( final Access access, final List rows, final Loaded loaded) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java index 4c3c052387bb..186c585c45b2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java @@ -180,7 +180,9 @@ private static TableBinding binding( for (final OntologyColumnBinding column : listOrEmpty(row.columns())) { final OntologyProperty property = facts.properties().get(column.getPropertyId()); if (OntologyBindingRules.resolveColumn(table, column.getColumnPath()) == null) { - missing.add(column.getColumnPath()); + if (property == null || facts.viewableProperties().contains(property.getId())) { + missing.add(column.getColumnPath()); + } } else if (property == null) { absent.add(column.getColumnPath()); } else if (facts.viewableProperties().contains(property.getId())) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java index 7f306addf9f0..bf2811861537 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java @@ -852,7 +852,10 @@ public ResultList list( @QueryParam("after") final String after, @QueryParam("include") @DefaultValue("non-deleted") final Include include) { final ListFilter filter = new ListFilter(include); - return listInternal(uriInfo, securityContext, fields, filter, limit, before, after); + final var page = listInternal(uriInfo, securityContext, fields, filter, limit, before, after); + final Access access = new Access(uriInfo, securityContext); + page.getData().forEach(ontology -> mappingHealth.withViewableMappingSource(access, ontology)); + return page; } @GET @@ -864,7 +867,8 @@ public Ontology get( @PathParam("id") final UUID id, @QueryParam("fields") final String fields, @QueryParam("include") @DefaultValue("non-deleted") final Include include) { - return getInternal(uriInfo, securityContext, id, fields, include, null); + final Ontology ontology = getInternal(uriInfo, securityContext, id, fields, include, null); + return mappingHealth.withViewableMappingSource(new Access(uriInfo, securityContext), ontology); } @GET @@ -876,7 +880,9 @@ public Ontology getByName( @PathParam("fqn") final String fqn, @QueryParam("fields") final String fields, @QueryParam("include") @DefaultValue("non-deleted") final Include include) { - return getByNameInternal(uriInfo, securityContext, fqn, fields, include, null); + final Ontology ontology = + getByNameInternal(uriInfo, securityContext, fqn, fields, include, null); + return mappingHealth.withViewableMappingSource(new Access(uriInfo, securityContext), ontology); } @POST diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java index 396be985cbfd..c916bb71fadf 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java @@ -240,7 +240,12 @@ private static void requireGenerated(TestCaseProposal proposal) { } String digest = digest(create.getTestDefinition(), create.getEntityLink(), create.getParameterValues()); - if (generatedBy == null || !digest.equals(generatedBy.getContentDigest())) { + if (generatedBy == null + || generatedBy.getClass_() == null + || generatedBy.getClass_().getId() == null) { + throw BadRequestException.of("A test case suggestion names the class it was generated for"); + } + if (!digest.equals(generatedBy.getContentDigest())) { throw BadRequestException.of( "The content digest of a test case suggestion must be that of its test definition, entity" + " link and parameter values: %s".formatted(digest)); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAccessLogTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAccessLogTest.java new file mode 100644 index 000000000000..e2fda52e59f6 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAccessLogTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.Database; +import org.openmetadata.schema.type.Include; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.util.EntityUtil.Fields; +import org.slf4j.LoggerFactory; + +class OntologyBindingAccessLogTest { + private final Authorizer authorizer = mock(Authorizer.class); + private final EntityRepository repository = mock(EntityRepository.class); + private final Access access = new Access(null, null); + private Logger logger; + private Level level; + private ListAppender appender; + + @BeforeEach + void setUp() { + logger = (Logger) LoggerFactory.getLogger(OntologyBindingAccess.class); + level = logger.getLevel(); + logger.setLevel(Level.DEBUG); + appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + when(repository.getEntityType()).thenReturn(Entity.DATABASE); + when(repository.getEntityClass()).thenReturn(Database.class); + when(repository.getFields(any(String.class))).thenReturn(new Fields(Set.of())); + } + + @AfterEach + void tearDown() { + logger.detachAppender(appender); + logger.setLevel(level); + } + + @Test + void aTargetHiddenFromTheReaderIsLoggedByCountAndNeverById() { + final Database first = new Database().withId(UUID.randomUUID()); + final Database second = new Database().withId(UUID.randomUUID()); + when(repository.get(any(), any(List.class), any(), any(Include.class))) + .thenReturn(List.of(first, second)); + doThrow(new AuthorizationException("denied")).when(authorizer).authorize(any(), any(), any()); + + final var viewable = + new OntologyBindingAccess(authorizer, type -> repository) + .viewable(access, Entity.DATABASE, List.of(first.getId(), second.getId())); + + assertTrue(viewable.isEmpty()); + assertEquals( + List.of("Binding target of type database: 2 of 2 are hidden from the reader"), messages()); + assertFalse(messages().toString().contains(first.getId().toString())); + } + + @Test + void aSingleTargetTheReaderCannotReadIsLoggedWithoutItsId() { + final UUID id = UUID.randomUUID(); + when(repository.get(any(), any(UUID.class), any(), any(Include.class), any(Boolean.class))) + .thenReturn(new Database().withId(id)); + doThrow(new AuthorizationException("denied")).when(authorizer).authorize(any(), any(), any()); + + final var readable = + new OntologyBindingAccess(authorizer, type -> repository) + .readable(access, Entity.DATABASE, id); + + assertTrue(readable.isEmpty()); + assertEquals( + List.of("A binding target of type database is unavailable to the current reader"), + messages()); + } + + private List messages() { + return appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList(); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java index 0c2b241f5d15..ea0fc4870794 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java @@ -1,3 +1,16 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.openmetadata.service.ontology; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -407,6 +420,25 @@ void aColumnTypeIsCheckedAgainstTheDatatypeOfItsProperty( property)); } + @ParameterizedTest + @CsvSource({"VARCHAR,true", "INT,true", "DATE,false", "TIMESTAMP,false", "DATETIME,false"}) + void aColumnTypeIsCheckedAgainstThePlatformDateType( + final ColumnDataType type, final boolean mismatch) { + final Table table = table("customers", column("c", type)); + final OntologyProperty property = dataProperty("p", OwlDatatypeSupport.DATE.toString()); + + assertEquals( + mismatch + ? List.of("columnTypeMismatch [c] " + type + " " + OwlDatatypeSupport.DATE) + : List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(property, "c")), + property)); + } + @Test void aPropertyWithNoSingleDatatypeIsNeverChecked() { final Table table = table("customers", column("c", ColumnDataType.VARCHAR)); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java index 0bd14c93eda6..da0cb51b3e13 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java @@ -744,6 +744,26 @@ void aPropertyTheVersionLacksIsListedByColumnPathAndAColumnTheTableLostIsListedA assertFalse(JsonUtils.pojoToJson(mapping).contains(lacking.getId().toString())); } + @Test + void aColumnTheTableLostIsNotListedWhenItsPropertyIsHidden() { + final World world = new World(); + final OntologyProperty secret = world.hiddenProperty("secret"); + final OntologyProperty name = world.data("name"); + world.bind( + world.type("Customer"), + world.table("customers", "id"), + OntologyBindingRole.IDENTITY, + "id", + column(secret, "secret_column"), + column(name, "dropped")); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding bound = mapping.classes().getFirst().tables().getFirst(); + assertEquals(List.of(List.of("dropped")), bound.missingColumns()); + assertFalse(JsonUtils.pojoToJson(mapping).contains("secret_column")); + } + @Test void theTableCarriesItsIdNameServiceTypeAndColumns() { final World world = new World(); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java index 9745fa4429d9..4127ca0ed74c 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java @@ -248,6 +248,36 @@ void aProposalWithNoInspectionQueryIsRefused() { refusal(() -> TestCaseSuggestion.require(task(with(p -> p.setInspectionQuery(null)))))); } + @Test + void aProposalWithNoGeneratingClassIsRefusedWhenFiled() { + final String message = "A test case suggestion names the class it was generated for"; + assertEquals( + message, + refusal( + () -> TestCaseSuggestion.require(task(with(p -> p.getGeneratedBy().setClass_(null)))))); + assertEquals( + message, + refusal( + () -> + TestCaseSuggestion.require( + task(with(p -> p.getGeneratedBy().setClass_(new EntityReference())))))); + assertEquals( + message, + refusal(() -> TestCaseSuggestion.require(task(with(p -> p.setGeneratedBy(null)))))); + } + + @Test + void aResolutionThatLeavesNoGeneratingClassIsRefusedWhenApproved() { + final TestCaseProposal withoutClass = with(p -> p.getGeneratedBy().setClass_(null)); + final Map resolved = + Map.of("suggestedValue", JsonUtils.pojoToJson(withoutClass)); + + assertEquals( + "A test case suggestion names the class it was generated for", + refusal(() -> TestCaseSuggestion.requireToApply(task(proposal()), resolved, null))); + assertDoesNotThrow(() -> TestCaseSuggestion.requireToApply(task(proposal()), null, null)); + } + @Test void aValueThatIsNotAProposalIsRefused() { Task task = task(proposal()); From 0efd86108cd1df06ed96ed24386ac15d671cdf00 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 16:26:26 -0800 Subject: [PATCH 191/203] ontology: a declined binding is keyed by its table, role, key and filter, not its columns --- ...ned-definition-is-remembered-by-content.md | 17 ++++--- .../tests/OntologyDeclinedBindingShapeIT.java | 17 ++++++- .../ontology/OntologyDefinitionDigest.java | 25 +++++---- .../OntologyDeclinedBindingShapeKeysTest.java | 51 +++++++++++++++++-- 4 files changed, 88 insertions(+), 22 deletions(-) diff --git a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md index 73c027af1d39..7cf2bd89456d 100644 --- a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md +++ b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md @@ -1,7 +1,7 @@ # A declined definition is remembered by its content, and narrowing a draft keeps its classes - **Status:** Accepted -- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-26 (canonical form stated in full and made stable for set order, empty lists and server-derived fields; narrowing checks every kept operation; a permanent delete removes the rows; declining asks the draft read right); v3 2026-12-05 (a table binding and a shape can be declined) +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-26 (canonical form stated in full and made stable for set order, empty lists and server-derived fields; narrowing checks every kept operation; a permanent delete removes the rows; declining asks the draft read right); v3 2026-12-05 (a table binding and a shape can be declined); v4 2026-12-05 (a binding is keyed by its table, role, key and row filter, not its columns) - **Deciders:** Ontology maintainers - **Guard:** `OntologyDefinitionDigestTest`, `OntologyDeclinedDefinitionsTest`, `OntologyDeclinedDefinitionDaoTest`, `OntologyDraftNarrowingTest`, @@ -75,11 +75,16 @@ carries no definition, such as a delete, cannot be declined. **A table binding and a shape.** An `UPSERT_BINDING` operation stands under the binding's class IRI, and an `UPSERT_SHAPE` operation under the shape's `targetConcept`. A binding's digest is the -SHA-256 of the canonical JSON of the binding without its `classIri`: its table, role, `subjectKey`, -row filter and columns, each column with its property IRI, column path and join. The steps 1, 4, 6 -and 7 above apply. Keys are sorted, and the columns and the column pairs of a join are sets, sorted -by the text of each element. The `subjectKey` keeps its order, because a contributing table pairs -its key with the identity table's by position. A shape's digest is the SHA-256 of the canonical +SHA-256 of the canonical JSON of the binding's table, role, `subjectKey` and row filter. The class +stays out, because a record keeps it as its IRI, and so do the columns and their joins. A reviewer +who rejects a binding rejects mapping that class to that table with that key and filter, and a +declined binding must stay declined when the same review declines one of its columns: a tool +that cuts the declined property or relation builds the binding without that column, and a digest +over the columns would then no longer match. A binding that differs only in which columns it maps +is the same declined binding. Another table, role, key or filter is another binding. The steps 1, 4, +6 and 7 above apply, with keys sorted. A binding with no role and one whose role is `null` or whose +`subjectKey` is empty give one digest. The `subjectKey` keeps its order, because a contributing +table pairs its key with the identity table's by position. A shape's digest is the SHA-256 of the canonical JSON of its constraints alone, in authored order, so a fresh id, name or description does not change it and another constraint does. A changed binding or shape does not match. The digests of the test fixtures are pinned in `OntologyDeclinedBindingShapeKeysTest`. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java index fe2e409fdacf..fa44b11e32c4 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.boundColumn; import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedDataProperty; @@ -52,6 +53,8 @@ import org.openmetadata.schema.type.OntologyDeclinedDefinition; import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatch; import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; /** * Declining a table binding and a shape of a draft, and matching later drafts against them. The @@ -92,10 +95,14 @@ void aDeclinedBindingAndShapeMatchUnderFreshIdsAndAChangedOneDoesNot(final TestN shape(ontology, 1), binds(keyed(archive, "order_id")), binds(keyed(orders, "customer_id")), - shape(ontology, 2)) + shape(ontology, 2), + binds( + keyed(orders, "order_id").withColumns(List.of(boundColumn(TOTAL, "order_id")))), + binds(keyed(orders, "order_id").withRole(OntologyBindingRole.CONTRIBUTING)), + binds(keyed(orders, "order_id").withRowFilter(statusFilter()))) .getMatches(); assertEquals( - List.of(true, true, false, false, false), + List.of(true, true, false, false, false, true, false, false), matches.stream().map(OntologyDeclinedDefinitionMatch::getDeclined).toList()); assertEquals(binding.getId(), matches.get(0).getRecord().getOperationId()); assertEquals(shape.getId(), matches.get(1).getRecord().getOperationId()); @@ -138,6 +145,12 @@ private static OntologyChangeOperation shape(final Ontology ontology, final int return creates(shape); } + private static OntologyRowFilter statusFilter() { + return new OntologyRowFilter() + .withColumn(List.of("customer_id")) + .withOperator(OntologyRowFilterOperator.IS_NOT_NULL); + } + private static OntologyBindingChange keyed(final Table table, final String key) { return bindingOf(ORDER, table) .withRole(OntologyBindingRole.IDENTITY) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java index d3d454688094..4192f2545e6a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java @@ -77,6 +77,8 @@ public final class OntologyDefinitionDigest { "superClasses", "subClasses"); + private static final List BINDING_KEY_FIELDS = + List.of("tableId", "role", "subjectKey", "rowFilter"); private static final String SCHEMA_FOLDER = "/json/schema/entity/data/"; private static final Map, String> SCHEMAS = Map.of( @@ -92,20 +94,21 @@ public static String of(final OntologyDefinition definition) { } /** - * The digest of a table binding, without its class, which a record keeps as its IRI. The columns - * and the column pairs of each join are sets and sort by their text. The subject key keeps its - * order, because a contributing table pairs its key with the identity table's by position. + * The digest of a table binding, which a record keys by what a reviewer rejects: the table, the + * role, the subject key and the row filter. The class stays out, because a record keeps it as its + * IRI, and so do the columns and their joins, so a binding that maps fewer columns is the same + * declined binding. The subject key keeps its order, because a contributing table pairs its key + * with the identity table's by position. */ public static String ofBinding(final OntologyBindingChange binding) { - final ObjectNode content = + final JsonNode tree = JsonUtils.valueToTree( - JsonUtils.readValue(JsonUtils.pojoToJson(binding), OntologyBindingChange.class)) - .deepCopy(); - content.remove("classIri"); - final JsonNode canonical = OntologyJson.canonical(withoutEmpty(content)); - sortAsSet(canonical, "columns"); - canonical.path("columns").forEach(column -> sortAsSet(column.path("join"), "on")); - return DigestUtils.sha256Hex(canonical.toString()); + JsonUtils.readValue(JsonUtils.pojoToJson(binding), OntologyBindingChange.class)); + final ObjectNode content = JsonUtils.getObjectNode(); + BINDING_KEY_FIELDS.stream() + .filter(tree::has) + .forEach(field -> content.set(field, tree.get(field).deepCopy())); + return DigestUtils.sha256Hex(OntologyJson.canonical(withoutEmpty(content)).toString()); } /** The digest of a shape's constraints, in the order they were authored. */ diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java index d2344a991857..a5bfd43b7df8 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java @@ -29,6 +29,8 @@ import org.openmetadata.schema.type.OntologyColumnBindingChange; import org.openmetadata.schema.type.OntologyJoinChange; import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.type.OntologyShapeSeverity; @@ -47,7 +49,7 @@ void aBindingStandsUnderItsClassAndTheSameBindingGivesTheSameKey() { assertEquals(OntologyChangeOperationType.UPSERT_BINDING, key.type()); assertEquals(ORDER, key.iri()); assertEquals( - "3993fb92667097975f2d0bf71b5f1d64deb049cd20614bd7590571b0b90cee03", key.payloadDigest()); + "3340e728db85bac61ad750b27a4ed386e92603077584872306aa0a1489e36960", key.payloadDigest()); assertEquals(key, OntologyDeclinedDefinitions.keyOf(bind(binding()))); } @@ -67,13 +69,49 @@ void theOrderOfColumnsAndOfJoinPairsDoesNotChangeTheKey() { } @Test - void anotherTableKeyRoleFilterOrColumnGivesAnotherKey() { + void aBindingThatMapsOtherColumnsOrOtherJoinsGivesTheSameKey() { + final String base = digest(bind(binding())); + + assertEquals(base, digest(bind(binding().withColumns(List.of(column(TOTAL, "total")))))); + assertEquals( + base, + digest( + bind( + binding() + .withColumns( + List.of(column(PLACED_BY, "customer_id").withJoin(join(false))))))); + assertEquals(base, digest(bind(binding().withColumns(List.of())))); + assertEquals(base, digest(bind(binding().withColumns(null)))); + assertEquals( + base, + digest( + bind( + binding() + .withColumns( + List.of( + column(TOTAL, "total"), + column(PLACED_BY, "region").withJoin(join(true))))))); + } + + @Test + void anotherTableKeyRoleOrFilterGivesAnotherKey() { final String base = digest(bind(binding())); assertNotEquals(base, digest(bind(binding().withTableId(ARCHIVE)))); assertNotEquals(base, digest(bind(binding().withSubjectKey(List.of(List.of("customer_id")))))); assertNotEquals(base, digest(bind(binding().withRole(OntologyBindingRole.CONTRIBUTING)))); - assertNotEquals(base, digest(bind(binding().withColumns(List.of(column(TOTAL, "amount")))))); + assertNotEquals(base, digest(bind(binding().withRole(null).withSubjectKey(null)))); + assertNotEquals(base, digest(bind(binding().withRowFilter(filter("kind", "a"))))); + assertNotEquals( + digest(bind(binding().withRowFilter(filter("kind", "a")))), + digest(bind(binding().withRowFilter(filter("kind", "b"))))); + } + + @Test + void aBindingWithNoRoleKeysTheSameWhetherTheRoleIsAbsentOrNull() { + assertEquals( + digest(bind(binding().withRole(null).withSubjectKey(null))), + digest(bind(binding().withRole(null).withSubjectKey(List.of())))); } @Test @@ -130,6 +168,13 @@ private static OntologyBindingChange binding() { column(TOTAL, "total"), column(PLACED_BY, "customer_id").withJoin(join(false)))); } + private static OntologyRowFilter filter(final String column, final String value) { + return new OntologyRowFilter() + .withColumn(List.of(column)) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue(value); + } + private static OntologyColumnBindingChange column(final URI property, final String column) { return new OntologyColumnBindingChange() .withPropertyIri(property) From aa0ef418fb2338648473d8fcb87730dea3ca9eca Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 17:33:43 -0800 Subject: [PATCH 192/203] Test that a release member listing keeps only the members the caller may view --- .../tests/IndependentOntologyReleaseIT.java | 33 +-- ...ndependentOntologyReleaseMemberReadIT.java | 269 ++++++++++++++++++ 2 files changed, 284 insertions(+), 18 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseMemberReadIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseIT.java index 5941df81e99a..bbc7dcc7ebf5 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseIT.java @@ -481,24 +481,21 @@ private static JsonNode events(OntologyRelease release, String query) { private static void assertMemberReadDenied( OpenMetadataClient denied, OntologyRelease release, OntologyConcept concept) { - for (String suffix : List.of("", "/" + concept.getId())) { - assertEquals( - 403, - assertThrows( - OpenMetadataException.class, - () -> - denied - .getHttpClient() - .execute( - HttpMethod.GET, - "/v1/ontologyReleases/" - + release.getId() - + "/members/CONCEPT" - + suffix, - null, - JsonNode.class)) - .getStatusCode()); - } + final String members = "/v1/ontologyReleases/" + release.getId() + "/members/CONCEPT"; + final JsonNode listed = + denied.getHttpClient().execute(HttpMethod.GET, members, null, JsonNode.class); + assertEquals(0, listed.path("data").size()); + assertEquals(0, listed.path("paging").path("total").asInt()); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> + denied + .getHttpClient() + .execute( + HttpMethod.GET, members + "/" + concept.getId(), null, JsonNode.class)) + .getStatusCode()); } private static OntologyReleaseMember member(OntologyRelease release, UUID conceptId) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseMemberReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseMemberReadIT.java new file mode 100644 index 000000000000..8380e77bafcf --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseMemberReadIT.java @@ -0,0 +1,269 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.bootstrap.SharedEntities; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyConcept; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyConceptType; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.config.OpenMetadataConfig; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** A release lists, to each reader, only the members that reader may view. */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyReleaseMemberReadIT extends BaseOntologyApprovalIT { + private record Members( + Ontology ontology, + OntologyRelease release, + List classes, + List properties) {} + + @Test + void aReaderDeniedMembersOwnedByOthersListsOnlyTheMembersItMayView(final TestNamespace ns) { + final Members members = members(ns); + ownBy(members, SharedEntities.get().USER1.getEntityReference()); + try (RdfAccessFixtures concepts = new RdfAccessFixtures("ownC" + ns.shortPrefix()); + RdfAccessFixtures properties = new RdfAccessFixtures("ownP" + ns.shortPrefix())) { + assertReaderSeesOnlyViewable(members, reader(concepts, properties, "!noOwner()")); + } + } + + @Test + void aReaderDeniedMembersItOwnsListsOnlyTheMembersItMayView(final TestNamespace ns) { + final Members members = members(ns); + try (RdfAccessFixtures concepts = new RdfAccessFixtures("mineC" + ns.shortPrefix()); + RdfAccessFixtures properties = new RdfAccessFixtures("mineP" + ns.shortPrefix())) { + final OpenMetadataClient reader = reader(concepts, properties, "isOwner()"); + final String userName = + ("mineC" + ns.shortPrefix() + "reader" + concepts.suffix()).toLowerCase(Locale.ROOT); + ownBy(members, SdkClients.adminClient().users().getByName(userName).getEntityReference()); + assertReaderSeesOnlyViewable(members, reader); + } + } + + @Test + void aReaderDeniedTheOntologyStillGetsForbidden(final TestNamespace ns) { + final Members members = members(ns); + try (RdfAccessFixtures fixtures = new RdfAccessFixtures("noOnt" + ns.shortPrefix())) { + final var role = fixtures.denyRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_RELEASE); + final OpenMetadataClient denied = client(fixtures.userToken("reader", List.of(role.getId()))); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> page(denied, members.release(), "CONCEPT", 50, null)) + .getStatusCode()); + } + } + + private static void assertReaderSeesOnlyViewable( + final Members members, final OpenMetadataClient reader) { + final List hidden = List.of(hiddenClass(members), hiddenProperty(members)); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> reader.ontologyConcepts().get(hiddenClass(members))) + .getStatusCode()); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> reader.ontologyProperties().get(hiddenProperty(members))) + .getStatusCode()); + final List viewableClasses = idsExcept(members.classes(), hiddenClass(members)); + final List viewableProperties = idsExcept(members.properties(), hiddenProperty(members)); + assertEquals(viewableClasses, walk(reader, members.release(), "CONCEPT", 1, hidden)); + assertEquals(viewableProperties, walk(reader, members.release(), "PROPERTY", 1, hidden)); + assertEquals( + viewableClasses.size(), + page(reader, members.release(), "CONCEPT", 50, null).path("paging").path("total").asInt()); + assertEquals( + viewableProperties.size(), + page(reader, members.release(), "PROPERTY", 50, null).path("paging").path("total").asInt()); + assertEquals( + members.classes().size(), + page(SdkClients.adminClient(), members.release(), "CONCEPT", 50, null).path("data").size()); + assertEquals( + members.properties().size(), + page(SdkClients.adminClient(), members.release(), "PROPERTY", 50, null) + .path("data") + .size()); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> + reader + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyReleases/" + + members.release().getId() + + "/members/CONCEPT/" + + hiddenClass(members), + null, + JsonNode.class)) + .getStatusCode()); + } + + private static List walk( + final OpenMetadataClient reader, + final OntologyRelease release, + final String kind, + final int limit, + final List hidden) { + final List seen = new ArrayList<>(); + String after = null; + do { + final JsonNode body = page(reader, release, kind, limit, after); + final String text = body.toString(); + hidden.forEach(secret -> assertFalse(text.contains(secret), text)); + body.path("data") + .forEach(member -> seen.add(UUID.fromString(member.path("memberId").asText()))); + after = textOrNull(body); + } while (after != null); + return seen.stream().sorted().toList(); + } + + private static String textOrNull(final JsonNode body) { + final String after = body.path("paging").path("after").asText(""); + return after.isEmpty() ? null : after; + } + + private static JsonNode page( + final OpenMetadataClient client, + final OntologyRelease release, + final String kind, + final int limit, + final String after) { + final String cursor = after == null ? "" : "&after=" + after; + return client + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyReleases/" + + release.getId() + + "/members/" + + kind + + "?limit=" + + limit + + cursor, + null, + JsonNode.class); + } + + private static String hiddenClass(final Members members) { + return members.classes().get(1).getId().toString(); + } + + private static String hiddenProperty(final Members members) { + return members.properties().get(1).getId().toString(); + } + + private static > List idsExcept( + final List all, final String hiddenId) { + return all.stream() + .map(T::getId) + .filter(id -> !id.toString().equals(hiddenId)) + .sorted() + .toList(); + } + + private static OpenMetadataClient reader( + final RdfAccessFixtures concepts, + final RdfAccessFixtures properties, + final String condition) { + final var conceptRole = + concepts.denyRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_CONCEPT, condition); + final var propertyRole = + properties.denyRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_PROPERTY, condition); + return client(concepts.userToken("reader", List.of(conceptRole.getId(), propertyRole.getId()))); + } + + private static OpenMetadataClient client(final String token) { + return new OpenMetadataClient( + OpenMetadataConfig.builder().serverUrl(SdkClients.baseUrl()).accessToken(token).build()); + } + + /** Three classes and two properties; the second of each is the one a test hides. */ + private static Members members(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final var admin = SdkClients.adminClient(); + final List classes = new ArrayList<>(); + for (int index = 0; index < 3; index++) { + classes.add( + admin + .ontologyConcepts() + .create( + new CreateOntologyConcept() + .withOntology(ontology.getFullyQualifiedName()) + .withName("Class" + index) + .withConceptType(OntologyConceptType.OWL_CLASS))); + } + final List properties = new ArrayList<>(); + for (int index = 0; index < 2; index++) { + properties.add( + admin + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withOntology(ontology.getFullyQualifiedName()) + .withName("property" + index) + .withKind(OntologyPropertyKind.OBJECT))); + } + return new Members(ontology, capture(ontology), classes, properties); + } + + private static void ownBy(final Members members, final EntityReference owner) { + final var concepts = SdkClients.adminClient().ontologyConcepts(); + final String conceptId = members.classes().get(1).getId().toString(); + final OntologyConcept concept = concepts.get(conceptId); + concept.setOwners(List.of(owner)); + concepts.update(conceptId, concept); + final var properties = SdkClients.adminClient().ontologyProperties(); + final String propertyId = members.properties().get(1).getId().toString(); + final OntologyProperty property = properties.get(propertyId); + property.setOwners(List.of(owner)); + properties.update(propertyId, property); + } +} From 4e8ac213910ef7a350f0153ca2f9c49bb2670c04 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 17:34:05 -0800 Subject: [PATCH 193/203] List only the release members the caller may view, and count only those --- ...ogy-releases-seal-canonical-sql-members.md | 22 ++++++++- .../jdbi3/OntologyReleaseRepository.java | 43 +++++++++++++----- .../ontology/OntologyReleaseResource.java | 13 +++--- .../ontology/OntologyResourceAccess.java | 45 +++++++++++++++++++ .../jdbi3/OntologyReleaseCaptureTest.java | 2 +- 5 files changed, 105 insertions(+), 20 deletions(-) diff --git a/docs/decisions/2026-10-14-ontology-releases-seal-canonical-sql-members.md b/docs/decisions/2026-10-14-ontology-releases-seal-canonical-sql-members.md index 41ef9341b0bc..c4e5c9e5eb7e 100644 --- a/docs/decisions/2026-10-14-ontology-releases-seal-canonical-sql-members.md +++ b/docs/decisions/2026-10-14-ontology-releases-seal-canonical-sql-members.md @@ -1,9 +1,9 @@ # Ontology releases seal canonical SQL members - **Status:** Accepted -- **Revisions:** v1 2026-10-14 (initial); v10 2026-10-15 (single-ontology releases, captured comparison baseline, active-only projection); v11 2026-10-30 (SKOS, SKOS-XL and CSV export, export options and the SHACL gate); v12 2026-11-06 (50,000 members, batched capture, cached and unlocked reads); v13 2026-11-08 (account for parsed release cache heap) +- **Revisions:** v1 2026-10-14 (initial); v10 2026-10-15 (single-ontology releases, captured comparison baseline, active-only projection); v11 2026-10-30 (SKOS, SKOS-XL and CSV export, export options and the SHACL gate); v12 2026-11-06 (50,000 members, batched capture, cached and unlocked reads); v13 2026-11-08 (account for parsed release cache heap); v14 2026-12-05 (member listings keep viewable members) - **Deciders:** Harsha -- **Guard:** `OntologyReleaseManifestTest`, `OntologyReleaseDAOTest`, `OntologyReleaseCaptureTest`, `NativeOntologyCapacityPerfIT`, `OntologyWorkingStateTest`, `OntologyReleaseProjectionTest`, `OntologyStructureValidatorTest`, `OntologyReleaseComparisonTest`, `OntologyReleaseComparisonStorageTest`, `IndependentOntologyReleaseDiffIT`, `IndependentOntologyReleaseIT`, `IndependentOntologyReleaseExportIT`, `IndependentOntologyRetentionIT`, `OntologySkosProjectionTest`, `OntologyReleaseExporterTest`, `OntologyBoundAssetLinksTest`, `OntologyExportGateTest`, `IndependentOntologyReleaseExportFormatsIT`, `IndependentOntologyReleaseExportAssetsIT`, `IndependentOntologyReleaseExportGateIT` +- **Guard:** `OntologyReleaseManifestTest`, `OntologyReleaseDAOTest`, `OntologyReleaseCaptureTest`, `NativeOntologyCapacityPerfIT`, `OntologyWorkingStateTest`, `OntologyReleaseProjectionTest`, `OntologyStructureValidatorTest`, `OntologyReleaseComparisonTest`, `OntologyReleaseComparisonStorageTest`, `IndependentOntologyReleaseDiffIT`, `IndependentOntologyReleaseIT`, `IndependentOntologyReleaseMemberReadIT`, `IndependentOntologyReleaseExportIT`, `IndependentOntologyRetentionIT`, `OntologySkosProjectionTest`, `OntologyReleaseExporterTest`, `OntologyBoundAssetLinksTest`, `OntologyExportGateTest`, `IndependentOntologyReleaseExportFormatsIT`, `IndependentOntologyReleaseExportAssetsIT`, `IndependentOntologyReleaseExportGateIT` - **Related:** [Organizational ontology design](../plans/2026-10-14-organizational-ontology-design.md) ## Context @@ -182,3 +182,21 @@ that size is read and verified from SQL on every call. The v12 warm-read timings releases that fit this smaller payload budget; they do not describe larger uncached releases. `OntologyReleaseCaptureTest` verifies that a 23 MB release remains readable without staying cached on both MySQL and PostgreSQL, alongside cache reuse and authorization for smaller releases. + +## Amendment: a member listing keeps the members the caller may view (2026-12-05) + +`GET /v1/ontologyReleases/{id}/members/{kind}` answers with the members of that kind the caller may +view, decided per member as `GET .../members/{kind}/{memberId}` decides it (`ViewAll` on the member's +definition, loaded with the attributes a condition reads). A deny rule that covers one class or +property no longer refuses the whole kind. A caller who may not view the release itself still gets +403, and the by-id read of a member the caller may not view still gets 403. + +The page, its `after` cursor and `paging.total` are computed over the viewable members only, so +neither a short page, a cursor nor a count reveals a hidden member. The live definition lists keep +the total of every row and refill from following pages; a release is sealed and bounded to 50,000 +members, so each request scans the kind in key order once and counts the viewable ones. Whole-release +readers (`OntologyReleaseReader`: export, SPARQL, comparison, validation) are unchanged: they still +authorize every member and fail for a caller who may not view one, because a partial release would +produce a wrong result rather than a smaller one. + +`IndependentOntologyReleaseMemberReadIT` guards the listing. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReleaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReleaseRepository.java index 33a662a37bbf..18116b0abab4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReleaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReleaseRepository.java @@ -13,6 +13,7 @@ import java.util.UUID; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.Stream; import org.openmetadata.schema.EntityInterface; @@ -51,6 +52,7 @@ @Repository public final class OntologyReleaseRepository extends OntologyEntityRepository { + private static final int MEMBER_SCAN_BATCH = 1000; private static final String USER_APPROVAL_TASK = "userApprovalTask"; private static final String REVIEW_TASK_FIELDS = "assignees,reviewers,createdBy"; @@ -196,19 +198,40 @@ public OntologyReleaseMember getMember( return member; } - public ResultList listMembers( - final UUID releaseId, final MemberKind kind, final int limit, final String after) { + /** + * One page of the members the caller may view, and how many there are. The scan reads the kind + * in key order and keeps only viewable members, so neither the page, its cursor nor the total + * depends on a member the caller may not view. + */ + public ResultList listViewableMembers( + final UUID releaseId, + final MemberKind kind, + final int limit, + final String after, + final UnaryOperator> viewable) { final String cursor = after == null ? "" : UUID.fromString(RestUtil.decodeCursor(after)).toString(); - final List members = - daoCollection.ontologyReleaseDAO().listMembers(releaseId, kind.value(), cursor, limit + 1); - final List page = - List.copyOf(members.subList(0, Math.min(limit, members.size()))); + final List page = new ArrayList<>(); + int total = 0; + String scanned = ""; + List batch; + do { + batch = + daoCollection + .ontologyReleaseDAO() + .listMembers(releaseId, kind.value(), scanned, MEMBER_SCAN_BATCH); + for (final OntologyReleaseMember member : viewable.apply(batch)) { + total++; + if (page.size() <= limit && member.getMemberId().toString().compareTo(cursor) > 0) { + page.add(member); + } + } + scanned = batch.isEmpty() ? scanned : batch.getLast().getMemberId().toString(); + } while (batch.size() == MEMBER_SCAN_BATCH); + final List shown = + List.copyOf(page.subList(0, Math.min(limit, page.size()))); return new ResultList<>( - page, - null, - members.size() > limit ? page.getLast().getMemberId().toString() : null, - daoCollection.ontologyReleaseDAO().countMembers(releaseId, kind.value())); + shown, null, page.size() > limit ? shown.getLast().getMemberId().toString() : null, total); } @Override diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyReleaseResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyReleaseResource.java index 95bdd8dbb88d..a5b48bfe63f9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyReleaseResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyReleaseResource.java @@ -362,12 +362,11 @@ public ResultList listMembers( @QueryParam("limit") @DefaultValue("50") @Min(1) @Max(1000) final int limit, @QueryParam("after") final String after) { get(uriInfo, securityContext, id); - final ResultList members = - repository.listMembers(id, kind, limit, after); - OntologyResourceAccess.requireView( - authorizer, - securityContext, - members.getData().stream().map(OntologyReleaseReader::definition).toList()); - return members; + return repository.listViewableMembers( + id, + kind, + limit, + after, + batch -> OntologyResourceAccess.retainViewable(authorizer, securityContext, batch)); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResourceAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResourceAccess.java index 5c702fe0fd1d..8b2d2f675302 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResourceAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResourceAccess.java @@ -5,6 +5,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import java.util.Collection; +import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -20,10 +21,13 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.OntologyEntityRepository; +import org.openmetadata.service.ontology.OntologyReleaseReader; import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.ViewPermissionFilter; import org.openmetadata.service.security.policyevaluator.CreateResourceContext; import org.openmetadata.service.security.policyevaluator.OperationContext; import org.openmetadata.service.security.policyevaluator.ResourceContext; @@ -206,6 +210,47 @@ static void requireView( requireView(authorizer, context, batch, Entity.getEntityRepository(type))); } + /** The release members whose definitions the caller may view, as a by-id read would decide. */ + static List retainViewable( + final Authorizer authorizer, + final SecurityContext context, + final List members) { + final Set viewable = new HashSet<>(); + members.stream() + .collect( + Collectors.groupingBy( + member -> OntologyReleaseReader.definition(member).getEntityReference().getType())) + .forEach( + (type, batch) -> + viewable.addAll( + viewableIds(authorizer, context, batch, Entity.getEntityRepository(type)))); + return members.stream().filter(member -> viewable.contains(member.getMemberId())).toList(); + } + + private static > Set viewableIds( + final Authorizer authorizer, + final SecurityContext context, + final List members, + final EntityRepository repository) { + final List rows = + members.stream() + .map( + member -> + repository.getEntityClass().cast(OntologyReleaseReader.definition(member))) + .toList(); + repository.setFieldsInBulk(ResourceContext.authorizationFields(repository), rows); + return new ViewPermissionFilter(authorizer) + .retainPermitted( + context, + repository.getEntityType(), + repository, + rows, + List.of(MetadataOperation.VIEW_ALL)) + .stream() + .map(EntityInterface::getId) + .collect(Collectors.toSet()); + } + private static > void requireView( final Authorizer authorizer, final SecurityContext context, diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyReleaseCaptureTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyReleaseCaptureTest.java index 2b962adedb63..b2aeb3a9c98d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyReleaseCaptureTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyReleaseCaptureTest.java @@ -427,7 +427,7 @@ void captureIncludesAllPagesAndRepeatCaptureReturnsTheSameRelease(ConnectionType 101, fixture .releases - .listMembers(first.getId(), MemberKind.CONCEPT, 200, null) + .listViewableMembers(first.getId(), MemberKind.CONCEPT, 200, null, all -> all) .getData() .size()); assertEquals(first.getId(), second.getId()); From efa2376ea5c4632dbd005b4cf6fc1a65fdc843a2 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 18:01:10 -0800 Subject: [PATCH 194/203] Move the declined-definition DAO test to the integration tests, as upstream moved the container tests Upstream removed the service module's OntologyTestDatabase and runs container tests against the suite's database server (#38626). The test now takes the lane's dialect instead of parameterising over both. --- ...inding-says-how-its-rows-become-records.md | 2 +- ...ned-definition-is-remembered-by-content.md | 2 +- .../OntologyDeclinedDefinitionDaoIT.java | 43 ++++++++----------- 3 files changed, 21 insertions(+), 26 deletions(-) rename openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDaoTest.java => openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyDeclinedDefinitionDaoIT.java (84%) diff --git a/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md b/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md index 76ac2bd02e57..c8365dd4e509 100644 --- a/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md +++ b/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-11-21 (initial) · v2 2026-11-22 (a row filter value is parsed as the data type of its column) - **Deciders:** Ontology Studio maintainers -- **Guard:** `OntologyBindingRulesTest`, `OntologyMappingHealthRulesTest`, `OntologyConceptBindingDaoTest`, `OntologyReleaseManifestTest#theMappingSourceOfAnOntologyIsNotCapturedDefinitionContent`, `IndependentOntologyTableBindingIT`, `IndependentOntologyMappingSourceIT`, `IndependentOntologyMappingHealthIT` +- **Guard:** `OntologyBindingRulesTest`, `OntologyMappingHealthRulesTest`, `OntologyConceptBindingDaoIT`, `OntologyReleaseManifestTest#theMappingSourceOfAnOntologyIsNotCapturedDefinitionContent`, `IndependentOntologyTableBindingIT`, `IndependentOntologyMappingSourceIT`, `IndependentOntologyMappingHealthIT` - **Related:** ADR:2026-10-19-native-concept-bindings-remain-operational-metadata (amended by this record), ADR:2026-10-14-ontology-releases-seal-canonical-sql-members diff --git a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md index 7cf2bd89456d..cedc1b46eedb 100644 --- a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md +++ b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md @@ -4,7 +4,7 @@ - **Revisions:** v1 2026-11-22 (initial); v2 2026-11-26 (canonical form stated in full and made stable for set order, empty lists and server-derived fields; narrowing checks every kept operation; a permanent delete removes the rows; declining asks the draft read right); v3 2026-12-05 (a table binding and a shape can be declined); v4 2026-12-05 (a binding is keyed by its table, role, key and row filter, not its columns) - **Deciders:** Ontology maintainers - **Guard:** `OntologyDefinitionDigestTest`, `OntologyDeclinedDefinitionsTest`, - `OntologyDeclinedDefinitionDaoTest`, `OntologyDraftNarrowingTest`, + `OntologyDeclinedDefinitionDaoIT`, `OntologyDraftNarrowingTest`, `OntologyDeclinedDefinitionRightsTest`, `OntologyDeclinedBindingShapeKeysTest`, `OntologyDeclinedDefinitionIT`, `OntologyDeclinedBindingShapeIT`, `OntologyDeclinedDefinitionReadIT` and `OntologyRolesMigrationIT` diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDaoTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyDeclinedDefinitionDaoIT.java similarity index 84% rename from openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDaoTest.java rename to openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyDeclinedDefinitionDaoIT.java index 9be98b379d5f..97f55354c29d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDaoTest.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyDeclinedDefinitionDaoIT.java @@ -11,38 +11,39 @@ * limitations under the License. */ -package org.openmetadata.service.jdbi3; +package org.openmetadata.it.tests.ontology; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.openmetadata.service.jdbi3.OntologyTestDatabase.migrate; -import static org.openmetadata.service.jdbi3.OntologyTestDatabase.withDatabase; +import static org.openmetadata.it.tests.ontology.OntologyTestDatabase.migrate; +import static org.openmetadata.it.tests.ontology.OntologyTestDatabase.withDatabase; import java.time.Clock; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.commons.codec.digest.DigestUtils; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.ScratchDatabase; import org.openmetadata.schema.type.OntologyDeclinedDefinition; import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.jdbi3.OntologyDeclinedDefinitionDAO.StoredDeclinedDefinition; import org.openmetadata.service.jdbi3.locator.ConnectionType; import org.openmetadata.service.ontology.OntologyDeclinedDefinitions; -class OntologyDeclinedDefinitionDaoTest { +@Execution(ExecutionMode.CONCURRENT) +class OntologyDeclinedDefinitionDaoIT { private static final UUID ONTOLOGY = new UUID(0xb1, 0); private static final UUID OTHER_ONTOLOGY = new UUID(0xb2, 0); private static final String IRI = "https://example.org/sales/Order"; - @ParameterizedTest - @EnumSource( - value = ConnectionType.class, - names = {"MYSQL", "POSTGRES"}) - void theMigrationRunsTwiceAndLeavesTheRowsItHolds(final ConnectionType dialect) { + @Test + void theMigrationRunsTwiceAndLeavesTheRowsItHolds() { + final ConnectionType dialect = ScratchDatabase.dialect(); withDatabase( - dialect, handle -> { handle.execute("DROP TABLE IF EXISTS ontology_declined_definition"); migrate(handle, dialect); @@ -55,13 +56,10 @@ void theMigrationRunsTwiceAndLeavesTheRowsItHolds(final ConnectionType dialect) }); } - @ParameterizedTest - @EnumSource( - value = ConnectionType.class, - names = {"MYSQL", "POSTGRES"}) - void aDefinitionDeclinedTwiceKeepsItsFirstDecision(final ConnectionType dialect) { + @Test + void aDefinitionDeclinedTwiceKeepsItsFirstDecision() { + final ConnectionType dialect = ScratchDatabase.dialect(); withDatabase( - dialect, handle -> { handle.execute("DROP TABLE IF EXISTS ontology_declined_definition"); migrate(handle, dialect); @@ -87,13 +85,10 @@ void aDefinitionDeclinedTwiceKeepsItsFirstDecision(final ConnectionType dialect) }); } - @ParameterizedTest - @EnumSource( - value = ConnectionType.class, - names = {"MYSQL", "POSTGRES"}) - void pagesRecordsInTheOrderTheyWereDeclinedEvenWhenTheyShareATime(final ConnectionType dialect) { + @Test + void pagesRecordsInTheOrderTheyWereDeclinedEvenWhenTheyShareATime() { + final ConnectionType dialect = ScratchDatabase.dialect(); withDatabase( - dialect, handle -> { handle.execute("DROP TABLE IF EXISTS ontology_declined_definition"); migrate(handle, dialect); From 831fbb12bd4e74b76a51f78b8bd48a3dae257d52 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 18:14:32 -0800 Subject: [PATCH 195/203] Update the constraint suggestion test to upstream's patch overload Upstream's TaskWorkflowHandler.saveChange calls patch without the impersonatedBy argument, which the repository now reads from ImpersonationContext. The test verified the six-argument form. --- .../tasks/TableConstraintSuggestionTest.java | 28 ++++++++----------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java index eafa20599564..b0e64c8b58c3 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -266,8 +266,7 @@ void applyingASuggestion_addsTheConstraintToTheTableAsTheApprover() throws Excep invokeApplySuggestion(task(Entity.TABLE, foreignKey), orders, repository, "approver"); ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); - verify(repository) - .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any(), (String) any()); + verify(repository).patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any()); String operations = patch.getValue().toJsonArray().toString(); assertTrue(operations.contains("\"op\":\"add\""), operations); assertTrue(operations.contains("\"path\":\"/tableConstraints\""), operations); @@ -287,8 +286,7 @@ void applyingASuggestionTheTableAlreadyHas_writesNothing() throws Exception { repository, "approver"); - verify(repository, never()) - .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + verify(repository, never()).patch(any(), any(UUID.class), anyString(), any(), any()); assertEquals(1, orders.getTableConstraints().size()); } @@ -350,7 +348,7 @@ void aFailureWhileApplying_escapesWithItsCause() throws Exception { EntityRepository repository = mock(EntityRepository.class); doThrow(new IllegalStateException("write failed")) .when(repository) - .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + .patch(any(), any(UUID.class), anyString(), any(), any()); Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); java.lang.reflect.InvocationTargetException thrown = @@ -371,7 +369,7 @@ void aTaskOfAnotherTypeCarryingAConstraintPayload_getsNoCheckNoWriteAndNoRethrow EntityRepository repository = mock(EntityRepository.class); doThrow(new IllegalStateException("write failed")) .when(repository) - .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + .patch(any(), any(UUID.class), anyString(), any(), any()); Task applied = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))).withType(otherType); @@ -379,8 +377,7 @@ void aTaskOfAnotherTypeCarryingAConstraintPayload_getsNoCheckNoWriteAndNoRethrow assertDoesNotThrow(() -> TableConstraintSuggestion.require(unchecked)); assertDoesNotThrow(() -> TableConstraintSuggestion.requireToApply(unchecked, null, null)); assertDoesNotThrow(() -> invokeApplySuggestion(applied, orders, repository, "approver")); - verify(repository, never()) - .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + verify(repository, never()).patch(any(), any(UUID.class), anyString(), any(), any()); Task suggestion = applied.withType(TaskEntityType.Suggestion); java.lang.reflect.InvocationTargetException thrown = @@ -704,7 +701,7 @@ void approving_underAnyForm_addsTheConstraintAndMakesNoOtherChange(String formNa ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); verify(repository, times(1)) - .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any(), (String) any()); + .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any()); assertEquals( "[{\"op\":\"add\",\"path\":\"/tableConstraints\",\"value\":[{\"constraintType\":\"UNIQUE\"," + "\"columns\":[\"email\"]}]}]", @@ -721,8 +718,7 @@ void approving_withTheDefaultForm_addsTheSameConstraint() throws Exception { task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), true, repository); verify(repository, times(1)) - .patch( - any(), eq(orders.getId()), eq("approver"), any(JsonPatch.class), any(), (String) any()); + .patch(any(), eq(orders.getId()), eq("approver"), any(JsonPatch.class), any()); } @ParameterizedTest @@ -738,8 +734,7 @@ void rejecting_underAnyForm_writesNothing(String formName) throws Exception { invokeApplyEntityChanges( task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), false, repository); - verify(repository, never()) - .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + verify(repository, never()).patch(any(), any(UUID.class), anyString(), any(), any()); } @Test @@ -756,8 +751,7 @@ void rejecting_underAFormWhoseRejectActionAppliesTheSuggestion_writesNothing() t invokeApplyEntityChanges( task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), false, repository); - verify(repository, never()) - .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + verify(repository, never()).patch(any(), any(UUID.class), anyString(), any(), any()); } @Test @@ -765,7 +759,7 @@ void aFailureWhileApprovingUnderAnyForm_escapesSoTheTaskStaysOpen() throws Excep boundTo("approval handler with no approve actions"); doThrow(new IllegalStateException("write failed")) .when(tableRepository) - .patch(any(), any(UUID.class), anyString(), any(), any(), (String) any()); + .patch(any(), any(UUID.class), anyString(), any(), any()); java.lang.reflect.InvocationTargetException thrown = assertThrows( @@ -786,7 +780,7 @@ void aDescriptionSuggestionUnderTheDefaultForm_isStillAppliedByTheSameCall() thr invokeApplyEntityChanges(descriptionTask(), true, tableRepository); verify(tableRepository, times(1)) - .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any(), (String) any()); + .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any()); assertTrue(patch.getValue().toJsonArray().toString().contains("/description")); } From 089dbb37c16548971e9e078339c6a4212f012964 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 18:14:37 -0800 Subject: [PATCH 196/203] Describe the shape class and the new predicates in the RDF ontology Upstream's RdfOntologyDescriptionContractTest requires every projected class and stored predicate to carry a comment and every shared predicate to list each class it is used on. The shape class, the shape fields, mappingSource and isDisplayName now satisfy it. --- .../resources/rdf/ontology/openmetadata.ttl | 418 ++++++++---------- 1 file changed, 193 insertions(+), 225 deletions(-) diff --git a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl index 291f0139e5bd..021936d80777 100644 --- a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl +++ b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl @@ -930,6 +930,11 @@ om:OntologyRelease a owl:Class ; rdfs:comment "A sealed, immutable version of an ontology's content, reviewed through the approval workflow before it is activated." ; rdfs:subClassOf om:Entity . +om:OntologyShape a owl:Class ; + rdfs:label "Ontology Shape" ; + rdfs:comment "A set of constraints on the properties of one class of an ontology, held with the ontology and kept out of its releases." ; + rdfs:subClassOf om:Entity . + om:Page a owl:Class ; rdfs:label "Page" ; rdfs:comment "A knowledge page in the Knowledge Center: an article or quick link, possibly with sub-pages." ; @@ -2533,86 +2538,71 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "description" ; rdfs:comment "The description written for the entity in OpenMetadata, usually Markdown. On a tag node it is the description carried by a tag label, and on om:LineageDetails it describes the lineage edge. Read it for business meaning when names are ambiguous." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:LineageDetails, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, - om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease, om:Page, om:Persona, om:Pipeline, - om:PipelineService, om:Policy, om:PromptTemplate, om:Query, - om:RelationshipType, om:Report, om:Role, om:SearchIndex, - om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, - om:StoredProcedure, om:Table, om:Tag, om:Team, - om:TestConnectionDefinition, om:Topic, om:Type, om:User, - om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:LineageDetails, om:MLModel, om:MLModelService, om:McpServer, + om:McpService, om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, + om:NotificationTemplate, om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, + om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, + om:Persona, om:Pipeline, om:PipelineService, om:Policy, om:PromptTemplate, om:Query, + om:RelationshipType, om:Report, om:Role, om:SearchIndex, om:SearchService, + om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, om:Table, om:Tag, + om:Team, om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "hasVersion" ; rdfs:comment "The entity's OpenMetadata metadata version, a decimal that grows with every change (0.1, 0.2, then 1.0 after a major change). dcat:version carries the same number." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Team, om:TestConnectionDefinition, - om:Topic, om:Type, om:User, om:Workflow, - om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Team, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "modified" ; rdfs:comment "When the entity last changed in OpenMetadata, as xsd:dateTime. On om:LineageDetails it is the lineage edge's last update, in Unix epoch milliseconds (xsd:long)." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:LineageDetails, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, - om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease, om:Page, om:Persona, om:Pipeline, - om:PipelineService, om:Policy, om:PromptTemplate, om:Query, - om:RelationshipType, om:Report, om:Role, om:SearchIndex, - om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, - om:StoredProcedure, om:Table, om:Tag, om:Task, - om:Team, om:TestCase, om:TestConnectionDefinition, om:Topic, - om:Type, om:User, om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:LineageDetails, om:MLModel, om:MLModelService, om:McpServer, + om:McpService, om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, + om:NotificationTemplate, om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, + om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, + om:Persona, om:Pipeline, om:PipelineService, om:Policy, om:PromptTemplate, om:Query, + om:RelationshipType, om:Report, om:Role, om:SearchIndex, om:SearchService, + om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, om:Table, om:Tag, + om:Task, om:Team, om:TestCase, om:TestConnectionDefinition, om:Topic, om:Type, om:User, + om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "publisher" ; rdfs:comment "Who provides the definition (the provider field): system for definitions OpenMetadata ships and seeds, user for ones people created." ; - schema:domainIncludes om:App, om:Bot, om:Classification, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Policy, om:RelationshipType, om:Role, om:Tag . + schema:domainIncludes om:App, om:Bot, om:Classification, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, + om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, + om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, + om:OntologyRelease, om:OntologyShape, om:Policy, om:RelationshipType, om:Role, om:Tag . a rdf:Property ; om:projectionStatus om:Stored ; @@ -2639,27 +2629,22 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "label" ; rdfs:comment "The entity's name (the name field), the last segment of its fully qualified name. Use om:fullyQualifiedName to identify an entity exactly and skos:prefLabel for the name people see." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Column, om:Container, om:ContextFile, - om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, - om:DashboardService, om:DataContract, om:DataProduct, om:Database, - om:DatabaseSchema, om:DatabaseService, om:Directory, om:Document, - om:Domain, om:DriveService, om:File, om:Folder, - om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, - om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, - om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease, om:Page, om:Persona, om:Pipeline, - om:PipelineService, om:Policy, om:PromptTemplate, om:Query, - om:RelationshipType, om:Report, om:Role, om:SearchIndex, - om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, - om:StoredProcedure, om:Table, om:Tag, om:Team, - om:TestConnectionDefinition, om:TestDefinition, om:TestResultValue, om:TestSuite, - om:Topic, om:Type, - om:User, om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Column, om:Container, + om:ContextFile, om:ContextFileContent, om:ContextMemory, om:Dashboard, + om:DashboardDataModel, om:DashboardService, om:DataContract, om:DataProduct, om:Database, + om:DatabaseSchema, om:DatabaseService, om:Directory, om:Document, om:Domain, + om:DriveService, om:File, om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, + om:LLMModel, om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, + om:McpServer, om:McpService, om:MessagingService, om:MetadataService, om:Metric, + om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, + om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, + om:OntologyShape, om:Page, om:Persona, om:Pipeline, om:PipelineService, om:Policy, + om:PromptTemplate, om:Query, om:RelationshipType, om:Report, om:Role, om:SearchIndex, + om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, + om:Table, om:Tag, om:Team, om:TestConnectionDefinition, om:TestDefinition, + om:TestResultValue, om:TestSuite, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; @@ -2707,26 +2692,21 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "prefLabel" ; rdfs:comment "The entity's display name (displayName), the name shown in the UI. It may be absent or differ from rdfs:label." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Team, om:TestConnectionDefinition, - om:Topic, om:Type, om:User, om:Workflow, - om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Team, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; @@ -2744,26 +2724,21 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "version" ; rdfs:comment "The entity's OpenMetadata metadata version as a number, the same value as dct:hasVersion." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Task, om:Team, - om:TestCase, om:TestConnectionDefinition, om:Topic, om:Type, - om:User, om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Task, om:Team, om:TestCase, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:InferenceOnly ; @@ -2814,26 +2789,21 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "invalidatedAtTime" ; rdfs:comment "Present only on a soft-deleted entity: its last update time, which is when it was deleted." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Task, om:Team, - om:TestCase, om:TestConnectionDefinition, om:Topic, om:Type, - om:User, om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Task, om:Team, om:TestCase, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; @@ -2862,24 +2832,20 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "wasAttributedTo" ; rdfs:comment "An owner of the entity, the PROV-O mirror of om:hasOwner: a user or team that owns it." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Chart, om:Classification, - om:Container, om:ContextFile, om:ContextMemory, om:Dashboard, - om:DashboardDataModel, om:DashboardService, om:DataContract, om:DataProduct, - om:Database, om:DatabaseSchema, om:DatabaseService, om:Directory, - om:Domain, om:DriveService, om:File, om:Folder, - om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, - om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Pipeline, om:PipelineService, om:Policy, - om:PromptTemplate, om:Query, om:RelationshipType, om:Report, - om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, - om:StorageService, om:StoredProcedure, om:Table, om:Tag, - om:Team, om:TestConnectionDefinition, om:Topic, om:Workflow, - om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Chart, om:Classification, om:Container, om:ContextFile, om:ContextMemory, + om:Dashboard, om:DashboardDataModel, om:DashboardService, om:DataContract, om:DataProduct, + om:Database, om:DatabaseSchema, om:DatabaseService, om:Directory, om:Domain, + om:DriveService, om:File, om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, + om:LLMModel, om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, + om:McpServer, om:McpService, om:MessagingService, om:MetadataService, om:Metric, + om:MetricGroup, om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, + om:StoredProcedure, om:Table, om:Tag, om:Team, om:TestConnectionDefinition, om:Topic, + om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; @@ -3161,15 +3127,24 @@ om:axiomType a rdf:Property ; om:constraints a rdf:Property ; om:projectionStatus om:Stored ; - rdfs:label "constraints" . + rdfs:label "constraints" ; + rdfs:comment "Constraints a shape places on the properties of its target class, in authored order. Set on om:OntologyShape. The value is the field's JSON, serialized as a string." ; + rdfs:domain om:OntologyShape ; + rdfs:range xsd:string . om:severity a rdf:Property ; om:projectionStatus om:Stored ; - rdfs:label "severity" . + rdfs:label "severity" ; + rdfs:comment "How serious a violation of a shape is. Set on om:OntologyShape." ; + rdfs:domain om:OntologyShape ; + rdfs:range xsd:string . om:targetConcept a rdf:Property ; om:projectionStatus om:Stored ; - rdfs:label "targetConcept" . + rdfs:label "targetConcept" ; + rdfs:comment "Full IRI of the class a shape applies to. Set on om:OntologyShape." ; + rdfs:domain om:OntologyShape ; + rdfs:range xsd:string . om:baseModel a rdf:Property ; om:projectionStatus om:Stored ; @@ -4595,23 +4570,19 @@ om:impersonatedBy a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "impersonatedBy" ; rdfs:comment "The bot that made the entity's last change on behalf of a user, when that change was impersonated." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:App, om:AppMarketPlaceDefinition, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextMemory, om:Dashboard, - om:DashboardDataModel, om:DashboardService, om:DataContract, om:DataProduct, - om:Database, om:DatabaseSchema, om:DatabaseService, om:Directory, - om:Document, om:Domain, om:DriveService, om:File, - om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:App, + om:AppMarketPlaceDefinition, om:Bot, om:Chart, om:Classification, om:Container, + om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, om:DataContract, + om:DataProduct, om:Database, om:DatabaseSchema, om:DatabaseService, om:Directory, + om:Document, om:Domain, om:DriveService, om:File, om:Glossary, om:GlossaryTerm, + om:IngestionPipeline, om:LLMModel, om:LearningResource, om:MLModel, om:MLModelService, + om:McpServer, om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, om:OntologyConcept, - om:OntologyProperty, om:OntologyRelease, om:Page, om:Persona, - om:Pipeline, om:PipelineService, om:Policy, om:Query, - om:RelationshipType, om:Report, om:Role, om:SearchIndex, - om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, - om:StoredProcedure, om:Table, om:Tag, om:Team, - om:TestConnectionDefinition, om:Topic, om:Type, om:User, - om:Workflow, om:Worksheet ; + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:Query, om:RelationshipType, om:Report, om:Role, + om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, + om:StoredProcedure, om:Table, om:Tag, om:Team, om:TestConnectionDefinition, om:Topic, + om:Type, om:User, om:Workflow, om:Worksheet ; rdfs:range xsd:string . om:includeRedacted a rdf:Property ; @@ -4625,26 +4596,21 @@ om:incrementalChangeDescription a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "incrementalChangeDescription" ; rdfs:comment "JSON of the change that produced the entity's current version: fields added, updated and deleted. It is one step, not the history; the entity version APIs keep the history." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Team, om:TestConnectionDefinition, - om:Topic, om:Type, om:User, om:Workflow, - om:Worksheet ; + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Team, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet ; rdfs:range xsd:string . om:index a rdf:Property ; @@ -4743,24 +4709,20 @@ om:isDeleted a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "isDeleted" ; rdfs:comment "True when the entity is soft-deleted (the deleted field)." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:Database, om:DatabaseSchema, om:DatabaseService, - om:Directory, om:DriveService, om:File, om:Folder, - om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, - om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, - om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease, om:Pipeline, om:PipelineService, om:Policy, - om:PromptTemplate, om:RelationshipType, om:Report, om:Role, - om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, - om:StorageService, om:StoredProcedure, om:Table, om:Tag, - om:Team, om:TestConnectionDefinition, om:Topic, om:User, - om:Workflow, om:Worksheet ; + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:Database, om:DatabaseSchema, om:DatabaseService, + om:Directory, om:DriveService, om:File, om:Folder, om:Glossary, om:GlossaryTerm, + om:IngestionPipeline, om:LLMModel, om:LLMService, om:LearningResource, om:MLModel, + om:MLModelService, om:McpServer, om:McpService, om:MessagingService, om:MetadataService, + om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, + om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, + om:OntologyShape, om:Pipeline, om:PipelineService, om:Policy, om:PromptTemplate, + om:RelationshipType, om:Report, om:Role, om:SearchIndex, om:SearchService, + om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, om:Table, om:Tag, + om:Team, om:TestConnectionDefinition, om:Topic, om:User, om:Workflow, om:Worksheet ; rdfs:range xsd:boolean . om:isDeployed a rdf:Property ; @@ -4978,7 +4940,10 @@ om:manifest a rdf:Property ; om:mappingSource a rdf:Property ; om:projectionStatus om:Stored ; - rdfs:label "mappingSource" . + rdfs:label "mappingSource" ; + rdfs:comment "The one database whose tables the classes of an ontology bind. Set on om:Ontology. The value is the reference's JSON, serialized as a string." ; + rdfs:domain om:Ontology ; + rdfs:range xsd:string . om:maximumMessageSize a rdf:Property ; om:projectionStatus om:Stored ; @@ -5177,8 +5142,8 @@ om:ontology a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "ontology" ; rdfs:comment "The ontology that owns a concept, property, axiom, change set or release, as the reference's JSON text." ; - schema:domainIncludes om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease ; + schema:domainIncludes om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, + om:OntologyShape ; rdfs:range xsd:string . om:operations a rdf:Property ; @@ -6590,7 +6555,10 @@ om:isIdentifier a rdf:Property ; om:isDisplayName a rdf:Property ; om:projectionStatus om:Stored ; - rdfs:label "isDisplayName" . + rdfs:label "isDisplayName" ; + rdfs:comment "Whether a DATA property supplies the display name of its class. Set on om:OntologyProperty." ; + rdfs:domain om:OntologyProperty ; + rdfs:range xsd:boolean . om:abstract a rdf:Property ; om:projectionStatus om:Stored ; From 97af2580e99fe10303eaa9310c1bf63d856fb3ee Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 18:20:53 -0800 Subject: [PATCH 197/203] Pass a StoredBinding where upstream's served-bindings IT upserts a binding The binding DAO's upsert takes a StoredBinding that carries the role, subject key and row filter; the IT upstream added called the five-argument form. --- .../jdbi3/OntologyServedBindingsStorageIT.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/service/jdbi3/OntologyServedBindingsStorageIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/service/jdbi3/OntologyServedBindingsStorageIT.java index 426ad6c65969..76eea806c2ea 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/service/jdbi3/OntologyServedBindingsStorageIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/service/jdbi3/OntologyServedBindingsStorageIT.java @@ -36,6 +36,7 @@ import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BoundAsset; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; import org.openmetadata.service.jdbi3.locator.ConnectionType; import org.openmetadata.service.ontology.OntologyConceptBindingService; import org.openmetadata.service.rdf.RdfLiveWrite; @@ -275,6 +276,14 @@ private static void bind( Entity.getCollectionDAO() .ontologyConceptBindingDAO() .upsert( - concept.getId(), asset, type.value(), "hash" + asset, JsonUtils.pojoToJson(columns)); + new StoredBinding( + concept.getId().toString(), + asset.toString(), + type.value(), + "hash" + asset, + JsonUtils.pojoToJson(columns), + null, + null, + null)); } } From 8bdc9383fcdffc105fd95fd512ad43026c537a91 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 18:32:35 -0800 Subject: [PATCH 198/203] Adapt the statement-count and assignee ITs to upstream's task and table reads Upstream's suggestion task workflow now assigns platform admins when no owner resolves, and its table reads run three to six more statements that do not grow with the data. The ITs pin both. --- .../it/tests/IndependentOntologyMappingAdviceCountIT.java | 4 ++-- .../openmetadata/it/tests/OntologyShapeCheckReadsIT.java | 4 ++-- .../openmetadata/it/tests/OntologyShapeProposalAskIT.java | 2 +- .../openmetadata/it/tests/OntologyTableMappingsIT.java | 8 ++++---- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java index f06c8d170578..b34a4ff5cdfb 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java @@ -49,8 +49,8 @@ class IndependentOntologyMappingAdviceCountIT extends BaseOntologyApprovalIT { private static final int FULL_PAGE = 100; private static final int SMALL_PAGE = 5; - private static final int SELECTS_WITH_IDENTITY_ON_PAGE = 50; - private static final int SELECTS_WITH_IDENTITY_OFF_PAGE = 50; + private static final int SELECTS_WITH_IDENTITY_ON_PAGE = 53; + private static final int SELECTS_WITH_IDENTITY_OFF_PAGE = 53; @Test void aPageOfOneHundredBindingsRunsNoMoreStatementsThanAPageOfFive(final TestNamespace ns) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index 509d6f41c66c..6390155c17d4 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -110,9 +110,9 @@ class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { " lock in share mode"); /** Every statement of one read of the draft, as an administrator, and of the active release. */ - private static final int DRAFT_STATEMENTS = 48; + private static final int DRAFT_STATEMENTS = 53; - private static final int RELEASE_STATEMENTS = 56; + private static final int RELEASE_STATEMENTS = 62; /** * The same reads when the identity binding of every class a part names has a row filter. The diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java index 5759f0a184ab..37a41af64da5 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java @@ -219,7 +219,7 @@ void noTableOwner(final TestNamespace ns) { release(ns, ontology); final OntologyConcept account = fixture.type("Account"); for (final JsonNode task : openTasks(account)) { - assertEquals(List.of(), assignees(task)); + assertEquals(List.of("admin"), assignees(task)); } final EntityReference ontologyOwner = diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java index 1ddb3d748250..8bfee138c1b0 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java @@ -668,10 +668,10 @@ void aVersionOf300ClassesAndFilteredBindingsCostsTheSameStatementsAsOneOfThree( read("admin", ontology, null).classes().stream() .mapToInt(type -> type.tables().size()) .sum()); - assertEquals(42, threeRelease); - assertEquals(43, threeDraft); - assertEquals(42, release); - assertEquals(43, draft); + assertEquals(45, threeRelease); + assertEquals(46, threeDraft); + assertEquals(45, release); + assertEquals(46, draft); } private static int statements(final Ontology ontology, final OntologyStatementVersion version) { From 1b0765358eada81fd6ad7f49ece0fa84edf85c5b Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 18:39:57 -0800 Subject: [PATCH 199/203] Pin one more statement for reading accepted proposals after upstream's test-case read change --- .../org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java index 6390155c17d4..3f9d492ed286 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -373,7 +373,7 @@ void theProposalsOfOneCheckAndOfFortyAreReadInTheSameStatementsWhetherProposedOr assertEquals(counts.getFirst(), counts.get(1), counts.toString()); assertEquals(counts.get(2), counts.get(3), counts.toString()); - assertEquals(List.of(5, 5, 32, 32), counts); + assertEquals(List.of(5, 5, 33, 33), counts); } /** From c17e917fcec74ba690a66323448d1adbbc64ca9f Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Sat, 5 Dec 2026 19:53:22 -0800 Subject: [PATCH 200/203] Merge the two mocks of the task payload fields in the task tab test Upstream's test mocks the edit form as a comment field, and this branch's test mocks it as a button that submits a filled payload. The later jest.mock replaced the earlier one, so upstream's comment test lost its field. One mock now serves both. --- .../TaskTab/TaskTabNew.component.test.tsx | 40 ++++++------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx index 3c2ff9fa2a11..97d7dad046c0 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx @@ -466,8 +466,11 @@ jest.mock( } ); -// The edit modal's form (the one with `onChange`) as a plain comment field the -// tests can type in; the read-only payload details render for real. +// A transition form's data, as a person fills it in. While it is set, the edit +// modal's form (the one with `onChange`) is one button that submits it; otherwise +// that form is a plain comment field the tests can type in. The read-only +// payload details render for real. +let mockFilledPayload: Record | undefined; jest.mock('../../../../pages/TasksPage/shared/TaskPayloadSchemaFields', () => { const Actual = jest.requireActual( '../../../../pages/TasksPage/shared/TaskPayloadSchemaFields' @@ -479,7 +482,13 @@ jest.mock('../../../../pages/TasksPage/shared/TaskPayloadSchemaFields', () => { payload?: Record; onChange?: (payload: Record) => void; }) => - props.onChange ? ( + mockFilledPayload && props.onChange ? ( + + ) : props.onChange ? (