Skip to content

Cache schema validation and load plugin data files from a stream - #2152

Open
waldekmastykarz wants to merge 16 commits into
dotnet:mainfrom
waldekmastykarz:schema-cache-stream-loading
Open

waldekmastykarz wants to merge 16 commits into
dotnet:mainfrom
waldekmastykarz:schema-cache-stream-loading

Conversation

@waldekmastykarz

Copy link
Copy Markdown
Collaborator

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>
Copilot AI balanced review requested due to automatic review settings November 21, 2026 13:58
@waldekmastykarz
waldekmastykarz requested a review from a team as a code owner November 21, 2026 13:58

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.

🟡 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.

1 open issue
What changed in this PR

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.
File Description
DevProxy.Tests/​Fakes.cs Allow tests to enable schema validation.
DevProxy.Tests/​BaseLoaderSchemaValidationTests.cs Test caching, file changes, placeholders, and YAML.
DevProxy.Plugins/​Reporting/​CsomTypesDefinitionLoader.cs Load CSOM definitions from streams.
DevProxy.Plugins/​Mocking/​WebSocketMockResponsesLoader.cs Load WebSocket mocks from streams.
DevProxy.Plugins/​Mocking/​MockStdioResponsesLoader.cs Load stdio mocks from streams.
DevProxy.Plugins/​Mocking/​MockResponsesLoader.cs Load HTTP response mocks from streams.
DevProxy.Plugins/​Mocking/​MockRequestLoader.cs Load mock requests from streams.
DevProxy.Plugins/​Mocking/​CrudApiDefinitionLoader.cs Load CRUD API definitions from streams.
DevProxy.Plugins/​Mocking/​CrudApiDataLoader.cs Read CRUD arrays through a streaming JSON reader.
DevProxy.Plugins/​Manipulation/​RewritesLoader.cs Load rewrite rules from streams.
DevProxy.Plugins/​Inspection/​LanguageModelPricingLoader.cs Load model pricing from streams.
DevProxy.Plugins/​Behavior/​RateLimitingCustomResponseLoader.cs Load rate-limit responses from streams.
DevProxy.Plugins/​Behavior/​LanguageModelRateLimitingCustomResponseLoader.cs Load model rate-limit responses from streams.
DevProxy.Plugins/​Behavior/​GenericErrorResponsesLoader.cs Load error responses from streams.
DevProxy.Abstractions/​Utils/​ProxyUtils.cs Cache schemas and add streaming validation and schema lookup.
DevProxy.Abstractions/​Plugins/​SchemaValidationCache.cs Track successful validation by file version and context.
DevProxy.Abstractions/​Plugins/​BasePlugin.cs Reuse validation results for unchanged config sections.
DevProxy.Abstractions/​Plugins/​BaseLoader.cs Add stream loading, fallback conversion, and validation caching.
DevProxy.Abstractions.Tests/​Utils/​ProxyUtilsTests.cs Test incremental schema lookup and parsing edge cases.

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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.

🟡 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.

1 open issue
1 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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.

🔵 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

Medium severity 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.

1 resolved since last review

Review effort: Balanced

@waldekmastykarz

Copy link
Copy Markdown
Collaborator Author

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.

@waldekmastykarz waldekmastykarz added the pr-performance Memory optimization, reduced allocations, and runtime or startup performance improvements label Nov 21, 2026
Copilot AI balanced review requested due to automatic review settings November 25, 2026 14:09

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.

🟢 Approval recommended

No active review issues block approval of the schema-validation caching and stream-based loading changes.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 06:41

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.

🟢 Approval recommended

No active review issues are recorded for the memory-use and schema-validation caching changes.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 13:08

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.

🟢 Approval recommended

No active review issues were identified in the schema-validation caching and stream-based loading changes.

No open issues 🎉

Review effort: Balanced

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.

🟢 Approval recommended

No active review issues remain for the schema-validation caching and stream-based loading changes.

No open issues 🎉

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 14:33

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.

🟢 Approval recommended

No active review issues were identified for the schema-validation caching and snapshot-based loading changes.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 15:08

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.

🟢 Approval recommended

The review identifies no active issues with the schema-caching and stream-based loading changes.

No open issues 🎉

Review effort: Balanced

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Functional test results

  • PR: #2152
  • Tested commit: eac74e48251c813a875c2ebf64b5d0341df34da3
  • Environment: macOS 27.2.1, .NET SDK 10.0.103, Debug source build; isolated home/state/certificate directory. Detached launch used --as-system-proxy false --port 0 --api-port 0. Schema validation enabled; deterministic loopback server served repository v4.1.0 schemas with explicit guard constraints for failure scenarios.
Scenario or test command Expected Actual Result
dotnet restore DevProxy.sln --locked-mode then dotnet build DevProxy.sln --no-restore --verbosity quiet Successful locked restore and clean source build Build succeeded, 0 warnings, 0 errors; no tracked changes PASS
Current-head automated validation Build, platform tests and smoke checks green Build, macOS/Linux/Windows tests, smoke and CodeQL all successful on tested SHA. Automated tests not rerun locally PASS
Detached readiness and explicitly proxied GET Authenticated API 200; exact HTTP 201 mock body and custom header API 200; body {"marker":"initial"} and X-PR2152: stream PASS
Unchanged and changed valid data-file reloads Skip unchanged validation; publish changed content; reuse downloaded schema Cache-hit log for unchanged file; changed response served; one schema GET PASS
Invalid data-file edit, then identical invalid retry Reject both attempts; retain valid mocks; do not cache failures Two validation errors; last valid response retained; no extra schema download PASS
Placeholder and encoding fallbacks Resolve environment variable and Unicode escape; support UTF-8/16/32 BOMs Exact HTTP 201 marker and header in all five cases PASS
JSON comments and malformed-input boundaries Accept comments; preserve trailing-comma rejection; reject malformed JSON after $schema without replacing mocks Expected responses and logged failures; last good mocks retained PASS
Original CRUD regression: reload [{"id":3,"name":"invalid"}] {"extra":true} after valid data Reject malformed edit and keep HTTP 200 [{"id":2,"name":"reloaded"}] Exact previous array retained; no null response. Initial and valid CRUD reloads also worked PASS
Configuration hot reload and identical plugin-section reload API/mocks recover; cached schemas survive; unchanged sections skip validation API 200 and expected mock response; section cache-hit messages; no additional schema GETs PASS
YAML initial load and unchanged reload Convert and validate YAML; reuse successful validation HTTP 201 {"marker":"yaml-ok"}; subsequent validation cache hit PASS
Schema initially unavailable, then restored Warn and load while unavailable; retry validation on identical file once schema recovers First schema GET 404; second GET succeeds and rejects invalid guard; corrected file then served PASS
Data edited during delayed schema retrieval Stable snapshots and eventual newest contents Final HTTP 201 {"marker":"delayed-new"}; one delayed-schema GET PASS
Two configuration sections share one schema Valid crud cache hit must not suppress invalid mock validation Invalid section reported on initial and identical config reload; valid section cache hit; schema downloaded once PASS
Previously valid plugin section edited to invalid Revalidate rather than reuse cached pass Plugin configuration validation error logged for changed invalid guard PASS
Recent warm-cache cancellation fix Already-canceled token throws on cached-schema validation Added regression test and pre-cache token check inspected; current-head platform CI test jobs pass. Not separately exercised through the live CLI PASS (CI)

Requested changes

None. The previously reported CRUD data-loss regression is fixed on the tested head.

Outcome

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>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 07:24
@waldekmastykarz

Copy link
Copy Markdown
Collaborator Author

Merged main (5b3e3c7) to resolve conflicts with #2145 and #2177:

  • 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.
  • CrudApiDataLoader keeps stream loading and drops null entries as in Ignore null entries in files loaded by data loaders. Closes #2176 #2177.
  • 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.

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.

🟡 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.

2 open issues

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 27, 2026 08:44

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.

🟢 Approval recommended

No active review issues were identified in the schema-validation caching and stream-loading changes.

2 open issues

Review effort: Balanced

…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>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 09:03

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.

🔵 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.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Functional test results

  • PR: #2152
  • Tested commit: 155050d257b748f2a1c2025f2e8c218922eed326
  • Environment: macOS 27.2.1, .NET SDK 10.0.103, Debug source build. Isolated home/state/certificate fixtures, loopback schema HTTP server, detached proxies with --as-system-proxy false --port 0 --api-port 0. External legacy-loader plugin compiled against the source-build plugin API.
Scenario or test command Expected Actual Result
dotnet build DevProxy.sln --no-restore --verbosity quiet Source solution builds cleanly 0 warnings, 0 errors PASS
Tested-head CI Automated validation passes on tested revision Build, smoke, macOS/Linux/Windows test jobs and CodeQL all successful; no automated test suite rerun locally PASS
Live readiness and explicit proxy request Authenticated API 200 and exact mocked HTTP 201 body/header Expected API response, body and X-PR2152 header PASS
Unchanged/changed mock reload and invalid validation retries Reuse successful validation and downloaded schemas; reject invalid edits each time Correct cache-hit messages, exact new responses, two invalid-file errors and one schema download PASS
Environment placeholders, Unicode escapes, UTF-8/16/32 BOMs Correct resolved/decoded data Exact expected HTTP 201 bodies and headers in all five cases PASS
JSON comments and malformed-input boundaries Accept comments; preserve trailing-comma rejection; reject malformed JSON without replacing valid mocks Expected responses and logged errors; previous mocks retained PASS
Original CRUD malformed-reload reproduction Preserve valid array after a second JSON root is appended HTTP 200 [{"id":2,"name":"reloaded"}] retained; no null PASS
Config/YAML reloads and section caching Host recovers; unchanged data/sections skip validation API/mocks recovered; cache-hit logs; expected YAML response PASS
Unavailable schema recovery and edit during delayed download Retry validation after schema recovery; eventually apply newest data Correct warning/retry/rejection; newest response served after delayed GET PASS
Two sections sharing a schema and valid-to-invalid section edit Independent cache keys and revalidation of changed sections Valid section hit did not suppress invalid section errors; changed invalid section revalidated PASS
Legacy raw-string loader: malformed reload with null, empty and unavailable $schema Reject malformed replacement before callback and retain prior data Prior raw JSON retained in all three cases PASS
External ValidateJsonAgainstSchemaAsync(null, ...) call Source compiles without ambiguity; supported empty-input result External plugin compiled; runtime returned Valid PASS
Legacy raw-string loader: single-quoted value after an available $schema Reject malformed JSON and retain previous valid raw data Malformed data published on head; current base rejects and preserves previous data FAIL
Identical malformed legacy file reload preserving size/mtime 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>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 12:25

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.

🟢 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Memory optimization, reduced allocations, and runtime or startup performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants