Skip to content

fix: honour classify --retry, avoid repeated dependency downloads, add duplicate face command and UI model download - #1616

Open
SchBenedikt wants to merge 6 commits into
nextcloud:mainfrom
SchBenedikt:feat/issue-batch-fixes
Open

SchBenedikt wants to merge 6 commits into
nextcloud:mainfrom
SchBenedikt:feat/issue-batch-fixes

Conversation

@SchBenedikt

@SchBenedikt SchBenedikt commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR bundles four independent improvements for maintenance and administration. They were chosen because each has a clear, reproducible root cause in the current code and can be reviewed in isolation:

Commit Fixes Area
fix(Classify): skip already processed files with --retry #1471 CLI
fix(InstallDeps): do not re-download installed TF.js and ffmpeg binaries #1478 Repair step
feat(Command): add recognize:remove-duplicate-faces with --dry-run #1604 CLI / face DB
feat(Admin): download models from the admin settings #1529 Admin UI
fix: address review feedback on classify retry, install isolation and model downloads review all of the above

Changes

1. occ recognize:classify --retry skipped nothing (#1471)

On main, the retry check fetched tags per file (getTagIdsForObjects() + getTagsByIds() — two queries per file) and the processed-tag comparison lived inside the per-file loop. The first revision of this PR moved the check in front of the queue building, which silently changed the semantics: files carrying the processed tag were skipped for every classifier, including the face classifier — which never tags files and tracks progress in the face detection table instead. That would have re-queued already-processed images for faces on every --retry run, and the opposite direction (a file processed by faces but not by the tag-based classifiers) was never reachable.

The command now:

  • resolves the processed-tag state of a whole page in one query via the new TagManager::getProcessedFileIds() (tag ids only — the previous path also loaded full tag objects per file),
  • distributes files to classifier queues in ClassificationQueueBuilder, which is unit-tested,
  • queues face-classified images unconditionally (the face pipeline deduplicates via faceDetections), while imagenet/movinet/musicnn skip only files that carry the processed tag.

2. occ maintenance:repair re-downloaded ~150 MB every time (#1478)

InstallDeps::run() unconditionally executed the tfjs-node, tfjs-node-gpu and ffmpeg-static install scripts, so every repair run downloaded the binaries again — even without --include-expensive.

The install scripts now only run if the corresponding artifact is missing:

  • native bindings: node_modules/@tensorflow/tfjs-node{,-gpu}/lib/<napi>/tfjs_binding.node
  • ffmpeg: node_modules/ffmpeg-static/ffmpeg

CPU and GPU are checked separately, so a missing GPU binding does not trigger a CPU re-download. Each step is additionally isolated (runInstallStep()): a failing install is reported as a warning and the remaining steps still run, so e.g. a tfjs-node-gpu failure can no longer prevent the ffmpeg install. This is covered by tests/InstallDepsTest.php, which drives the real run() with a fake node binary.

3. New occ recognize:remove-duplicate-faces with --dry-run (#1604)

The duplicate face detection repair step added in #1318 was only reachable through the repair step. This exposes it to administrators:

occ recognize:remove-duplicate-faces --dry-run   # only count
occ recognize:remove-duplicate-faces             # remove

RemoveDuplicateFaceDetections now exposes removeDuplicates(bool $dryRun): int; run() uses it, so the repair step and the command share one implementation and cannot drift apart. The command is registered in appinfo/info.xml and documented in the admin settings' "Terminal commands" section.

A unit test asserts that a dry run reports the duplicates but leaves the table untouched.

4. Download the models from the admin settings (#1529)

Installations without shell access (managed hosting, Docker images without occ) previously could not download the models. The status card now offers a Download models button:

  • GET /apps/recognize/admin/downloadModels queues a DownloadModelsJob — but only if no download is already queued or running. Queued jobs leave the jobs table as soon as they start, so the check additionally consults OCP\BackgroundJob\IJobRuns::runningJobs(); a stale "running" entry older than 24h is ignored so a crashed download cannot block the button forever.
  • GET /apps/recognize/admin/modelsStatus reports downloaded / scheduled with the same active-job detection, so the UI keeps polling while a download is in flight.
  • the download runs in a QueuedJob, not in the HTTP request (the archive is ~1.4 GB)
  • the page polls while the job is scheduled and switches to the success state once models/ exists
  • the existing occ recognize:download-models note stays visible as an alternative

Verification

Run in this environment (PHP 8.5.9, Node 24):

  • php -l on every changed PHP file — no syntax errors
  • php-cs-fixer on all touched files — clean
  • New unit tests pass against a standalone OCP stub bootstrap (no Nextcloud server needed): ClassificationQueueBuilderTest (5), TagManagerTest (3), TagManagerAuditTest (8), InstallDepsTest (5), AdminControllerTest (7, requires the NC 3rdparty autoloader for DBAL types)
  • eslint src/components/ViewAdmin.vue — 0 errors (the 6 vue/attributes-order warnings are pre-existing on untouched lines)
  • appinfo/info.xml parses with simplexml_load_file()
  • composer install and npm ci --ignore-scripts succeed, so the dependency manifests are consistent

Not executable here: the full PHPUnit suite and Psalm. App tests bootstrap from ../../../tests/bootstrap.php, i.e. a full Nextcloud server checkout, which is not available on this machine; Psalm 6.5 additionally crashes on PHP 8.5 (SplObjectStorage::attach() deprecation in its own error handler). CI should be authoritative for both — note the pre-existing FsActionServiceTest failures (Trashbin::deleteAll() signature) are unrelated to this PR.

Notes for reviewers

  • The admin download job does not retry automatically on failure; it logs the error and the status endpoint keeps reporting the models as missing, so an administrator can press the button again. Automatic retries felt riskier than a visible, idempotent action.
  • There is still a small check-then-queue race between the status check and jobList->add(); two simultaneous clicks could enqueue two jobs, but the second download is idempotent (it re-downloads into the same directory). Hardening the job itself against concurrent execution would need a lock inside DownloadModelsJob — happy to add that if you prefer.
  • models/ is committed in the repository (the release package strips it), so in a development checkout the UI already considers the models downloaded. This matches the existing AdminSettings initial state and is unchanged.
  • I deliberately did not touch areas already covered by open PRs, so this does not conflict with fix(InstallDeps): don't chmod an already executable node binary #1614 (chmod handling in InstallDeps), Added a Setting to set the Model Download Folder #1557 (configurable model folder), Feat/link faces to contacts #1580 (contacts integration) or feat(Classify): allow specifying user/path #905 #1225 (--user/--path for recognize:classify).

Follow-ups this PR does not attempt

Benedikt Schächner added 4 commits November 24, 2026 19:45
The retry check looked up the tags of the last file id under an integer key,
while getTagsForFiles returns them keyed by string, so the lookup never
matched and already processed files were classified again. Check the tags
of a whole page in one query and compare tag ids instead, and skip such
files before they are added to any classifier queue.

Fixes nextcloud#1471

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

Signed-off-by: Benedikt Schächner <benedikt@schaechner.dev>
The repair step runs on every maintenance:repair and re-downloaded ~150 MB
of TensorFlow.js binaries each time although they were already present.
Only run the install scripts when the native bindings or the ffmpeg
binary are actually missing.

Fixes nextcloud#1478

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

Signed-off-by: Benedikt Schächner <benedikt@schaechner.dev>
Expose the duplicate face detection repair step as an occ command, with a
dry-run mode that only reports how many detections would be removed. The
repair step now returns the number of removed duplicates so the command and
the repair step share one implementation.

Refs nextcloud#1604

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

Signed-off-by: Benedikt Schächner <benedikt@schaechner.dev>
Add a button to the admin settings that queues a background job downloading
the machine learning models, so installations without shell access can
download them. The page polls the job status and updates automatically.

Fixes nextcloud#1529

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

Signed-off-by: Benedikt Schächner <benedikt@schaechner.dev>
@SchBenedikt
SchBenedikt force-pushed the feat/issue-batch-fixes branch from e915f19 to 6c016dd Compare November 24, 2026 19:45
Comment thread lib/Controller/AdminController.php Outdated
if (file_exists(__DIR__ . '/../../models')) {
return new JSONResponse(['downloaded' => true, 'scheduled' => false]);
}
$this->jobList->add(DownloadModelsJob::class);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We should first check if the job is already running, otherwise we have multiple download jobs at the same time. (Queued Jobs are removed from the jobs table upon being started.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch — fixed in a1c9c08. QueuedJob rows leave the jobs table once they start, so isModelDownloadActive() now also consults OCP\BackgroundJob\IJobRuns::runningJobs() and refuses to enqueue a second job while one is running. modelsStatus() uses the same check so the UI keeps polling during the download. A stale 'running' entry older than 24h is ignored so a crashed download can't block the button forever. Note there is still a tiny check-then-queue race between two simultaneous clicks; the second download is idempotent, and I mentioned it in the PR notes — happy to add an in-job lock if you prefer.

Comment thread lib/Migration/InstallDeps.php Outdated
if ($this->isFfmpegInstalled()) {
$output->info('ffmpeg binary is already installed, skipping download.');
} else {
$this->runFfmpegInstall($binaryPath);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Doesn't this skip installing ffmpeg when GPU install fails?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, it did — the steps ran sequentially and a GPU failure aborted the rest. Fixed in a1c9c08: each install step now goes through runInstallStep(), which catches the failure, reports it as a warning and lets the remaining steps run. Covered by tests/InstallDepsTest.php, which uses a fake node binary that fails the GPU install and asserts ffmpeg is still installed.

Comment thread lib/Command/Classify.php Outdated
foreach ($files as $file) {
$lastFileId = $file['fileid'];
// If the retry flag is set, skip files that already carry the processed tag, for all classifiers
if ($input->getOption('retry') && $this->hasProcessedTag($tagsByFile[(string)$file['fileid']] ?? [], $processedTag)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think the face classification pipeline doesn't add processed tags to files, so this will skip all tagged files from being processed by face classification.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You're right, and this was the most important catch — the first revision skipped tagged files for all classifiers, but the face classifier never tags files and deduplicates via faceDetections instead. Fixed in a1c9c08: queue distribution moved into ClassificationQueueBuilder, which queues images for faces unconditionally and only applies the processed-tag skip to the tag-based classifiers (imagenet/movinet/musicnn). Covered by ClassificationQueueBuilderTest.

Comment thread lib/Command/Classify.php Outdated
// Fetch the tags of the whole page at once instead of issuing one query per file
$fileIds = array_map(static fn (array $file): string => (string)$file['fileid'], $files);
$tagsByFile = $input->getOption('retry') && count($fileIds) > 0
? $this->tagManager->getTagsForFiles($fileIds)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Doesn't this method still loop over the fileIds with one query per file?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It did — getTagsForFiles() internally calls getTagIdsForObjects() plus a getTagsByIds() per file just to resolve full tag objects we never used. Fixed in a1c9c08: the new TagManager::getProcessedFileIds() only resolves tag ids, so the whole page is fetched with a single getTagIdsForObjects() query (one query per page instead of ~2 per file).

Comment thread lib/Command/Classify.php
if ($input->getOption('retry')) {
$fileTags = $this->tagManager->getTagsForFiles([(string)$lastFileId]);
// check if processed tag is already in the tags
if (in_array($processedTag, $fileTags[$lastFileId])) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You're claiming "getTagsForFiles() keys its result by the string file id, but the lookup used the int $lastFileId, so the array access was always undefined", but PHP turns numeric string keys into ints, so IMO the old lookup worked. Did you try it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You're right — I verified it: PHP casts numeric string keys to int, so $tagsByFile[$lastFileId] did resolve, and the object comparison in in_array() was non-strict so it worked too. The PR description claimed otherwise and I've corrected it. What was actually wrong with the previous revision was semantic, not the lookup: it skipped tagged files for every classifier including faces (see the other thread), and it still cost ~2 queries per file. Both are fixed in a1c9c08.

Benedikt Schächner and others added 2 commits November 28, 2026 12:33
… model downloads

- recognize:classify --retry now resolves the processed tag state of a whole
  page in a single query (TagManager::getProcessedFileIds) instead of loading
  full tag objects per file, and only skips the tag-based classifiers. The
  face classifier keeps its independent retry behaviour because it does not
  tag files and tracks progress in the face detection table.
- Queue distribution moved into ClassificationQueueBuilder so the per-classifier
  retry semantics are covered by unit tests.
- InstallDeps runs each download step isolated, so a failing tfjs-node-gpu
  install can no longer prevent the ffmpeg install.
- The admin model download now also detects a currently running
  DownloadModelsJob via OCP\BackgroundJob\IJobRuns, because queued jobs leave
  the jobs table once they start. Stale running entries older than 24h are
  ignored so a crashed download cannot block the button forever.
- Add regression tests for all of the above.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
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.

2 participants