Repository navigation
Conversation
42e007b to
71db97f
Compare
60f62c4 to
1b36dc0
Compare
🔍 Adversarial Review — PR #4SummarySolid feature with thorough test coverage, but contains a confirmed race condition between Phase 1 and Phase 2 of 🐛 Bugs & Issues1. Phase 2 overwrites Phase 1 normalization for HTTP/HTTPS variants (Confirmed) When a schema declares
Reproduced locally with rdflib 7.x: from rdflib import Graph, Namespace, URIRef
g = Graph()
g.bind('schema', Namespace('http://schema.org/')) # metamodel
g.namespace_manager.bind('sdo', URIRef('https://schema.org/')) # user
# Phase 1
g.bind('schema', Namespace('https://schema.org/'), override=True, replace=True)
# → schema: https://schema.org/ ✅, schema1: http://schema.org/ (orphan)
# Phase 2
g.bind('schema', Namespace('http://schema.org/'), override=True, replace=True)
# → schema: http://schema.org/ ❌ (HTTPS binding silently lost!)Fix: Phase 2 should check whether # In Phase 2, before rebinding:
current_ns_for_std = dict(graph.namespaces()).get(std_pfx)
if current_ns_for_std and str(current_ns_for_std) != ns_str:
continue # std_pfx already claimed by Phase 1 for a different URI2. The test asserts
|
| PR #1 | PR #4 | |
|---|---|---|
| Approach | Dynamic: {str(ns): str(pfx) for pfx, ns in RdfGraph().namespaces()} |
Static: MappingProxyType({...}) with ~30 entries |
| rdflib dependency | Changes with rdflib version | Frozen, version-independent |
| HTTP/HTTPS variants | Only what rdflib provides | Explicitly includes both |
PR #4's static approach is explicitly designed to solve a problem with PR #1's dynamic approach (rdflib defaults changed between 6.x and 7.x). These will conflict on merge. Recommendation: merge PR #4 first, or rebase PR #1 to use PR #4's static map.
4. Cross-PR conflict — flag forwarding in jsonldgen.py
PR #4 forwards both normalize_prefixes AND deterministic to the embedded ContextGenerator:
for flag in ("normalize_prefixes", "deterministic"):
if hasattr(self, flag):
context_kwargs.setdefault(flag, getattr(self, flag))PR #1 adds deterministic handling in a different location (post-serialization in end_schema). PR #4's forwarding of deterministic creates a dependency on PR #1's field existing. The hasattr guard prevents a crash, but semantically PR #4 shouldn't forward a flag it doesn't define. Either:
- Remove
"deterministic"from the forwarding loop (PR feat(generators): add --normalize-prefixes for conventional prefix names in generated artifacts #4 doesn't own this flag), or - Document the intentional coupling with PR feat(generators): add --deterministic flag with hybrid RDFC-1.0 + rdflib serialization #1 and establish merge order
5. PR title says fix: but commit says feat: — which is it?
The commit message uses feat(generators): while the PR title uses fix(generators):. This is a new opt-in flag, which is a feature — feat: is correct per conventional commits.
6. Static map maintenance burden
The _WELL_KNOWN_PREFIX_MAP needs manual updates when rdflib adds new curated defaults. The test_matches_rdflib_defaults test catches additions but not removals. Consider adding a reverse check: entries in the static map that are NOT in rdflib's defaults could indicate stale entries.
🧪 Test Coverage Assessment
Strong coverage (18 tests across 7 classes):
- ✅ OWL, SHACL, JSON-LD context normalization (sdo→schema, dce→dc)
- ✅ HTTP/HTTPS schema.org variants
- ✅ Collision detection with warnings (caplog)
- ✅ Cross-generator consistency
- ✅ Static map integrity and copy safety
- ✅ JSONLDGenerator flag forwarding
- ✅ Flag-off backward compatibility
Gaps:
- ❌ No test for
normalize_prefixes+exclude_importsinteraction - ❌ No test for empty schema (zero prefixes) — is
_prefix_remap.clear()safe? - ❌ No test that explicitly sets up both HTTP and HTTPS runtime bindings to exercise Phase 2 overwrite (the scenario from Bug feat(generators): add --deterministic flag with hybrid RDFC-1.0 + rdflib serialization #1)
- ❌ No test for
add_prefixbeing called before__post_init__completes (defensive, but_prefix_remapaccess would crash) - ❌ CURIE remapping test (
test_normalize_prefixes_curie_remapping) only checks thatPerson @idstarts withschema:— doesn't verifyfull_nameslot's@idusesschema:nameinstead ofsdo:name
📋 Fix Plan
- Fix Phase 2 overwrite bug — add a graph-binding check before rebinding in Phase 2 to prevent overwriting Phase 1's normalization
- Add regression test — explicitly set up a graph with both
schema: http://schema.org/andsdo: https://schema.org/, run normalize, and assert the HTTPS binding survives - Remove
"deterministic"from forwarding loop — or gate it behindhasattronly (already done) but add a comment explaining the cross-PR dependency - Fix PR title — change
fix:tofeat:for consistency with the commit - Add empty-schema test — verify no crash when schema has zero prefixes
- Add
exclude_importsinteraction test — verify normalization works when imports are excluded - Strengthen CURIE remapping test — assert that slot URIs (not just class URIs) are remapped in the context
✅ What's Good
- Excellent documentation: the 3-case handling in
visit_schemais well-commented with case numbers - Defensive
_prefix_remapinitialization: correctly placed beforesuper().__post_init__()with clear comment explaining why - Collision detection: warning on skip is the right behavior — no silent data loss
MappingProxyTypefor the static map: prevents accidental mutationwell_known_prefix_map()returns a copy: callers can't corrupt the canonical map- Phase 2 concept is sound: cleaning up runtime-injected orphan bindings is the right idea, it just needs the overwrite guard
- Cross-generator consistency test: ensures OWL, SHACL, and JSON-LD agree — excellent
- Backward compatibility: flag defaults to off, existing behavior preserved
d9fb738 to
dd0ce0c
Compare
8d098e9 to
ef47b47
Compare
8dc3ece to
260a97e
Compare
260a97e to
e56ca65
Compare
e56ca65 to
5f17e19
Compare
ce55ccb to
909eb7d
Compare
a4b329c to
32821d0
Compare
32821d0 to
0342283
Compare
Review update from #4: test_csv_limit left the process-wide CSV field size limit at 20, so later tests on the same xdist worker that read prefixmaps' CSV data failed intermittently. Signed-off-by: jdsika <[email protected]>
0342283 to
316b430
Compare
Review update from #4: test_csv_limit left the process-wide CSV field size limit at 20, so later tests on the same xdist worker that read prefixmaps' CSV data failed intermittently. Signed-off-by: jdsika <[email protected]>
9ede52d to
29098c8
Compare
29098c8 to
d6e7eae
Compare
0f2e3d2 to
53485b5
Compare
…mes in generated artifacts Add an opt-in --normalize-prefixes option that writes the conventional name of a well-known namespace, e.g. dc for http://purl.org/dc/elements/1.1/ where a schema declares dce, and writes the same name in each of the generators that offer it: gen-owl, gen-shacl, gen-shex, gen-sparql, gen-yarrrml, gen-sssom and gen-jsonld-context. Only names change; every IRI stays the same. The names come from two curated sources, the prefixmaps linked_data context and the names rdflib binds by default, which the RDF generators serialize with; the two name no namespace differently. prefixmaps' merged context is not used: it names a namespace after the first registry in its merge order that lists it, which for W3C vocabularies is often the upper-cased Bioregistry name, such as ADMS for http://www.w3.org/ns/adms#. linkml.generators.common.prefixes computes one plan per schema as a curies Converter of preferred names with the other names as synonyms. In each output format a prefix declaration reaches no further than the document that carries it (Turtle 1.1 2.4, SPARQL 1.1 4.1.1.1, JSON-LD 1.1 3.1, CURIE Syntax 1.0 3), so a declaration in an imported schema binds nothing in a generated document that does not repeat it. A conventional name is therefore unavailable for a namespace where the schema's documents write it for another one: the schema declares it itself, or only an import declares it and it is in use, meaning that an element is identified by or mapped to an IRI of that namespace, is written with the prefix in a CURIE, names it in id_prefixes, or a schema lists it in emit_prefixes; or nothing declares it and a CURIE, id_prefixes or emit_prefixes names it all the same. A prefix that only an import declares and nothing uses holds no name. linkml:types declares schema for http://schema.org/ and uses it only in the mappings of its types, which none of these generators writes. A schema that declares schema for https://schema.org/ next to it is refused by gen-jsonld-context, gen-shex and gen-sssom, and gen-owl and gen-shacl then write http://schema.org/ IRIs; so a schema declares another name, such as sdo, and the option writes schema for https://schema.org/, which schema.org calls its preferred form in examples. LinkML's loaders and dumpers keep expanding schema in data as the import declares it, which the plan reports as a warning. A prefix keeps its name, with a warning, where two namespaces want the same conventional name or the name is that of a class, slot or permissible value, which a JSON-LD context uses as a term. How a generator applies the plan depends on what its prefixes are. Self- contained documents (Turtle, RDF/XML, ShExC, SPARQL, YARRRML, SSSOM) use only the preferred names, as a prefix there only abbreviates IRIs (RDF 1.1 Concepts 1.4); they rename only the prefixes they declare, keep the order of their declarations, and a prefix that their own CURIEs use keeps what it denotes, declared or not. A JSON-LD context is shared with the data written against it, and a compact IRI whose prefix it no longer defines stops expanding (JSON-LD 1.1 4.1.5), so it keeps every declared name and adds the preferred one; it writes its own compact IRIs, but not its keys, with the preferred names, and renames nothing with --no- prefixes. SchemaLoader-based generators read the plan from a SchemaView of the schema as given, resolving local imports of YAML text against base_dir. gen-sparql renders its queries once to learn which prefixes they use and keeps the declarations of those it writes as they stand, the named graphs and the template's own. It resets the caches of its working copy of the SchemaView: the copy compares equal to the original, so once the plan had filled the original's caches the copy was served those elements, and materialization rewrote the input and dropped queries. gen-prefix-map gives each namespace one name, the schema's, gen-rdf and gen-jsonld write CURIEs as literal data, and gen-python, gen-pydantic and gen-namespaces make prefix names part of the generated code, so they do not offer the option. test_csv_limit set csv.field_size_limit(20) without restoring it, so any later test on the same worker that read prefixmaps' CSV data failed; it now restores the limit. Signed-off-by: jdsika <[email protected]>
53485b5 to
6458056
Compare
Mirror of linkml#3446, same head. Review there; this PR tracks the fork stack.
Adds an opt-in
--normalize-prefixesoption that writes the conventional name of a well-known namespace, the same in each of the seven generators that offer it. Only names change; every IRI stays the same. Without the option the output of all seven is byte-identical tomain.In plain words: a prefix is a nickname for a long web address, and many schemas pick their own nickname for a well-known address. The option writes the nickname everyone else uses. A nickname is not taken when the generated files already use that word for something else: for a different address, or as the name of a class, slot or enum value. A nickname that an imported file merely declares, and that no generated file needs, does not count as used.
That last point is what makes the option work for schema.org. Nearly every schema imports
linkml:types, which declaresschemafor the oldhttp://schema.org/. A schema that wants today'shttps://schema.org/cannot rely on the nicknameschemaitself (the generators read it three different ways, see below), so it declaressdo. With the option the generated files sayschema, and the JSON-LD context understands bothschemaandsdo.Reproduce: without and with the option
sdo.yaml:--normalize-prefixesgen-owl --no-use-native-uris --no-metadata sdo.yaml@prefix sdo: <https://schema.org/> .sdo:Person a owl:Class ;@prefix schema: <https://schema.org/> .schema:Person a owl:Class ;gen-jsonld-context --no-metadata sdo.yaml"sdo": "https://schema.org/","@id": "sdo:Person""schema": "https://schema.org/","sdo": "https://schema.org/","@id": "schema:Person"The IRI is
https://schema.org/Personin every cell. The context keepssdo, so data written with it still expands. With the option each generator run reports the name it took over, once:Why the schema does not simply declare
schemaitself. The same file withsdoreplaced byschemathroughout (direct.yaml), without the option:gen-jsonld-context direct.yaml,gen-shex direct.yaml,gen-sssom direct.yamlValueError: Prefix: schema mismatch between s and typesgen-owl --no-use-native-uris direct.yaml,gen-shacl direct.yaml<http://schema.org/Person> a owl:Class ;andsh:targetClass <http://schema.org/Person>: the import's namespace, not the one the schema declaresgen-sparql -d out direct.yamlPREFIX schema: <http://schema.org/>withschema:Person: the import's namespace againlinkml generate yarrrml direct.yamlschema: https://schema.org/: the schema's namespaceNext to
linkml:typesthe seven generators read a schema's ownschema:three different ways. The only CURIE spelling that all of them read ashttps://schema.org/is an alias (full IRIs inclass_uri/slot_uriare the alternative), and this option is what gives the alias its conventional name in the output.The ordinary case is the same mechanism: a schema that declares
dce: http://purl.org/dc/elements/1.1/andw3prov: http://www.w3.org/ns/prov#getsdc:titleandprov:Agent; a prefix without a conventional name (ex) keeps its name.The rule and its basis
linkml.generators.common.prefixes.preferred_prefixes(sv)computes one plan per schema, a curiesConverterwith the preferred name per namespace and the other names as synonyms. Every generator applies the same plan, so artifacts generated in separate runs agree.A conventional name is given to a namespace unless the schema's documents already write it for something else:
class_uri,slot_uri, a type'suri,enum_uri, a permissible value'smeaning, or the IRI derived from the element's name), is mapped to one (class, slot, enum, permissible value), is written with the prefix in a CURIE, names it inid_prefixes, or a schema lists it inemit_prefixes;id_prefixesoremit_prefixesnames it all the same (it is then read with a default CURIE map or as an unknown namespace);timeblocksowltime→time).A prefix that only an import declares and nothing uses is needed by no document generated for the schema, so it holds no name.
linkml:typesusesschemaonly in the mappings of its types, which none of the seven generators writes (a test checks each of them, with and without the option).Why an unused declaration in an import does not count. In each output format a prefix declaration reaches no further than the document that carries it, so a declaration in an imported schema binds nothing in a generated document that does not repeat it:
LinkML's own schema language is the exception: a schema is read with the prefixes of its imports. That is the first point under What to weigh.
schema.org.
http://schema.org/andhttps://schema.org/are two namespaces: "Two IRIs are equal if and only if they are equivalent under Simple String Comparison" (RDF 1.1 Concepts §3.2). schema.org calls https its "preferred form in examples" and says "both 'https://schema.org' and 'http://schema.org' are fine" (FAQ). The two sources of conventional names each giveschemato one of them: prefixmaps to http, rdflib to https. If a schema writeshttp://schema.org/too (slot_uri: schema:legacyName),schemais in use for that namespace andsdokeeps its name.What to weigh
sdo+linkml:types, data that writesschema:Thingishttp://schema.org/Thingtolinkml-convertandhttps://schema.org/Thingto a JSON-LD processor using the normalized context (without the option the context leavesschemaundefined). Data written with the declared name,sdo, is read alike by both.linked_data(prefixmapsmainaddswgsforhttp://www.w3.org/2003/01/geo/wgs84_pos#,ICD10CM,NANDO) changes what the option writes for schemas that alias it. Pin both where generated artifacts are committed.SchemaViewgets its caches reset. Without the option its output is byte-identical tomain. With the option the reset matters: the copy compares equal to the original, so once the plan had filled the original's caches, materialization rewrote the input schema and two repository schemas lost queries (linkml_issue_388.yaml6 → 4,not_required.yaml17 → 16).linkml.generators.common.prefixesandGenerator.prefix_schemaview().Per generator
schema: http://schema.org/also wins over rdflib's defaultschema→ https, so noschema1. gen-shex's RDF output binds no schema prefix by default and the planned ones with the option.skos:exactMatchin SSSOM). gen-sparql renders its queries once to learn which prefixes they use, and keeps thePREFIXlines of the CURIEs it writes as they stand (named graphs, the template'srdf:andlinkml:).@type. A compact IRI whose prefix a context no longer defines "is interpreted as IRI instead" (JSON-LD 1.1 §4.1.5), which is why every declared name stays.--no-prefixesrenames nothing, since its prefixes then come from another context.curiesrejects synonyms there), gen-rdf and gen-jsonld (CURIEs are literal data), gen-python, gen-pydantic, gen-namespaces (prefix names are part of the generated code). To change the names users write, rename the prefixes in the schema.The conventional names come from two curated sources, no hand-written table: the
linked_datacontext of prefixmaps, as asked in review, and the names rdflib binds by default, which the RDF generators serialize with. The two name no namespace differently. prefixmaps'mergedcontext is not used: it names a namespace after the first registry in its merge order that lists it, which for W3C vocabularies is often the upper-cased Bioregistry name (ADMSforhttp://www.w3.org/ns/adms#,TIMEforhttp://www.w3.org/2006/time#,ODRL). Released prefixmaps (≥ 0.2.2) works.Testing
test_normalize_prefixes.py, 1026 tests over 16 schemas with hard cases:Fifteen mutations of the plan and of the generators each fail tests. The module passes with prefixmaps 0.2.2, 0.2.6 and
main(ada53ec).tests/linkmlandtests/linkml_runtimepass. Without the option, the output of the seven generators is byte-identical tomainon every repository schema both can generate.What the tests cover in detail
dc/dce, a case-only alias, a slot or enum value named like a prefix, an alias asdefault_prefix, in a typeurior enum meaning, prefixes declared only in an import, a declaredschema: http://schema.org/.--diff-stable, mapped URIs, metaclasses, metadata profile, annotations, type objects), ShExJ, SPARQL parse trees with expanded names, YARRRML and SSSOM with expanded CURIEs.id_prefixes,emit_prefixes, name-derived IRI, a full IRI, a type mapping, a description, …), each checked against the plan and 20 of them against what gen-owl, gen-shacl, gen-shex and gen-jsonld-context write.SchemaViewwhose namespace cache was filled before the imports loaded; a prefix written in a CURIE that nothing declares.--use-curies,--flatprefixes,--fix-multivalue-containers,--no-mergeimports); a name only the normalized context defines is the conventional name of a namespace the default context defines;--no-model+--no-prefixescontexts, gen-prefix-map +--no-prefixes, an importer with--exclude-importsnext to its import's context (also where the import uses the name), frames, YAML text input with local imports.schema: https://schema.org/next tolinkml:types: refused by gen-jsonld-context and gen-shex, read as http by gen-owl and gen-shacl.--no-normalize-prefixesequals the default, rejected elsewhere.test_csv_limitnow restorescsv.field_size_limit: left at 20, it broke prefixmaps' CSV loading in later tests on the same xdist worker.Limitations
see_also, annotations) do not hold the name. Only the RDF generators write them, as full IRIs, so the graph is the same with and without the option.Checklist