Skip to content

Avoid unconditional constraint instantiation in Draft06/07/2019 dispatch - #926

Open
DannyvdSluijs wants to merge 1 commit into
mainfrom
fix/920-avoid-unconditional-constraint-instantiation
Open

DannyvdSluijs wants to merge 1 commit into
mainfrom
fix/920-avoid-unconditional-constraint-instantiation

Conversation

@DannyvdSluijs

Copy link
Copy Markdown
Collaborator

Summary

  • Draft06Constraint, Draft07Constraint, and Draft2019Constraint previously called checkForKeyword() for every registered keyword on every schema node, unconditionally instantiating a constraint object (via Factory::createInstanceFor()) even when the keyword was absent from the schema — the constraint's own check() would just immediately return via its internal property_exists($schema, ...) guard.
  • checkForKeyword() now skips createInstanceFor() entirely when the relevant schema property is absent, using a small per-class keyword→property map to handle the three keywords whose name doesn't match the schema property they guard on (ref→$ref, ifThenElse→if, content→contentMediaType/contentEncoding).
  • No behavior change: the guard exactly mirrors each constraint's own existing early-return.

Fixes #920.

Verification

  • Full official JSON-Schema-Test-Suite (composer test): identical failure set before and after (verified via git-stash A/B diff of failing test names) — zero regressions.
  • composer phpstan (level 8): clean.
  • composer style-check: clean.
  • 16 new unit tests (tests/Constraints/Drafts/Draft{06,07,2019}/) assert createInstanceFor is skipped for absent keywords and invoked for present ones.
  • Benchmarked on a representative nested schema: constraint instantiations for one recursive validation dropped from 40 to 9; isolated dispatch throughput went from ~267 to ~864 checks/sec (~3.2x). No measurable change in peak memory — the avoided objects were already being freed immediately via refcounting, so this is a CPU/allocator-churn win rather than a footprint win.

Follow-up

A related, larger idea came up during review: gating could go further by also checking the value's type (not just schema-property presence), since ~76% of Draft2019 constraints already guard on value type internally. That's a bigger, potentially breaking change (touches ~98 constraint classes, would need an opt-in addition to ConstraintInterface to stay backward compatible for consumers using Factory::setConstraintClass()), so it's tracked separately in #925 rather than folded into this PR.

Test plan

  • composer test
  • composer phpstan
  • composer style-check

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR optimizes Draft06/Draft07/Draft2019 keyword dispatch by avoiding unconditional constraint instantiation when the corresponding schema keyword/property is absent, while preserving existing behavior (matching the constraints’ own early-return guards).

Changes:

  • Added per-draft keyword→schema-property maps for the few keywords whose dispatch name doesn’t match their guarding schema property (ref, ifThenElse, content).
  • Updated checkForKeyword() in Draft06/07/2019 dispatchers to skip Factory::createInstanceFor() unless the relevant schema property exists.
  • Added unit tests asserting that only present keywords trigger createInstanceFor() calls.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/JsonSchema/Constraints/Drafts/Draft06/Draft06Constraint.php Gate constraint instantiation on schema-property presence (incl. $ref mapping).
src/JsonSchema/Constraints/Drafts/Draft07/Draft07Constraint.php Gate constraint instantiation on schema-property presence (incl. $ref, if, content* mappings).
src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php Gate constraint instantiation on schema-property presence (incl. $ref, if, content* mappings).
tests/Constraints/Drafts/Draft06/Draft06ConstraintTest.php New tests verifying instantiation is skipped for absent keywords in Draft06.
tests/Constraints/Drafts/Draft07/Draft07ConstraintTest.php New tests verifying instantiation is skipped for absent keywords (incl. special mappings) in Draft07.
tests/Constraints/Drafts/Draft2019/Draft2019ConstraintTest.php New tests verifying instantiation is skipped for absent keywords (incl. special mappings) in Draft2019.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +90 to +101
public function testDependentSchemasAndDependentRequiredAreInstantiatedIndependently(): void
{
$constraint = new Draft2019Constraint();
$calledKeywords = [];
$this->injectFactory($constraint, $this->createSpyFactory($calledKeywords));

$schema = json_decode('{"dependentRequired": {"a": ["b"]}}');
$value = json_decode('{"a": 1, "b": 2}');
$constraint->check($value, $schema);

$this->assertSame(['dependentRequired'], $calledKeywords);
}
@DannyvdSluijs
DannyvdSluijs force-pushed the fix/920-avoid-unconditional-constraint-instantiation branch from b379304 to 4f9cdb0 Compare July 24, 2026 09:57
@DannyvdSluijs
DannyvdSluijs force-pushed the fix/920-avoid-unconditional-constraint-instantiation branch from 4f9cdb0 to 0ca666a Compare August 21, 2026 11:30
@DannyvdSluijs
DannyvdSluijs force-pushed the fix/920-avoid-unconditional-constraint-instantiation branch from 0ca666a to 803e676 Compare September 9, 2026 19:44
checkForKeyword() now skips createInstanceFor() when the corresponding
schema property is absent, instead of always instantiating a constraint
object only for it to immediately no-op via its own internal guard.
Fixes #920.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@DannyvdSluijs
DannyvdSluijs force-pushed the fix/920-avoid-unconditional-constraint-instantiation branch from 803e676 to aead65c Compare September 17, 2026 19:58
@Roman3349

Roman3349 commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

If a keyword's name differs from its schema property and it isn't in KEYWORD_SCHEMA_PROPERTIES, that keyword never runs, and nothing reports it. I hit this when merging this PR with the $recursiveRef support for Draft 2019-09 in #984 (keyword recursiveRef, property $recursiveRef). Git merged it without a conflict, but $recursiveRef stopped working entirely.

I opened #993 against this branch with a test that keeps the map in sync with the constraints. For every keyword in each draft factory's constraintMap, it compares the properties in the first condition of the constraint's check() with the properties the dispatcher checks. It passes on this PR for all 97 keywords (Draft 2019-09 content is skipped because its check() is a no-op). It fails when ifThenElse is removed from the Draft07 map, and when merged with #984 until 'recursiveRef' => ['$recursiveRef'] is added.

The test relies on the convention that the first if in check() is the guard. Longer term, it would be cleaner for each constraint to declare the properties it guards on, so the dispatcher doesn't need its own map. That's out of scope here, though.

#993 also fixes the tests in this PR: the dependentSchemas/dependentRequired test only covered dependentRequired (as Copilot noted), and the tests mock the base Factory, which fails once the draft constraints call a draft factory method such as getDynamicScope() from #984.

BC

Custom constraints registered through Factory::setConstraintClass() no longer run when their keyword is absent from the schema.

Correction: custom constraint classes registered on the factory passed to the Validator never reach strict mode at all, because each Draft*Constraint creates its own draft factory and only takes the schema storage, URI retriever and config from the given one. The gating only affects a subclass of a Draft*Constraint that registers a custom keyword on the draft factory, and only when that keyword's name differs from its schema property. That is narrow enough not to block this PR.

@Roman3349

Copy link
Copy Markdown
Contributor

I profiled the strict mode with the GeoJSON schema of the jsonschema-benchmark (Draft-07), using the benchmark's harness for this library, and this PR helps a lot there. For the first 100 instances:

Time
main 26.7 s
This PR 11.0 s
This PR + #1007 5.6 s

#1007 evaluates the branches of oneOf, anyOf, not and if up to their first error, so it works together with this PR. Both change checkForKeyword(), whichever is merged second needs a small rebase, I'm happy to do it.

With this PR, the dispatch still calls checkForKeyword() for each of the 33 Draft-07 keywords on every schema node, while most nodes have only 2 to 4 of them. I tried dispatching only the keywords the schema has: iterate over get_object_vars($schema), look each property up in a map of property => [position, keyword] (which also covers if and content*), and sort the found keywords by their position, so the order stays the same as now. In a prototype for Draft-07, that took the same 100 instances from 11.0 s to 6.0 s, and to 1.8 s together with #1007. The JSON Schema Test Suite for Draft-07 passed.

It would replace the KEYWORD_SCHEMA_PROPERTIES lookup in this PR rather than extend it, so I didn't want to open a competing PR. If you like the idea, I can open a follow-up for Draft-06, Draft-07 and Draft 2019-09 once this one is merged, or share the patch here if you'd rather include it in this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Draft06Constraint, Draft07Constraint, and Draft2019Constraint instantiate all constraint objects unconditionally per schema node

3 participants