Skip to content

fix(ml): scores of every label and the model description in a prediction (3.0) - #92

Open
nieprzecietny wants to merge 4 commits into
masterfrom
fix/ml-scores-and-model-info-master
Open

nieprzecietny wants to merge 4 commits into
masterfrom
fix/ml-scores-and-model-info-master

Conversation

@nieprzecietny

@nieprzecietny nieprzecietny commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

What

The 3.0 counterpart of #91, which went to release/2.1 and was released as 2.1.1. master had the same commented-out code in TailoredApps.Shared.Mediator.ML: ClassifyImage returned only the winning label, ImagePrediction.Scores and ModelInfo were null, and a model saved without the Labels.txt entry had no labels.

Four commits:

  1. The merged change of fix(ml): scores of every label and the model description in a prediction #91 with the names of this line (TailoredApps.Shared.MediatR.* -> TailoredApps.Shared.Mediator.*, docs/Libraries/MediatR -> docs/Libraries/Mediator).
  2. After the first review here: the description of the model is recorded when the model is loaded, from the same bytes, instead of being read from the configured file when a loaded model is first used.
  3. After the second review: a watched model is replaced atomically for predictions, and a reload that failed is retried.
  4. After the third review: the file is watched before it is first loaded, and disposing the loader releases the file.

Changes

  • FromModelFile(path, watchForChanges = true) (new, on PredictionEnginePoolBuilder) is the library's own loader for the pool. It reads the checksum, the version and the model through one open file and records the description for that model instance.
    • With watchForChanges it loads the file again when it changes. Watching starts before the first load, which holds the lock every reload takes, so a file replaced while the application starts is not missed.
    • A file that cannot be loaded yet (still being written, or held by its writer) is tried again with growing delays for about a minute after the last reported change; until it loads, the current model stays in use.
    • Dispose waits for a reload under way, so the file is closed when the service provider has been disposed.
  • Predictions and the replacement of a model are kept apart by a gate. Every call that borrows an engine runs on its shared side; the replacement, together with the pool's reload callback, on its exclusive side. A prediction sees the model and the engines of one generation, and no engine of the previous model is put back among the new ones.
  • ImageClassificationService.Predict fills Scores (label -> score) and ModelInfo, and both belong to the model that made the prediction.
    • The labels are the ones the loaded model names its scores with, read from the engine that made the prediction.
    • ModelInfo is the description recorded by FromModelFile for that model. Replacing the file later does not change what the predictions of an already loaded model report.
    • Scores stays null when the model does not name its scores or the names do not match them one to one.
    • ModelInfo stays null when the model was loaded in another way (the FromFile of ML.NET, a URI) and with an adapter other than the library's. In each case no file can be proven to be the model that predicted.
  • GetModelInfo() describes the configured file as it is now; for a file without Labels.txt its labels come from the loaded model.
  • PredictionEnginePoolAdapter.GetLabels returns the engine to the pool and answers with an empty array for a model whose scores are not named, instead of throwing.
  • ModelHelper.GetChecksum keeps the checksum of a model file until its size or write time changes. GetVersion / GetLabels open the file with read-only, shared access.

What an application has to change

pool.FromFile(...) -> pool.FromModelFile(...). With FromFile the model still loads and Scores are filled, but ModelInfo is null. The 3.0 upgrade guide has the entry and a checklist row; the registration examples and the demo use FromModelFile.

This differs from 2.1.1, where ModelInfo is read from the configured file when a loaded model is first used. The gap the first review describes (a file replaced between loading and the first classification) is still there in 2.1.1.

