You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Cache schema validation and load plugin data files from a stream - #2152
Reduces memory used when plugin data files (mocks, errors, rewrites, …) and plugin config sections are loaded with schema validation on (the default).
Changes
Schema cache: downloaded JSON schemas are cached per process. A schema changed online is picked up the next time Dev Proxy starts.
Validation cache: a data file or plugin config section that hasn't changed since it last passed validation isn't validated again on reload. The per-process cache has one entry per file, schema URL and section, and compares size and last write time (plus a hash of the resolved contents when environment variable placeholders changed them). Failed validations aren't cached, and a pass is stored only if the file didn't change while it was being validated. The schema version warning is still logged on every load.
$schema lookup:ProxyUtils.ReadSchemaReference reads the top-level $schema with Utf8JsonReader and stops as soon as it finds it, instead of parsing the whole file into a JsonDocument.
Stream loading: JSON data files are validated and deserialized from the file stream instead of a string, so JsonSerializer.Deserialize<T>(string) no longer rents a UTF-8 buffer ~3× the string (16 MiB for a 5 MB file, which stayed pooled on the LOH across reloads). YAML files, files with environment variable placeholders or \u escapes, and UTF-16/32 files still go through the string path (converted to a UTF-8 MemoryStream once).
BaseLoader API:LoadData(string) is now virtual instead of abstract, and a new virtual LoadData(Stream) overload is called by the base class. Its default reads the stream into a string and calls LoadData(string), so existing third-party loaders keep working unchanged. Built-in loaders override the stream overload.
Measurements
5 MB mocks file with $schema, Server GC, hot reload triggered twice, no traffic (macOS phys_footprint):
Moment
Before
After
12 s after start
193 MB
151 MB
After reload 1
311 MB
170 MB
After reload 2
421 MB
179 MB
Mocks loaded on start and on each reload in both runs, with no validation failures.
Notes
The first load still builds a Newtonsoft DOM for validation. A cheaper validator is out of scope here.
For a malformed JSON file with $schema declared before the error, the error is now reported as a schema validation failure instead of a JSON read error. The file still isn't loaded in either case.
Tests
ReadSchemaReference: top-level vs nested $schema, comments and trailing commas, array root, BOM, tokens larger than the buffer read one byte at a time, stops after $schema, invalid JSON before $schema.
BaseLoader: unchanged file isn't validated again, a changed file is validated again with the cached schema, failed validation isn't cached, a change in resolved placeholders triggers validation, YAML files are cached.
- Cache downloaded JSON schemas per process.
- Skip validating a data file or plugin config section that hasn't changed
since it last passed validation (keyed by path, size, last write time,
schema URL and, when placeholders were resolved, a hash of the contents).
Failed validations aren't cached. The schema version warning is kept.
- Read $schema with Utf8JsonReader, stopping at the top-level property,
instead of parsing the whole file into a JsonDocument.
- Load JSON data files from the file stream instead of a string, so
JsonSerializer no longer rents a UTF-8 buffer about 3x the string. YAML
files and files with environment variable placeholders still go through
the string path. BaseLoader.LoadData(string) is now virtual and a new
LoadData(Stream) overload is used by built-in loaders.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
A critical race allows schema-invalid contents to be loaded if the file changes between validation and deserialization, because cache protection does not prevent publishing modified data.
This PR reduces memory use when Dev Proxy loads plugin data and reloads configuration by caching schema validation and using streams for eligible JSON files.
Changes:
Cache downloaded schemas and successful validation results per process.
Add stream-based loading for built-in loaders while preserving compatibility with existing string-based loaders.
Add tests for schema lookup and validation-cache behavior.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
A cache hit can skip validation of changed, potentially schema-invalid file contents because the current file version is not rechecked before accepting the cached result.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Concurrent cache misses can still duplicate schema downloads and parsing because callers do not share in-flight work.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Deduplicate concurrent schema downloads with an in-flight task
DevProxy.Abstractions/Utils/ProxyUtils.cs:380
Concurrent cache misses still download and parse the same schema more than once; GetOrAdd only selects a result after that work finishes. This can happen when a file-watcher reload overlaps the initial load while the first schema download is pending. Cache an in-flight task per URL so callers share the work, with an explicit cancellation policy and eviction of failed tasks so later loads can retry.
Re the review's 'previously missed' note about deduplicating concurrent schema downloads: I'm leaving this as is on purpose. Before this PR every validation downloaded and parsed the schema. Now the only duplicate is when two loads miss the cache for the same URL at the same moment, which happens at most once per URL per process (for example, a watcher reload overlapping the first load). The schemas are small, so the cost is negligible. Sharing an in-flight task would also mean deciding whose cancellation token owns the download and evicting faulted tasks, which adds more complexity than this rare case is worth.
Approve, scoped to functional testing. All 21 locally executed live scenarios passed, including the original failure reproduction and additional schema recovery, pending-download reload and plugin-section cache scenarios. This updated result supersedes my previous change request; it does not replace code review or re-benchmark the PR's memory measurements.
Owned proxy PID 12376 stopped gracefully and was verified exited; the local schema server stopped. Owned fixture/home/certificate/state files and generated runtime log were removed after preserving sanitized evidence. Worktree clean; no blockers or PR code changes.
Resolve conflicts with dotnet#2145 (local schemas) and dotnet#2177 (null entries):
- Stream and string validation share one path: the local schema first,
then the online schema, with downloaded schemas cached per process
(including the remote fallback).
- CrudApiDataLoader keeps stream loading and drops null entries.
- Schema validation tests use unique schema URLs, because downloaded
schemas are cached per process.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The stream and string validation overloads now share one path. The schema shipped with Dev Proxy is used first. The online schema is only downloaded when the document doesn't match the local schema. Downloaded schemas, including that fallback, use the per-process cache from this PR.
The tests from Ship JSON schemas and validate against them locally #2145 now use a unique schema URL per test, because the cache is process-wide. I added tests for the stream overload with local schemas and for the cached fallback.
The build has 0 warnings. All tests pass except ApiEndpointSchemasTests.Get_ProxyStatusResponse_ListsAllProxyInfoProperties. That test also fails on main (4df4a30, where the build check is failing), and the files involved are identical to main.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Schema-validation fallback paths can pass malformed JSON to legacy loaders and replace valid data, while the new public overload breaks source compatibility by making existing null-argument calls ambiguous.
…tion overload internal
- Fully check JSON syntax before loading when $schema is null/empty or the schema can't be retrieved
- Make ValidateJsonAgainstSchemaAsync(Stream, ...) internal to avoid ambiguous null calls
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because schema validation can admit malformed JSON into the cache and legacy loaders, creating a critical regression from the previous strict parsing behavior.
Do not cache malformed data as a successful validation
Head logs one validation-cache hit and republishes malformed data; base logs syntax error with no hit
FAIL
Requested changes
Reject malformed JSON on successful schema-validation paths
Requested change: Preserve the strict JSON syntax contract before invoking a legacy loader or recording a successful validation-cache entry, including when an available schema accepts Newtonsoft's permissive syntax. Add a raw-string loader regression covering this case and its unchanged-file retry.
Expected: After loading valid data with "name":"previous", reject a replacement with "name":'malformed', retain the previous raw data, and do not cache a pass.
Actual: The PR invokes LoadData(string) with the malformed replacement. Its next identical reload skips validation because the malformed version was cached as successful.
Reproduction: An external plugin exposes its raw-string loader contents at /legacy. With schema validation enabled and a loopback schema requiring string name, replace the data file with {"$schema":"http://127.0.0.1:<schema-port>/v4.1.0/legacy.schema.json","name":'malformed'}. Wait for reload and repeat the explicitly proxied GET. Head publishes malformed raw data; current base b2a9cbfef9bd434ee3b10d761814aa25d83aba20 rejects it and retains valid data. Confirmed in the full matrix and again with only the external plugin.
Inline comment: Replied to the existing malformed-JSON thread rather than duplicating it: #2152 (comment)
Outcome
Request changes. The latest null/empty/unavailable-schema fixes and external public-overload compatibility pass, but a reproducible available-schema syntax/cache regression remains. The full live matrix had 25 passing scenarios and two failing assertions for this one defect; base comparison confirmed attribution.
All owned proxies (44147, 45375, 46120, 46190) stopped gracefully and were verified exited. Local schema servers stopped; owned home/certificate/state/fixtures/logs and comparison worktree removed. Source checkout clean. Initial external-fixture dependency/type-identity setup errors were corrected before the successful legacy probe; they are not PR defects. No code fixes, pushes or merges.
The schema validator accepts JSON that System.Text.Json rejects, such as
single-quoted strings, which let malformed data be loaded and cached as a
successful validation.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟢 Approval recommended
No active review issues are recorded for the schema-validation caching and stream-based plugin loading changes.
No open issues 🎉
Review effort: Balanced
This branch has not been deployed
No deployments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pr-performanceMemory optimization, reduced allocations, and runtime or startup performance improvements
3 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Reduces memory used when plugin data files (mocks, errors, rewrites, …) and plugin config sections are loaded with schema validation on (the default).
Changes
$schemalookup:ProxyUtils.ReadSchemaReferencereads the top-level$schemawithUtf8JsonReaderand stops as soon as it finds it, instead of parsing the whole file into aJsonDocument.JsonSerializer.Deserialize<T>(string)no longer rents a UTF-8 buffer ~3× the string (16 MiB for a 5 MB file, which stayed pooled on the LOH across reloads). YAML files, files with environment variable placeholders or\uescapes, and UTF-16/32 files still go through the string path (converted to a UTF-8MemoryStreamonce).BaseLoaderAPI:LoadData(string)is nowvirtualinstead ofabstract, and a newvirtual LoadData(Stream)overload is called by the base class. Its default reads the stream into a string and callsLoadData(string), so existing third-party loaders keep working unchanged. Built-in loaders override the stream overload.Measurements
5 MB mocks file with
$schema, Server GC, hot reload triggered twice, no traffic (macOS phys_footprint):Mocks loaded on start and on each reload in both runs, with no validation failures.
Notes
$schemadeclared before the error, the error is now reported as a schema validation failure instead of a JSON read error. The file still isn't loaded in either case.Tests
ReadSchemaReference: top-level vs nested$schema, comments and trailing commas, array root, BOM, tokens larger than the buffer read one byte at a time, stops after$schema, invalid JSON before$schema.BaseLoader: unchanged file isn't validated again, a changed file is validated again with the cached schema, failed validation isn't cached, a change in resolved placeholders triggers validation, YAML files are cached.