Skip to content

Similarity analysis backend (issue #42) - #74

Merged
matbrgz merged 4 commits into
masterfrom
feature/issue-42-similarity-analysis
Sep 11, 2026
Merged

matbrgz merged 4 commits into
masterfrom
feature/issue-42-similarity-analysis

Conversation

@matbrgz

@matbrgz matbrgz commented Sep 11, 2026

Copy link
Copy Markdown
Member

Summary

Implements the real backend behind Similarity.vue (issue #42), matching docs/specs/42-similarity.md:

  • GET /api/frontend/similarity and POST /api/frontend/similarity/checks on the web session guard + CSRF (routes/frontend_api_similarity.php, ['auth','admin']), following the shared {"data": {...}} envelope, status codes, and Idempotency-Key contract from docs/specs/README.md.
  • similarity_checks / similarity_pairs migrations, snapshotting the exact run IDs/hashes and engine config used, so a completed report never silently drifts.
  • RunSimilarityCheckJob (ShouldQueue, queued -> running -> completed|failed), with a SimilarityEngineInterface abstraction: JplagSimilarityEngine shells out to a pinned, checksum-verified JPlag jar via Process, in an isolated temp dir with no shell interpolation; tests use Tests\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.
  • A reusable HandlesIdempotency trait + idempotency_keys table: same key + same payload replays the saved response; same key + different payload is 409.
  • GET /api/frontend/similarity/runs/{run}/source mirrors Api\RunController::downloadSource()'s exact authorization check.
  • A per-contest Cache::lock around the concurrency-check + duplicate-snapshot-check + create sequence in store(), closing a real INSERT/INSERT race for concurrent requests without an Idempotency-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-jdk the main Dockerfile already installs for AutoJudgeService. The jar is downloaded and sha256-verified at Docker build time, exported as real container ENV (single source of truth), and re-verified by JplagSimilarityEngine before every invocation. The .jplag result format (not guessed from docs) was confirmed by actually running the pinned jar locally against a small fixture and inspecting runInformation.json/topComparisons.json byte for byte — see docs/specs/42-similarity.md's "Estado da implementação" for exactly how.

Two pre-existing bugs fixed along the way

  • bootstrap/providers.php never existed in this repo, so Helium\Providers\AppServiceProvider (and any container binding placed in it, including this PR's SimilarityEngineInterface binding) was never actually registered by Laravel 11's boot sequence. Added the file.
  • tests/Unit/QueueConfigTest.php "restored" QUEUE_CONNECTION in its finally block by unsetting it entirely (putenv($key) with no value) instead of putting back its prior value — which let the real .env's QUEUE_CONNECTION=redis leak 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 forced sync connection. Fixed to snapshot/restore the actual prior value.

Open gates (per spec's "Perguntas para decisão")

  • No retention policy for reports (they never expire/delete) — left for the team.
  • Caps chosen concretely: 60 teams/job, 300 pairs/report, 2 concurrent checks/contest (all env-configurable) — team can revisit.
  • Base-code exclusion is a server-side config path (SIMILARITY_BASE_CODE_PATH), not a UI field — no per-problem base-code model exists yet.
  • Network isolation for the JPlag process is only "no flag opts into network use" at the PHP level; OS/container-level egress denial is flagged as an infra follow-up, out of scope for this PHP change.

Closes #42.

Test plan

  • php artisan test — 633 passed (618 baseline + 15 new for this issue), full suite green.
  • New tests/Feature/SimilarityTest.php covers 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 stuck running, zero-pairs vs unsupported-language being distinct outcomes, plus the concurrency-lock and non-timeout-interruption-labeling fixes from code review.
  • code-review skill run on the diff; all findings fixed or documented (see commit history / spec doc).

🤖 Generated with Claude Code

https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn

matbrgz and others added 4 commits September 11, 2026 01:07
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
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
matbrgz merged commit ecd9e5e into master Sep 11, 2026
@matbrgz
matbrgz deleted the feature/issue-42-similarity-analysis branch September 11, 2026 11:44
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]>
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.

Add plagiarism/similarity detection for submissions (JPlag-style)

1 participant