Checks

  • mkdocs build --strict passes for both sites.
  • dotnet build TailoredApps.Shared.slnx -c Release -p:ValidatePublicApi=true: 0 errors, 0 warnings.
  • dotnet test TailoredApps.Shared.slnx -c Release: every project passes on net10.0 and net11.0; Mediator.ML.Tests 117 passed, 1 skipped (the training test that was already skipped); the integration tests of the demo pass with FromModelFile.
  • ModelFileLoadingTests run against a real PredictionEnginePool, with small models trained in the test:
    • the file replaced after loading and before the first prediction (the case from the first review);
    • the file replaced without a reload, and replaced while watched;
    • four threads classifying while the watched file is replaced: no prediction mixes two models, and 200 predictions in a row afterwards come from the new one;
    • the file written in place through an exclusive handle that stays open after its last write;
    • the file made unreadable while watched, and a model loaded with FromFile;
    • a missing model file and a missing directory, with and without watching.
  • The window of the third review (a file replaced during the first load) cannot be opened from outside the loader, so it has no test of its own.
  • The last two concurrency and retry tests fail on the previous commit of this branch (run twice), and pass with this one. After the fourth commit the model loading tests were run sixteen times on both frameworks without a failure; before it, one run in six failed because a retry still had the model file open when the test deleted its folder.
  • A real model (before the third commit): a 95 MB image model from 2021 without Labels.txt, three images, on Windows and in mcr.microsoft.com/dotnet/aspnet:11.0 (model mounted read-only):
    • the same label and the same five scores as TailoredApps.Shared.MediatR.ImageClassification 1.1.0 and the released 2.1.1 return for these images;
    • ModelInfo.Checksum equals the MD5 of the file, and the version is the one stored in it;
    • about 70 ms per image on Windows and about 120 ms in the container.

Docs

docs/Libraries/Mediator/ML.md, docs-en/Libraries/Mediator/ML.md, the package README.md and both Migration/v3.md pages.

The 3.0 counterpart of #91 (release/2.1, released as 2.1.1), ported to TailoredApps.Shared.Mediator.ML.

ClassifyImage returned only the winning label: ImagePrediction.Scores and ModelInfo were left null, and a
model saved without the Labels.txt entry had no labels at all.

- ImageClassificationService.Predict fills Scores (label -> score) and ModelInfo, and both belong to the
  model that made the prediction. The labels are read from the engine that made it; the file at
  ModelFilePath is described once for every loaded model, when that model is first used. A file replaced
  without the pool reloading it keeps the labels and the description of the model that still predicts.
- Scores stays null when the model does not name its scores or the names do not match them one to one.
  ModelInfo stays null when ModelFilePath is not configured or cannot be read, when the pool replaced the
  model while the prediction ran, and with an adapter other than the library's.
- GetModelInfo() describes the file as it is now; without Labels.txt its labels come from the loaded model.
- PredictionEnginePoolAdapter predicts and reports the labels and the model in one call (an internal
  contract). GetLabels returns the engine to the pool and answers with an empty array for a model whose
  scores are not named.
- ModelHelper keeps the checksum of a model file until its size or write time changes, and reads the
  version and the labels with read-only, shared access.

No public API changes. Tests and docs are ported with the code.
@nieprzecietny
nieprzecietny requested a review from a team as a code owner December 2, 2026 00:48
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-02T01:25:50.065018Z 03efb26 Manual request
🔒 Security Review ✅ Completed 2026-12-02T00:52:35.368355Z 9f0dd67 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

description = new ModelFileDescription(path, modelInfoService.ModelFileName, modelInfoService.ModelChecksum, modelInfoService.ModelVersion);

P2 Badge Bind file metadata to the model before caching its description

If the model file is replaced after PredictWithModel returns but before this first description is read, the prediction uses the old model while ModelChecksum and ModelVersion describe the replacement. The adapter's before/after model comparison has already finished, so it cannot detect this change, and caching the description under the old model makes subsequent predictions retain the incorrect identity. The same mismatch occurs if the file changes between loading the pool and its first classification with watchForChanges: false. Capture metadata alongside model loading, or leave ModelInfo null when the file cannot be verified as belonging to the predicting model.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@codecov

codecov Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.95633% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.03%. Comparing base (4cbc378) to head (ae42d64).

Files with missing lines Patch % Lines
...ator.ML/Infrastructure/DescribedFileModelLoader.cs 82.65% 11 Missing and 6 partials ⚠️
...ediator.ML/Infrastructure/ClassificationService.cs 88.88% 0 Missing and 3 partials ⚠️
...r.ML/Infrastructure/PredictionEnginePoolAdapter.cs 94.73% 0 Missing and 2 partials ⚠️
...s.Shared.Mediator.ML/Infrastructure/ModelHelper.cs 95.83% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #92      +/-   ##
==========================================
+ Coverage   92.95%   93.03%   +0.07%     
==========================================
  Files         140      143       +3     
  Lines        4869     4207     -662     
  Branches      538      560      +22     
==========================================
- Hits         4526     3914     -612     
+ Misses        216      159      -57     
- Partials      127      134       +7     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Review of the previous commit: the description of the model file was read when a loaded model was first
used. A file replaced between the loading of the pool and its first classification was then described as
the model that predicts, and that description stayed for as long as the model lived.

- FromModelFile(path, watchForChanges = true) is the library's own loader for the pool. It reads the
  checksum, the version and the model through one open file and records the description for that model
  instance, so a description can only be that of the bytes the model came from. With watchForChanges it
  loads the file again when it changes; a file that cannot be loaded leaves the current model in use.
- ImagePrediction.ModelInfo comes only from that record. A model loaded in another way (the FromFile of
  ML.NET, a URI) has no ModelInfo: no file can be proven to be the model that predicted. Scores are not
  affected.
- The registration examples, the demo and the 3.0 upgrade guide use FromModelFile.

Tests against a real pool: the file replaced after loading and before the first prediction, replaced
without a reload, replaced while watched, made unreadable while watched, and a model loaded with FromFile.
@nieprzecietny

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

return new ModelBoundPrediction<TPrediction>(prediction, labels, ReferenceEquals(modelBefore, modelAfter) ? modelBefore : null);

P2 Badge Bind model identity to the rented engine's pool generation

With concurrent predictions during a watched reload, this comparison can attribute an old model's prediction to the replacement. The new loader assigns model in DescribedFileModelLoader.Reload before cancelling the reload token, leaving a window where both GetModel() calls return the replacement but GetPredictionEngine() still rents from the old pool. ML.NET's GetModel() implementation reads directly from the loader, whereas the engine pool changes through the reload callback. Thus reference equality does not establish engine identity, and ModelInfo can contain the replacement's checksum/version alongside the old model's scores. Bind identity to the engine's generation, or synchronize publication and prediction so this intermediate state cannot be observed.


// Most often the file is still being written: the watcher reports again when the writer is
// done, and until then the pool keeps the model it has.
logger.LogWarning(exception, "The model file {ModelFile} could not be reloaded; the loaded model stays in use.", Path.GetFileName(filePath));
return;

P2 Badge Retry transient reload failures without requiring another file event

When a producer updates the watched file in place and keeps an exclusive writable handle open after its final write, all change notifications can be handled while ReadChecksum or Load still fails with a sharing violation. Returning here permanently loses that update: closing the writer does not guarantee another Changed event, and the inspected .NET Linux watcher implementation handles modification events rather than close-write events. The service can therefore keep predicting with the old model indefinitely despite watchForChanges: true. Schedule a delayed retry for transient failures instead of relying solely on another filesystem notification.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…reload that failed

Review of the previous commit, both about a watched model file (watchForChanges):

- A prediction could pair the scores of the old model with the description of the new one. The loader
  handed out the new model before the pool, called back through the reload token, built its new engines,
  so for a moment the pool's model and its engines belonged to different models. An engine borrowed
  before the replacement was also put back among the new engines and kept predicting with the old model.
  Predictions (every call that borrows an engine) now run on the shared side of a gate and the
  replacement, with the pool's callback, on its exclusive side: a prediction sees the model and the
  engines of one generation, and no engine of the previous model survives the replacement.
- A reload that failed was tried again only when the system reported another change. A writer that keeps
  the file open after its last write leaves no such change, and the old model stayed in use for good. The
  loader now comes back on its own, with growing delays, for about a minute after the last reported change.

Tests, both failing before this change: four threads classifying while the file is replaced (no prediction
mixes two models, and afterwards 200 predictions in a row come from the new one), and a file written in
place through an exclusive handle that stays open after the last write.
@nieprzecietny

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review


P2 Badge Reconcile file changes made during initial model loading

If a deployment replaces the model after Load opens the original file but before the watcher is enabled, the pool retains the original model and misses the replacement notification. No retry is scheduled in this case, so even with watchForChanges: true, predictions can use the outdated model indefinitely until another file change occurs. Establish watching before the initial load with appropriate synchronization, or recheck the file after enabling the watcher to reconcile changes made during startup.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…spose

- Review of the previous commit: the file was loaded first and watched afterwards, so a file replaced
  while the first load ran was never reported and the pool kept the outdated model until the next change.
  Watching now starts before the first load, and the first load holds the lock every reload takes: a change
  reported meanwhile waits for the load and is then compared with what was loaded.
- Dispose waits for a reload under way. With the retries added in the previous commit an attempt could
  still have the model file open after the service provider was disposed; a test deleting its folder
  right after that failed once in six runs.

Tests: a missing model file and a missing directory are reported as such, with and without watching. The
model loading tests were run sixteen times on both frameworks without a failure. The window of the first
point cannot be opened from outside the loader, so it has no test of its own.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant