Repository navigation
Similarity analysis backend (issue #42) - #74
Merged
Merged
Conversation
Adds the real backend behind Similarity.vue: GET/POST /api/frontend/similarity* (web session + CSRF, admin-only), similarity_checks/similarity_pairs tables, a queued->running->completed|failed job, and a JPlag-based comparison engine behind SimilarityEngineInterface (JplagSimilarityEngine for real runs, a FakeSimilarityEngine for hermetic tests). JPlag is pinned to v6.2.0 (last release built for JDK 21) with a checksum verified at both Docker build time and before every run. Idempotency-Key handling is a small reusable trait backed by a new idempotency_keys table, per docs/specs/README.md's contract. Also fixes two pre-existing issues this work exposed: - bootstrap/providers.php never existed, so Helium\Providers\AppServiceProvider (and thus any container binding placed in it) was never actually registered. - tests/Unit/QueueConfigTest.php "restored" QUEUE_CONNECTION by unsetting it entirely instead of putting back its prior value, letting the real .env's QUEUE_CONNECTION=redis leak into every later test in the same PHPUnit process -- invisible until a test (this PR's) dispatched a job expecting it to actually run under the forced "sync" queue connection. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
…tion) Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
Merges origin/master (issue #46 bank-governance, #47 managed-accounts) into this branch, consolidating the duplicate Idempotency-Key mechanism onto master's App\Support\IdempotencyStore (its own migration 2026_09_11_000202_create_idempotency_keys_table.php and IdempotencyKey model win; this branch's App\Support\HandlesIdempotency trait, its own IdempotencyKey model, and its own idempotency_keys migration are removed). SimilarityController::store() now calls IdempotencyStore::handle(), which requires the Idempotency-Key header (400 without it) and claims the key atomically via INSERT before running the callback. similarity_checks/ similarity_pairs migrations renamed to 2026_09_11_010010/010011 to sort after master's same-day organizations/problem_bank migrations. Also fixes 10 findings from an independent code review of PR #74: 1. SimilarityController::index() merged its two ->with() calls into one -- the second call's 'pairs.runA.user'/'pairs.runB.user' dot-relations were silently overwriting the first call's similarity_score-desc ordering closure for the 'pairs' key (Builder::with() merges via array_merge()). 2. JplagSimilarityEngine no longer uses a truthy check on minimumTokenMatch, which silently dropped an explicit 0 (a valid, distinct-from-unset value). 3. Excluded-team counts/reasons (missing source, unparseable) are now surfaced in the Check response (excluded_count/excluded_reasons) instead of being recorded in the snapshot but never returned -- the spec requires this ("para não sugerir cobertura completa"). 4. RunSimilarityCheckJob now folds SimilarityEngineResult::$unparseableRunIds into the same excluded-teams accounting instead of silently dropping them. 5. RunSimilarityCheckJob now implements ShouldBeUnique (keyed on the check id), matching JudgeRunJob's established pattern -- closes a queued->running race under queue redelivery that could run JPlag twice concurrently. 6. SimilarityController::store()'s concurrency-cap + duplicate-snapshot + create sequence now uses this codebase's established DB::transaction()+ lockForUpdate() pattern (see SubmitController) instead of Cache::lock(), which would have depended on the cache driver being cross-process-safe. 7. RunSimilarityCheckJob::dispatch() is now wrapped in try/catch -- if enqueueing itself throws, the check is marked failed instead of staying stuck at 'queued' forever with no job ever attempted. 8. store() now also validates the language is_active, matching what index() actually offers in its dropdown. 9. Flagged (not fixed here): App\Support\IdempotencyStore's payload_hash is still a plain json_encode() without key-order normalization, so a logically-identical retry with differently-ordered JSON fields could get a spurious 409. Left to the #47 owners since it's now shared code. 10. similarity_checks.user_id is now nullable with nullOnDelete() instead of cascadeOnDelete() -- deleting the requesting admin's account no longer destroys the check and its similarity_pairs evidence. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
Fixes 5 correctness/robustness findings from a second independent review of PR #74, plus a documentation-only fix for a suggestion the coordinator explicitly identified as harmful: 1. SimilarityController::index() computed capabilities.can_start by checking the same per-contest concurrency condition store() enforces (queued/running count < max_concurrent_per_contest), instead of always hardcoding true -- the UI can now disable the submit button instead of letting an admin predictably hit a 409. 2. bootstrap/providers.php documents why only AppServiceProvider is registered: AuthServiceProvider/EventServiceProvider reference classes that don't exist anywhere in this codebase, and RouteServiceProvider would re-register routes/web.php and routes/api.php a second time (already loaded via bootstrap/app.php's ->withRouting()). Not omitted by oversight -- registering them was suggested by the review and confirmed harmful, so this is a comment, not a registration. 3. Check responses now include pairs_truncated: a report whose returned pair count reaches the configured cap (JPlag's -n flag) can't be told apart, from stored data alone, from "there were exactly that many" -- flagging the ambiguity is more honest than a report that looks complete either way. 4. RunSimilarityCheckJob's result-persisting transaction is now wrapped in its own try/catch (extracted to persistResult()), recording the new 'result_persist_failed' safe error code instead of falling through to the generic failed() handler's 'worker_interrupted' mislabel. 5. Extracted the "admin/judge or the run's own owner" authorization check, previously copy-pasted between Api\RunController::downloadSource() and Frontend\SimilarityController::downloadSource(), into a new shared Controller::authorizeSourceAccess() helper (matching the existing authorizeScopedAccess()/authorizeRunAccess() pattern), used by both. The remaining lower-priority findings from that review (hand-rolled pagination vs paginate(), EligibleRunFinder loading all historical runs instead of a SQL-side "latest per team" query, the transaction-closure tagged-array return shape) are left as-is per the coordinator's guidance -- real but not correctness bugs. The "index() expensive if polled" finding doesn't apply: docs/specs/42-similarity.md is explicit that job updates are "manual e explícita nesta fase, sem polling em background". Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
matbrgz
added a commit
that referenced
this pull request
Sep 11, 2026
…s PR #73 review round 2 Merges in #74 (similarity backend), #75 (IdempotencyStore payload-hash key ordering), and #76 (Contest::getContestTime() sign fix). Only conflict was routes/web.php's `require` lines (kept all of them). A. Removes BocaWebcastZipBuilder::timeFile()'s local workaround for Contest::getContestTime()'s Carbon 3 signed-diff bug, now that #76 fixes the root cause directly on the model. timeFile() just calls $contest->getContestTime() again -- no more parallel implementation of the same elapsed-time calculation. The value produced is unchanged (the workaround already computed the correct positive figure), so no test expectations needed correcting, just the redundant code removed. B. Ten further review findings, all fixed: 1. Webcast\ScoreboardController::show() now null-checks $credential-> contest before use -- a still-active credential whose contest was soft-deleted (Contest uses SoftDeletes; ContestController::destroy() never cascades) previously reached Leaderboard::getScoreboard(null) and threw a TypeError instead of a clean 401. 2. BocaWebcastZipBuilder::teams() uses ?? instead of ?: for the fallback team name -- ?: silently replaced a team literally named "0" with the placeholder, since "0" is falsy in PHP. 3. AuthenticateWebcastCredential now eager-loads `contest` on the credential lookup (the one route a credential is meant to be polled on repeatedly). 4. WebcastController::storeCredential() no longer runs a redundant Rule::exists('contests','id') validation query alongside the Contest::find() + null-check that already answers the same question (and already correctly excludes soft-deleted contests). 5. WebcastController::export() now uses response()->download($path)-> deleteFileAfterSend(true) instead of a hand-rolled streamDownload()+ readfile()+register_shutdown_function() -- Symfony's BinaryFileResponse already calls ignore_user_abort(true) and unlinks the temp file in a finally block around the transfer loop, so a client-cancelled download still gets cleaned up via the framework's own mechanism. 6. WebcastController::index() now uses Eloquent's paginate() instead of hand-rolled page/perPage/lastPage/forPage bookkeeping, matching the convention Api\Frontend\ManagedAccountsController (#47) already established for the same "session-admin JSON list" shape. 7. Removed the dead hash_equals() re-check in AuthenticateWebcastCredential -- a row can only be returned by `WHERE token_hash = $hash`, so comparing them again could never evaluate false; it was presented as a timing-safety measure but wasn't one. 8. Left a comment on the storeCredential() secret-redaction workaround describing the pattern and a possible shared fix (an optional redact closure on IdempotencyStore::handle()) as a follow-up, since that would touch the shared class #47's endpoint also depends on. 9. BocaWebcastZipBuilder::resultCode() simplified in_array($run->status, ['judged'], true) to the direct $run->status !== 'judged' comparison. Regression tests added for #1 (soft-deleted contest -> 401), #2 (team named "0"), and #3 (relationLoaded('contest') on the credential lookup, tested directly against the query shape rather than by counting queries over a full request, which would also pick up Leaderboard::getScoreboard() 's own unrelated internal Contest::findOrFail() call). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
matbrgz
added a commit
that referenced
this pull request
Sep 23, 2026
O docblock e o teste diziam que o `golang` ficou quebrado "por três releases". O repositório não tem release nenhuma; conferido com `git log -S`, o identificador errado veio junto com o mapa original, no #74 (11/09/2026). O texto passa a dizer isso. De carona, uma palavra em português que tinha ficado num comentário em inglês. Co-Authored-By: Claude Opus 5.5 <[email protected]>
matbrgz
added a commit
that referenced
this pull request
Sep 23, 2026
…silêncio (#305) (#388) * A detecção de plágio prometia Go e falhava, e ignorava C e Scheme em silêncio (#305) Três achados do mesmo mapa, os três medidos com o jar fixado (JPlag 6.2.0, aarch64, 23/09/2026), e um deles é falha em produção e não lacuna: 1. `'go' => 'golang'`. `golang` é como o README do JPlag CHAMA a linguagem; o identificador que a CLI aceita é `go`. A interface oferecia Go, o job era despachado, e o JPlag saía com `Language golang does not exists` -- ou seja, toda checagem de Go falhava, com a banca já na tela. 2. As três entradas de C (`c_gcc13`, `c99_gcc`, `c_clang17`) estavam fora do mapa por uma suposição escrita no docblock: a de que o parser `c` do JPlag, marcado como legacy, miraria um padrão velho demais para o que compilamos. Medido, não é verdade -- `-l c` leu C17 de maratona sem um erro de ANTLR (inicializador designado, declaração dentro do `for`, VLA, `restrict`, `[static 1]`, `_Generic`, `_Static_assert`) e separou cópia com identificadores renomeados (1.000, casamento de 39 tokens) de solução de outro problema (0.000). O caminho tentador, mandar C pelo parser `cpp`, é o que mede pior: erra no inicializador designado (`extraneous input '.'`) e recupera com menos tokens. C é a linguagem mais usada numa maratona, e a regra das irmãs por extensão não podia ver esta ausência: como NENHUMA das três estava mapeada, não havia irmã para cobrar. 3. `scm` (Guile) entra pelo parser `scheme`, com a mesma discriminação medida (1.000 contra 0.000). `rkt` (Racket) fica FORA de propósito, e agora com teste que diz por quê: o parser `scheme` só lê `.scm`/`.ss` e o motor grava `submission.rkt`, então todos os envios voltam como `Nothing to parse` e a execução termina em `Not enough valid submissions!` -- trocar "não analisado em silêncio" por "falha na cara do operador" seria pior. Renomear também não salva: `#lang racket` é erro léxico na linha 1. O que impede a volta: `test_todo_identificador_usado_no_mapa_existe_no_jplag_fixado` carrega a seção `Languages:` do `--help` da versão fixada e confronta cada identificador do mapa com ela. Rodado contra o `master`, ele reprova apontando `go => 'golang'` -- que é o defeito que ninguém tinha. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Tira do mapa de plágio uma afirmação que não foi conferida (#305) O docblock e o teste diziam que o `golang` ficou quebrado "por três releases". O repositório não tem release nenhuma; conferido com `git log -S`, o identificador errado veio junto com o mapa original, no #74 (11/09/2026). O texto passa a dizer isso. De carona, uma palavra em português que tinha ficado num comentário em inglês. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Implements the real backend behind
Similarity.vue(issue #42), matchingdocs/specs/42-similarity.md:GET /api/frontend/similarityandPOST /api/frontend/similarity/checkson the web session guard + CSRF (routes/frontend_api_similarity.php,['auth','admin']), following the shared{"data": {...}}envelope, status codes, andIdempotency-Keycontract fromdocs/specs/README.md.similarity_checks/similarity_pairsmigrations, snapshotting the exact run IDs/hashes and engine config used, so a completed report never silently drifts.RunSimilarityCheckJob(ShouldQueue,queued -> running -> completed|failed), with aSimilarityEngineInterfaceabstraction:JplagSimilarityEngineshells out to a pinned, checksum-verified JPlag jar viaProcess, in an isolated temp dir with no shell interpolation; tests useTests\Support\Similarity\FakeSimilarityEngine(deterministic, no network, no real jar).EligibleRunFinder: last accepted run per team (user_id), tie-broken by highest run id, excluding runs whose source is missing on disk (safe reason code, never a path). Practice-run exclusion is a documented no-op — issue Persistent practice/training mode outside live contests #43 hasn't added a column to distinguish practice submissions yet.HandlesIdempotencytrait +idempotency_keystable: same key + same payload replays the saved response; same key + different payload is 409.GET /api/frontend/similarity/runs/{run}/sourcemirrorsApi\RunController::downloadSource()'s exact authorization check.Cache::lockaround the concurrency-check + duplicate-snapshot-check + create sequence instore(), closing a real INSERT/INSERT race for concurrent requests without anIdempotency-Key(no DB-level unique constraint could catch it otherwise).JPlag / JDK decision
Pinned to v6.2.0 — the last release built for JDK 21 (v6.3.0 bumped the minimum to JDK 25), matching the
openjdk21-jdkthe mainDockerfilealready installs forAutoJudgeService. The jar is downloaded and sha256-verified at Docker build time, exported as real containerENV(single source of truth), and re-verified byJplagSimilarityEnginebefore every invocation. The.jplagresult format (not guessed from docs) was confirmed by actually running the pinned jar locally against a small fixture and inspectingrunInformation.json/topComparisons.jsonbyte for byte — seedocs/specs/42-similarity.md's "Estado da implementação" for exactly how.Two pre-existing bugs fixed along the way
bootstrap/providers.phpnever existed in this repo, soHelium\Providers\AppServiceProvider(and any container binding placed in it, including this PR'sSimilarityEngineInterfacebinding) was never actually registered by Laravel 11's boot sequence. Added the file.tests/Unit/QueueConfigTest.php"restored"QUEUE_CONNECTIONin itsfinallyblock by unsetting it entirely (putenv($key)with no value) instead of putting back its prior value — which let the real.env'sQUEUE_CONNECTION=redisleak into every subsequent test in the same PHPUnit process. Invisible until this PR's job dispatch, since no earlier test dispatched a real (non-Queue::fake()) job expecting it to run under the forcedsyncconnection. Fixed to snapshot/restore the actual prior value.Open gates (per spec's "Perguntas para decisão")
SIMILARITY_BASE_CODE_PATH), not a UI field — no per-problem base-code model exists yet.Closes #42.
Test plan
php artisan test— 633 passed (618 baseline + 15 new for this issue), full suite green.tests/Feature/SimilarityTest.phpcovers every "Critérios de aceite" bullet: stable snapshot + idempotent retry, pending/WA-after-AC not replacing the snapshot with id-tiebreak, admin-gets-pairs/participant-gets-403-and-can't-guess-the-source-URL, engine timeout/failure never leaving a check stuckrunning, zero-pairs vs unsupported-language being distinct outcomes, plus the concurrency-lock and non-timeout-interruption-labeling fixes from code review.code-reviewskill run on the diff; all findings fixed or documented (see commit history / spec doc).🤖 Generated with Claude Code
https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn