Repository navigation
Fix scoreboard-ranking inversion: Contest::getContestTime() sign bug - #76
Conversation
CRITICAL: Contest::getContestTime() computed elapsed time as
now()->diffInSeconds($this->start_time). Under Carbon 3 (this app's
pinned version), $a->diffInSeconds($b) returns $b's timestamp minus
$a's -- signed, not absolute -- so this returned a NEGATIVE value for
the entire duration a contest was running, instead of positive elapsed
seconds since start.
This corrupted every consumer across the app: Run.contest_time,
Run.judged_time, Task.completed_time, and Clarification.answered_time
were all negative (13 call sites in SubmitController, JudgeController,
StaffController, SiteController, AutoJudgeService,
ReconcileStuckRunsCommand, and the Api\* equivalents). Worse,
Score::updateScore() derives solved_time = floor(contest_time / 60),
and Leaderboard::getScoreboard() ranks by total_time ascending -- so a
LATER solve produced a MORE NEGATIVE (i.e. numerically smaller)
total_time and ranked BETTER, inverting the scoreboard's core ranking
for every contest this app has ever run.
tests/Unit/ContestModelTest.php had a test that explicitly asserted
the negative result as correct ("The method returns the time
difference (negative when contest has started)"), which is why this
went uncaught -- the test was calibrated to the bug rather than the
intended behavior.
Fix: swap the receiver/argument
($this->start_time->diffInSeconds(now())) so elapsed time is
correctly signed positive. Updated the test that encoded the wrong
expectation, and added ScoreLeaderboardRankingTest -- an end-to-end
test through the real Contest::getContestTime() -> Score::updateScore()
-> Leaderboard::getScoreboard() pipeline (not literal/fixed total_time
values, which is how every other existing scoreboard test avoided
tripping over this) proving an earlier solver now ranks ahead of a
later one. Verified this new test fails against the pre-fix code
(-30 instead of positive) and passes after the fix.
Found while independently reviewing PR #73 (webcast export), which
had already discovered this bug and worked around it locally in its
own BocaWebcastZipBuilder rather than fixing the shared root cause --
that workaround should be simplified once this lands.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
|
One finding from independent review, confirmed correct but out of this PR's scope to fix in code: this fix corrects the sign only for future calls to Deployment note for whoever operates this: if this is deployed to an environment with existing contest data from before this fix, run a one-time backfill re-computing Merging as-is since the fix itself is verified correct and this is an operational note, not a code defect. |
…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
Closes #89. `users.icpc_id` has existed since 2025_11_25_000007 and nothing used it -- not one reference in the codebase, and no form that could set it. BOCA produces the file it exists for in src/admin/report/icpc.php: one CSV line per team, in final standings order, usericpcid, placement, solved, total time, first solve This is not the webcast export of #44. That one streams a live scoreboard to a ceremony display; this is the record of what happened, and its consumer is a person filing results with a regional. Three surfaces, because filing results happens in more than one way: - `IcpcReportBuilder` holds the logic, reading Leaderboard::getScoreboard() -- the same source the public scoreboard uses, including #76's getContestTime() sign fix, without which every time here would be negative. - `GET /api/frontend/contests/{contest}/icpc-report` for the browser: admin session, text/csv attachment, no-store. - `php artisan contest:icpc-report {contest} [--output=]` for the contest host at 2am over ssh, which is where this usually actually happens. Teams still missing an icpc_id are reported rather than enforced: BOCA files the report with the column blank, and an organiser may well be exporting before the ids are in. The command names them, the endpoint counts them in X-Icpc-Teams-Missing-Id. Either way you learn it before sending the file, not after. The practice contest (#43) is refused by both: it is not an event and has no standings, and it must not be reachable through an event-shaped export. `icpc_id` is now settable on the backend user form, which is the only place a contest account is created outside the specced managed-accounts API. Adding it there too would change #47's frontend contract, so that is left alone. Claude-Session: https://claude.ai/code/session_01Pvf2R8xtgbWQm1wRvjBqQY Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
CRITICAL.
Contest::getContestTime()computed elapsed time asnow()->diffInSeconds($this->start_time). Under Carbon 3 (this app's pinned version),$a->diffInSeconds($b)returns$b's timestamp minus$a's -- signed, not absolute -- so this returned a negative value for the entire duration a contest was running, instead of positive elapsed seconds since start.This corrupted every consumer:
Run.contest_time,Run.judged_time,Task.completed_time,Clarification.answered_time(13 call sites). Worse,Score::updateScore()derivessolved_time = floor(contest_time / 60), andLeaderboard::getScoreboard()ranks bytotal_timeascending -- so a later solve produced a more negative (numerically smaller)total_timeand ranked better, inverting the scoreboard's core ranking for every contest.tests/Unit/ContestModelTest.phphad a test explicitly asserting the negative result as correct ("The method returns the time difference (negative when contest has started)") -- the test was calibrated to the bug, not the intended behavior, which is why this went uncaught.Found while independently reviewing PR #73 (webcast export), which had already discovered this bug and worked around it locally in its own
BocaWebcastZipBuilderrather than fixing the shared root cause -- that workaround should be simplified once this lands (will follow up on that PR).Fix
Swap the receiver/argument (
$this->start_time->diffInSeconds(now())) so elapsed time is correctly signed positive.Test plan
ContestModelTest's test that encoded the wrong (negative) expectation.tests/Unit/ScoreLeaderboardRankingTest.php: an end-to-end test through the realContest::getContestTime()->Score::updateScore()->Leaderboard::getScoreboard()pipeline (not literal/fixedtotal_timevalues, which is how every other existing scoreboard test avoided tripping over this) proving an earlier solver now ranks ahead of a later one.-30instead of positive) and passes after the fix (confirmed by temporarily reverting just theContest.phpchange and re-running).🤖 Generated with Claude Code
https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn