Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions .castor/earl.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@
* order, so the cache directory constants of qa.php are not defined yet when this
* file is parsed.
*
* @return array<string, array{name: string, manifest: string, iri: string}>
* The RDF suites are driven by their manifest: their data sets are named after
* the fragment of the test IRI rather than after a fixture file ("byId").
*
* @return array<string, array{name: string, manifest: string, iri: string, byId?: bool}>
*/
function earlSuites(): array
{
Expand All @@ -63,6 +66,30 @@ function earlSuites(): array
'manifest' => CACHE_DIR_W3C_FRAMING_TEST_SUITE . '/tests/frame-manifest.jsonld',
'iri' => 'https://w3c.github.io/json-ld-framing/tests/frame-manifest',
],
'ToRdfTest' => [
'name' => 'toRdf',
'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/toRdf-manifest.jsonld',
'iri' => 'https://w3c.github.io/json-ld-api/tests/toRdf-manifest',
'byId' => true,
],
'FromRdfTest' => [
'name' => 'fromRdf',
'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/fromRdf-manifest.jsonld',
'iri' => 'https://w3c.github.io/json-ld-api/tests/fromRdf-manifest',
'byId' => true,
],
'RemoteDocTest' => [
'name' => 'remote-doc',
'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/remote-doc-manifest.jsonld',
'iri' => 'https://w3c.github.io/json-ld-api/tests/remote-doc-manifest',
'byId' => true,
],
'HtmlTest' => [
'name' => 'html',
'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/html-manifest.jsonld',
'iri' => 'https://w3c.github.io/json-ld-api/tests/html-manifest',
'byId' => true,
],
];
}

Expand Down Expand Up @@ -126,7 +153,7 @@ function earl(
$results = $outcomes[$testClass] ?? [];
$summary[$suite['name']] = ['passed' => 0, 'failed' => 0, 'inapplicable' => 0, 'untested' => 0];

foreach (earlManifestEntries($suite['manifest']) as $entry) {
foreach (earlManifestEntries($suite['manifest'], $suite['byId'] ?? false) as $entry) {
// A test that was not run is either out of scope (it only applies to
// JSON-LD 1.0 processors) or genuinely untested: the distinction matters
// in the consolidated report.
Expand Down Expand Up @@ -201,10 +228,11 @@ function earlOutcomesFromJunit(string $junitFile): array
* The data set name follows the convention of AbstractJsonLdTestCase: the expected
* output file with "-out" replaced by "-in" (several manifest entries share an
* input file but not an expected output), or the input file for a negative test.
* The suites driven by their manifest name it after the test fragment instead.
*
* @return list<array{id: string, test: string, jsonLd10Only: bool}>
*/
function earlManifestEntries(string $manifestFile): array
function earlManifestEntries(string $manifestFile, bool $byId = false): array
{
$content = file_get_contents($manifestFile);

Expand All @@ -229,9 +257,11 @@ function earlManifestEntries(string $manifestFile): array

$entries[] = [
'id' => $test['@id'],
'test' => \is_string($test['expect'] ?? null)
? str_replace('-out', '-in', basename($test['expect']))
: basename($test['input']),
'test' => match (true) {
$byId => $test['@id'],
\is_string($test['expect'] ?? null) => str_replace('-out', '-in', basename($test['expect'])),
default => basename($test['input']),
},
'jsonLd10Only' => 'json-ld-1.0' === ($option['specVersion'] ?? null),
];
}
Expand Down
53 changes: 53 additions & 0 deletions .castor/json-ld.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace json_ld;

use Castor\Attribute\AsArgument;
use Castor\Attribute\AsOption;
use Castor\Attribute\AsTask;

use function Castor\io;
Expand All @@ -20,6 +21,11 @@
use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander;
use JoliCode\StructuredData\JsonLd\Algorithms\Flatten\Flattener;
use JoliCode\StructuredData\JsonLd\Algorithms\Frame\Framer;
use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions;
use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter;
use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer;
use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter;
use Symfony\Component\Console\Input\InputOption;

#[AsTask(description: 'Applies the expansion algorithm to a JSON-LD document')]
function expand(
Expand Down Expand Up @@ -118,3 +124,50 @@ function frameJsonLd(

io()->writeln($result);
}

#[AsTask(name: 'to-rdf', description: 'Deserializes a JSON-LD document to RDF, written as N-Quads')]
function toRdf(
#[AsArgument(name: 'file', description: 'The JSON-LD file to deserialize')]
string $fileName,
#[AsOption(name: 'rdf-direction', mode: InputOption::VALUE_REQUIRED, description: 'How the base direction of a string is written: "i18n-datatype" or "compound-literal" (dropped by default)')]
?string $rdfDirection = null,
#[AsOption(name: 'generalized', description: 'Keep the triples whose predicate is a blank node')]
bool $generalized = false,
): void {
$file = file_get_contents($fileName);

if (false === $file) {
io()->error(\sprintf('The file "%s" could not be read.', $fileName));

return;
}

$converter = new ToRdfConverter();
$dataset = $converter->toRdf($file, new ProcessorOptions(produceGeneralizedRdf: $generalized, rdfDirection: $rdfDirection));

io()->write(NQuadsSerializer::serialize($dataset));
}

#[AsTask(name: 'from-rdf', description: 'Serializes an RDF dataset, read as N-Quads, as a JSON-LD document')]
function fromRdf(
#[AsArgument(name: 'file', description: 'The N-Quads file to serialize')]
string $fileName,
#[AsOption(name: 'rdf-direction', mode: InputOption::VALUE_REQUIRED, description: 'How the base direction of a string is read back: "i18n-datatype" or "compound-literal"')]
?string $rdfDirection = null,
#[AsOption(name: 'native-types', description: 'Turn xsd:boolean, xsd:integer and xsd:double literals into JSON booleans and numbers')]
bool $nativeTypes = false,
#[AsOption(name: 'rdf-type', description: 'Keep rdf:type as an ordinary property instead of "@type"')]
bool $rdfType = false,
): void {
$file = file_get_contents($fileName);

if (false === $file) {
io()->error(\sprintf('The file "%s" could not be read.', $fileName));

return;
}

$converter = new FromRdfConverter();

io()->writeln($converter->fromRdf($file, new ProcessorOptions(rdfDirection: $rdfDirection, useNativeTypes: $nativeTypes, useRdfType: $rdfType, ordered: true)));
}
18 changes: 18 additions & 0 deletions .castor/qa.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ function suiteFixturesAreMissing(): bool
return !fs()->exists(\sprintf('%s/tests/flatten/output', CACHE_DIR_W3C_TEST_SUITE))
|| !fs()->exists(\sprintf('%s/tests/frame/output', CACHE_DIR_W3C_FRAMING_TEST_SUITE))
|| !fs()->exists(\sprintf('%s/tests/expand-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE))
|| !fs()->exists(\sprintf('%s/tests/toRdf-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE))
|| !fs()->exists(\sprintf('%s/tests/fromRdf-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE))
|| !fs()->exists(\sprintf('%s/tests/html-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE))
|| !fs()->exists(\sprintf('%s/tests/remote-doc-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE))
|| !fs()->exists(\sprintf('%s/tests/frame-manifest.jsonld', CACHE_DIR_W3C_FRAMING_TEST_SUITE));
}

Expand Down Expand Up @@ -237,6 +241,20 @@ function phpunitPrepare(
}
}

// These suites are driven by their manifest, which names every file of a
// test: their fixtures are copied as they are upstream.
foreach (Algorithms::manifestDrivenSuiteNames() as $algorithm) {
fs()->copy(
\sprintf('%s/json-ld-api-%s/tests/%s-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE, $ref, $algorithm),
\sprintf('%s/tests/%s-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE, $algorithm),
true,
);
fs()->mirror(
\sprintf('%s/json-ld-api-%s/tests/%s', CACHE_DIR_W3C_TEST_SUITE, $ref, $algorithm),
\sprintf('%s/tests/%s', CACHE_DIR_W3C_TEST_SUITE, $algorithm),
);
}

// remove the zip archive and all the files
fs()->remove($zipFileName);
fs()->remove(\sprintf('%s/json-ld-api-%s', CACHE_DIR_W3C_TEST_SUITE, $ref));
Expand Down
60 changes: 41 additions & 19 deletions BENCHMARKS.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Benchmarks

The figures below come from `castor qa:bench:all`, run on 2026-11-13 on a developer
laptop, with PHP 8.5 in CLI, opcache and JIT disabled. They are
The figures below come from `castor qa:bench:all`, run on 2026-11-21 on a developer
laptop, with PHP 8.5 in CLI, opcache and JIT disabled, and Composer's optimized
autoloader. They are
[PHPBench](https://github.com/phpbench/phpbench) *mode* values: the most frequent
measurement over the iterations, with the relative standard deviation next to it.
Memory is the peak of the benchmark process. Take them as orders of magnitude: the
Expand All @@ -24,9 +25,9 @@ content-keyed cache can serve them.

| Scenario | Document | Time per document | Peak memory |
| --- | --- | --- | --- |
| 25 distinct variants of the Google *Book* fixture | 9 KB JSON-LD, 10 nested types | 12.7 ms | 20.6 MB |
| 25 distinct variants of the Google *Book* fixture | 9 KB JSON-LD, 10 nested types | 13.2 ms | 20.8 MB |

The 25 documents took 318 ms in total (±0.25 %).
The 25 documents took 330 ms in total (±2.36 %).

### The same document, again and again

Expand All @@ -37,12 +38,12 @@ costs.

| Document | Size | Time per audit | Peak memory |
| --- | --- | --- | --- |
| schema.org fixture, a single type | 0.4 KB JSON-LD | 1.5 ms | 5.2 MB |
| schema.org fixture, nested types | 6 KB JSON-LD | 3.3 ms | 5.8 MB |
| Google *Book* fixture | 9 KB JSON-LD | 12.6 ms | 8.1 MB |
| jolicode.com homepage | 139 KB HTML | 6.8 ms | 6.6 MB |
| jolicampus.com homepage | 95 KB HTML | 5.5 ms | 6.5 MB |
| Google structured data introduction | 187 KB HTML | 10.5 ms | 6.5 MB |
| schema.org fixture, a single type | 0.4 KB JSON-LD | 1.6 ms | 5.2 MB |
| schema.org fixture, nested types | 6 KB JSON-LD | 4.0 ms | 6.2 MB |
| Google *Book* fixture | 9 KB JSON-LD | 13.1 ms | 8.2 MB |
| jolicode.com homepage | 139 KB HTML | 7.1 ms | 6.6 MB |
| jolicampus.com homepage | 95 KB HTML | 5.9 ms | 6.5 MB |
| Google structured data introduction | 187 KB HTML | 10.9 ms | 6.6 MB |

The HTML pages are real pages, downloaded by `castor qa:phpunit:download-fixtures`
from hosts JoliCode owns or operates (plus the Google documentation page), and never
Expand All @@ -56,18 +57,28 @@ processor benchmarks measure the context processing step alone.
| Algorithm | Input | Time | Peak memory |
| --- | --- | --- | --- |
| Context processing | inline context | 11 µs | 3.9 MB |
| Context processing | scoped contexts | 24 µs | 3.9 MB |
| Context processing | scoped contexts | 25 µs | 3.9 MB |
| Context processing | nested contexts | 12 µs | 3.9 MB |
| Expansion | minimal document (`expand/0002`) | 224 µs | 3.9 MB |
| Expansion | context-heavy document (`expand/0036`) | 409 µs | 3.9 MB |
| Expansion | nested `@graph` (`expand/pr25`) | 829 µs | 3.9 MB |
| Expansion | 8 nodes each repeating the schema.org context | 3.1 ms | 5.1 MB |
| Expansion | context-heavy document (`expand/0036`) | 412 µs | 3.9 MB |
| Expansion | nested `@graph` (`expand/pr25`) | 837 µs | 3.9 MB |
| Expansion | 8 nodes each repeating the schema.org context | 3.2 ms | 5.1 MB |
| Compaction | inline context | 215 µs | 3.9 MB |
| Compaction | into the schema.org context | 13.4 ms | 10.2 MB |
| Flattening | minimal document | 266 µs | 3.9 MB |
| Compaction | into the schema.org context | 13.8 ms | 10.2 MB |
| Flattening | minimal document | 264 µs | 3.9 MB |
| Flattening | nested lists | 600 µs | 3.9 MB |
| Framing | by type, schema.org context | 16.2 ms | 10.5 MB |
| Framing | embedded node, schema.org context | 16.2 ms | 10.5 MB |
| Framing | by type, schema.org context | 16.3 ms | 10.5 MB |
| Framing | embedded node, schema.org context | 16.3 ms | 10.5 MB |
| Deserialization to RDF | minimal document (`toRdf/0002`) | 126 µs | 3.9 MB |
| Deserialization to RDF | list (`toRdf/0036`) | 182 µs | 3.9 MB |
| Deserialization to RDF | nested `@graph` (`toRdf/pr25`) | 987 µs | 3.9 MB |
| Deserialization to RDF | JSON literal (`toRdf/js12`) | 182 µs | 3.9 MB |
| Deserialization to RDF | 8 schema.org nodes, written as N-Quads | 1.5 ms | 5.2 MB |
| Serialization from RDF | minimal dataset (`fromRdf/0002`) | 87 µs | 3.9 MB |
| Serialization from RDF | lists (`fromRdf/li03`) | 274 µs | 3.9 MB |
| Serialization from RDF | native types (`fromRdf/0027`) | 184 µs | 3.9 MB |
| Serialization from RDF | 1,600 statements, read from N-Quads | 15.7 ms | 6.4 MB |
| Serialization from RDF | the same 1,600 statements, already parsed | 5.6 ms | 5.3 MB |

Compaction into the schema.org context and framing with it both cost around 15 ms:
that is the price of building the inverse context of the roughly 3,000 schema.org
Expand All @@ -76,24 +87,35 @@ is cheap in comparison, because the processed context is served from the static
vocabulary files the library ships with. The "repeated remote context" subject is the
regression guard for that path.

The deserialization to RDF is an expansion followed by the node map generation: on the
nested `@graph` document it costs 18 % more than the expansion alone. The serialization from RDF takes an
`RdfDataset` or N-Quads: on the 1,600 statements dataset, reading the N-Quads is two
thirds of the time (about 6 µs per statement), the algorithm itself the last third
(about 3.5 µs per statement).

## Reproducing

```bash
castor qa:install # phpbench and the other QA tools
castor qa:phpunit:prepare # the W3C test suites
castor qa:phpunit:download-fixtures # the HTML pages
composer dump-autoload -o # the optimized autoloader the figures are taken with
castor qa:bench:all
```

`castor qa:bench:validators -d` additionally breaks the HTML pipeline down step by
step (format detection, extraction, parsing, mapping, validation); it is slow.

The autoloader matters: without the optimized class map, the audits of a single document
are 2 to 10 % slower and the peak memory figures are 1.3 to 3 MB lower, the class map of
the 3,000 generated vocabulary classes not being loaded.

For finer time units than the default seconds, call PHPBench directly:

```bash
tools/phpbench/vendor/bin/phpbench run tests/Algorithms/Benchmark --report=readable --time-unit=microseconds
tools/phpbench/vendor/bin/phpbench run tests/Validation/Benchmark/JsonLdValidatorBench.php tests/Validation/Benchmark/WorkerValidationBench.php --report=readable --time-unit=milliseconds
```

For the record, the full PHPUnit suite (1,496 tests, 3,317 assertions, W3C suites
For the record, the full PHPUnit suite (2,281 tests, 4,802 assertions, W3C suites
included) runs in about 20 seconds on the same machine.
Loading
Loading