Deimos
Deimos screens programming exercise participations for malicious intent against the build infrastructure. An instructor triggers a run over a course or a single exercise, the server reconstructs each participation's submission history, classifies it with a language model, and emails the initiator a summary.
This page is for developers working on the module. The user-facing behaviour is documented under malicious participation analysis for instructors and Deimos setup for administrators.
Design constraints
Three constraints shape most of the code and are worth internalising before changing anything:
- The analysed input is written by the adversary. Student code is the thing being judged, and it can contain whatever its author wants, including text aimed at the model. Everything that touches the payload has to assume this.
- A silent failure is worse than a loud one. The output influences whether an instructor suspects a student of misconduct. A run that fails halfway must not be indistinguishable from a run that found nothing.
- Nothing is persisted. Runs produce an email and a log line. There is no schema, no run history, no result view.
Enablement
The module is behind two independent gates, and both must be open:
| Gate | Mechanism | Effect when closed |
|---|---|---|
| Startup | artemis.deimos.enabled, evaluated by DeimosEnabled as a Spring @Conditional | No Deimos bean exists at all; the REST endpoints are not mapped |
| Runtime | Feature.Deimos, applied via @FeatureToggle on DeimosResource | Endpoints return 403; the client hides the trigger buttons |
Every Deimos bean carries @Conditional(DeimosEnabled.class) and @Lazy. When you add a new one, keep both, or the
module starts leaking into instances that did not enable it.
Startup validation
Configuration is validated eagerly. Deimos calls the LLM preset assigned under artemis.deimos.llm-preset, which has
no default: DeimosLlmConfiguration reports the assignment to LlmConfigurationValidator, which stops the boot when
it is missing, names an unknown preset or an embeddings preset, or when the preset's endpoint is invalid. The limits
under artemis.deimos.payload.* and artemis.deimos.batch.* are checked by ConfigurationValidator; a violation
stops the boot with DeimosConfigurationException, rendered by DeimosConfigurationFailureAnalyzer into an
actionable message, see Evidence construction.
Whether the provider accepts the api-key of the preset's endpoint is not checked at startup, because an empty key
is a valid setup for an unauthenticated OpenAI-compatible endpoint (Artemis then sends no Authorization header). A missing or wrong key surfaces at the first request as HTTP 401
or 403, which DefaultDeimosLlmClient reports as LLM_AUTHENTICATION_FAILED.
DefaultDeimosLlmClient obtains its chat client from LlmClientService, so integration tests route it through the
mocked chat model like every other preset.
Package layout
| Package | Contents |
|---|---|
web | DeimosResource, the two POST endpoints, role annotations and the feature toggle |
api | DeimosBatchApi, the interface the resource implements |
service | DeimosBatchService (validation, scheduling, mail), DeimosAnalysisService (evidence and orchestration), DeimosLlmClient with DefaultDeimosLlmClient, DeimosPromptTemplateService, DeimosSnapshotReader (the files of one commit), DeimosDiffBuilder (the unified diffs within the size limits, and the escaping of paths in them) |
repository | DeimosBatchParticipationRepository, the candidate-selection queries |
dto | Request, summary, email and failure records |
exception | DeimosConfigurationException, DeimosLlmException, DeimosSnapshotHistoryException, plus the failure analyzer |
config | DeimosEnabled, DeimosLlmConfiguration, DeimosLimits (defaults of the configurable limits), DeimosInfoContributor |
Request path
DeimosResourceauthorizes via@EnforceAtLeastInstructorInCourseor@EnforceAtLeastInstructorInExerciseand loads the triggering user, which is only ever used as the mail recipient.DeimosBatchServicevalidates the window (order, maximum length, candidate count), generates a run id, and submits the run to thedeimosTaskExecutor. A rejected submission surfaces as503. The endpoint returns202with the run id immediately.- The background task collects candidate participation ids in pages, then calls
DeimosAnalysisService.analyze. - Per participation, the service builds the evidence, calls the model, and records either a verdict or a typed
failure. A single participation failing never aborts the run, with one exception:
LLM_AUTHENTICATION_FAILEDstops the loop, because every further request would be rejected as well. The participations not reached are recorded in one batch-levelFailedAnalysis(participation idDeimosBatchSummaryDTO.BATCH_LEVEL_FAILURE_PARTICIPATION_ID) and added tofailed. DeimosBatchServiceturns the summary into aDeimosAnalysisCompleteEmailDTOand sends the completion mail.
Candidate selection lives entirely in JPQL. Note that the course-scoped query resolves the owning course through
COALESCE(e.course.id, ex.course.id), so exam exercises of that course are included.
Evidence construction
DeimosAnalysisService.buildSnapshotHistory reconstructs the history from ProgrammingSubmission rows, not by
walking the git graph. Consequences worth knowing:
- Several commits pushed together collapse into one snapshot.
- Submissions without a commit hash never reach the loop; the repository query filters them out and they leave no
trace. A blank hash reaches the loop, is skipped with a log line, and is marked in the payload as a submission that
could not be examined. It is recorded as a
MISSING_COMMIT_HASHomission. - Snapshots are read with
DeimosSnapshotReader, which leaves a file out as binary only when both its extension and the beginning of its content say so, and reads no more than that beginning for such files. A commit with a text file above 10 MiB, text files above 100 MiB in total or more than 100,000 entries fails the read, as reading all files of a repository does elsewhere: the whole snapshot is held in memory before any payload limit applies, and leaving the excess out would hide it from the marker scan. Scripts such as.shor.bat, whose extensions count as binary for the repository exports, are therefore part of the evidence. Scripts are never classified away by their content, and a file without a binary extension is always read as text, so a NUL byte cannot hide either. Every other entry (binary files, symbolic links and submodules) is reported with the id of the object it points to. Its path is scanned for imitated markers and is not named in the payload while the entry is not text; a file that was text in an earlier snapshot appears in the diffs of that time, including the deletion when it stops being text. - An entry that is not text and whose object id differs from the previous snapshot is recorded as a
NON_TEXT_FILEomission, unless it matches the template's entry at the same path, which keeps unchanged files such asgradle-wrapper.jarand a restored template version out of the report. Only the content counts: a change of the file mode alone is not recorded. Deleted entries leave nothing to examine. These omissions are recorded before any budget decision, so a dropped snapshot section keeps them. The payload gets one notice with their number but no paths, because the names are the student's. - The baseline is a commit of the template repository, resolved once per participation so the diffs and the marker
scan share it. It is deliberately not the setup commit of the participation repository: that history is the
student's, and
getFirstCommitWithMessagewould accept an older commit with the setup message from a merged history or another branch, which would then hide its files from the diffs and its markers from the scan. A missing template participation, branch or commit throwsDeimosSnapshotHistoryExceptionrather than falling back to an empty baseline, which would attribute the whole template to the student. - The participation repository is a copy without history, so later template changes never reach it. Deimos therefore
approximates the template at participation setup: the commit of the latest submission of the template participation
whose
submissionDateis at or before the participation'sinitializationDate. Both dates are set by the server,createInitialSubmissionrecords the template at setup, and a push to the template records its head commit unless a submission for that commit already exists.TESTsubmissions are skipped, because they carry the commit of the tests repository. A recorded commit that still exists in the template repository is used even when it is no longer reachable from the branch: only staff and the server write that repository, so an orphaned commit is still a genuine template state. - Without an initialisation date (programming practice participations), without an eligible record, or when the recorded commit object is gone, the baseline is the head of the exercise branch, as it was before. This is best effort: it improves the attribution where the records match the copied state, and can keep or introduce errors where they do not. Known gaps are the time between the copy and the recorded date, missing or deleted template submissions, a repository recreated after cleanup under the preserved date, a force push back to a commit that was already recorded (it gets no new submission, so a later record wins), and practice participations copied from the graded repository, whose content comes from the graded participation's baseline. Recording the template commit when the repository is copied, inheriting it into practice copies and keeping its objects would close most of these gaps.
Diffs are real unified diffs built with JGit in memory, under four configurable byte budgets. The defaults live in
DeimosLimits and every @Value fallback refers to them; application.yml repeats them, and DeimosLimitsTest
keeps the two in line.
Property under artemis.deimos.payload | Default | Purpose |
|---|---|---|
max-file-input-bytes | 256 KiB | Files larger than this are not diffed at all |
max-file-diff-bytes | 32 KiB | Per-file diff cap, truncated at a line boundary; when that keeps no added line although the first hunk has one, as when the first changed line alone exceeds the cap, the beginnings of the first removed and the first added line of that hunk share the space |
max-payload-bytes | 128 KiB | Hard bound on the untrusted history, notices and headers included; the prompt text around it is not counted |
final-state-reserved-bytes | 32 KiB | Held back from the incremental loop so the cumulative diff always has room |
ConfigurationValidator requires every byte limit to be at least DeimosLimits.MIN_BYTE_LIMIT (1 KiB),
final-state-reserved-bytes < max-payload-bytes and max-file-diff-bytes <= max-payload-bytes. The floor is what
keeps the bound hard for small settings: the snapshot-omitted, missing-hash and non-text notices, the final-state header and the
128 bytes each diff keeps for its own omission notice (DIFF_OMISSION_NOTICE_RESERVED_BYTES) all have to fit inside
the reservation. Byte arithmetic uses long, so large configured values cannot overflow.
The batch limits artemis.deimos.batch.max-participations-per-run (default 5000) and
artemis.deimos.batch.max-window-days (default 31) are injected into DeimosBatchService the same way.
DeimosInfoContributor publishes the window as deimosMaxWindowDays on /management/info, and the date-range dialog
reads it from ProfileService, so the client never validates against a different value than the server.
The reservation exists so that exhausting the budget cannot leave the model judging only a chronological prefix. The
cumulative section is emitted unless it would be empty or would exactly repeat a single snapshot whose text was not
omitted; NON_TEXT_FILE omissions do not count here. That case is decided before the section is built, so a truncated copy of complete evidence cannot mark the participation as
incompletely checked. Every
budget-caused omission is written into the payload as an explicit marker.
Every omission is also recorded as a DeimosOmission with its reason (FILE_INPUT_LIMIT, FILE_DIFF_LIMIT,
PAYLOAD_LIMIT, MISSING_COMMIT_HASH, NON_TEXT_FILE), the file and the snapshot. For the limits, the reason is the
limit that actually bound. A truncated diff counts as
FILE_DIFF_LIMIT only when the per-file cap was no larger than what was left of the section budget. When a whole
snapshot section is dropped, the file-level omissions of its text diff are replaced by one snapshot-level
PAYLOAD_LIMIT entry; its NON_TEXT_FILE omissions are kept. The
system prompt tells the model that omitted content is unexamined and a reason for caution, and that a notice about
binary files or links marks content it did not receive without establishing malicious intent by itself.
Prompt and trust boundary
The system and user prompts live in src/main/resources/prompts/deimos/ and are loaded by
DeimosPromptTemplateService.
The payload is fenced between a 128-bit random sentinel carried in both delimiters. The sentinel is regenerated, not stripped, if it happens to occur inside the payload, so evidence is never altered to make fencing work. The system prompt instructs the model to treat the region strictly as evidence, to ignore any instruction, verdict or marker appearing inside it, and to weigh attempts at steering the classification as a signal in their own right.
File paths and metadata pass through DeimosDiffBuilder.escapeMetadata, which escapes newlines and control characters rather than
rejecting them. Rejecting a hostile filename would let a student suppress the analysis of their own participation,
which is the opposite of what you want.
Imitated fence markers
buildSnapshotHistory scans the full content of every file that changed against the previous snapshot, and every new
file path, for lines imitating a fence marker, before any budget applies. Padding a submission therefore cannot push a
forged marker out of sight of this check, even when it pushes it out of the payload. The pattern in DeimosFenceMarkers matches
---, BEGIN or END, UNTRUSTED and DATA, case-insensitively and with any whitespace in between (Unicode spaces
included), anywhere in a line and with any identifier. It must stay linear in the input: the fixed -{3} prefix and
the possessive quantifiers mean a long run of hyphens or whitespace is scanned once, and the scan reuses one matcher
with its region set to each line. Marker lines that the template's version of the same file already contains are not
attributed to the student, as often as the template contains them, and findings are deduplicated by file and line text.
Only a SHA-256 digest of each finding's key is retained, for at most MAX_TRACKED_FINDINGS_PER_PARTICIPATION
distinct findings; beyond that, the verdict is unchanged and the email reports the count as a lower bound.
The findings live in a per-participation ParticipationEvidence owned by analyze, so they survive a snapshot that
fails later or a failed model call. If the random sentinel itself shows up in student content, which would mean it
leaked from Deimos, a server warning is logged; the content is never logged.
Verdict precedence
Every analysed participation receives one DeimosVerdict, highest applicable first:
MANIPULATION_ATTEMPT: at least one finding. Holds without the model. The model is still called whenever a non-empty history can be built; its answer, or the failure type of the call, of the repository or of an empty history, is kept as additional information.MALICIOUS: the model's classification.INCOMPLETELY_CHECKED: the model found nothing malicious, but at least one omission was recorded. It replaces onlyBENIGN. A participation whose only changes areNON_TEXT_FILEomissions has no text for the model and receives this verdict without a request.BENIGN: the model's classification over complete evidence.
Apart from these two cases without the model, a participation without a model verdict is a failure with its
DeimosFailureType.
Verdict parsing
DefaultDeimosLlmClient.parseVerdict is deliberately tolerant about packaging and strict about content. It accepts a
raw object, a fenced block, or an object embedded in a preamble, but it requires both malicious and rationale.
A response missing either is rejected as LLM_UNPARSEABLE rather than being read as benign.
Candidates are grouped into tiers of decreasing confidence: the whole response, then fenced blocks, then balanced
objects found in the text. The first tier that yields a verdict decides. Within that tier, identical verdicts are
collapsed, but two differing verdicts are rejected as LLM_UNPARSEABLE instead of being resolved by position:
nothing in a sequence of objects says which one is final, and taking the first could report a malicious participation
as benign. Verdicts that differ in malicious are rejected across tiers as well, because a fence does not mark the
final answer either: a fenced object may be a quoted example followed by the actual answer. A classification stated
outside a recoverable object counts too, so prose with an unmatched brace or quote cannot hide a later verdict.
Quotes only delimit strings inside an object, and an opening brace that is never closed is treated as prose: the text
after it is scanned again, so a verdict following it is still recovered. After MAX_UNMATCHED_BRACE_RECOVERIES such
braces the response is rejected as LLM_UNPARSEABLE, which bounds the work and keeps a differing verdict from hiding
in the part that was not scanned.
Failure taxonomy
DeimosFailureType distinguishes why a participation produced no verdict. This is not cosmetic: without it, "there
was nothing to analyse" and "the model was unreachable" collapse into one counter and a broken run looks clean.
classifyCallFailure maps transport exceptions onto the LLM categories after the HTTP client exhausts the preset’s max-retries.
credentialRejectionStatus runs first and looks for a RestClientResponseException with status 401 or 403 anywhere in a
bounded, cycle-safe cause chain, so a wrapper whose message mentions a timeout cannot hide it. Such a failure becomes
LLM_AUTHENTICATION_FAILED with a fixed message carrying only the status and no cause, because the HTTP exception
can contain provider-supplied text; the analysis service logs that message without the exception.
DeimosBatchSummaryDTO.failureCountsByType reconciles the per-participation details with the total, so a run that
aborted before reaching individual participations cannot report Failed: 200 next to a breakdown summing to one. The
participations not accounted for are counted under the category of the batch-level entry, which is
LLM_AUTHENTICATION_FAILED for an aborted run and OTHER when the run failed as a whole. When the participation limit
is exceeded while candidates are being collected, the failure count is the number observed so far, not 1.
Testing
DeimosResourceIntegrationTest covers the access rules and window validation of both endpoints. Two constraints shape
it:
- It extends an existing base class and uses no
@MockitoBean. The architecture rules forbid that outside the allowed base classes, because it forks a Spring context. deimosTaskExecutoris synchronous under the test profile, as for mail and quiz statistics. Without that, the queued batch races the assertions and the database teardown.
Requests use a window with no candidate participations, so an accepted run has nothing to analyse and never reaches the model.
DeimosAnalysisCompleteEmailRenderingTest renders the real email template with the production messages in English
and German, so a broken Thymeleaf expression or a missing translation fails a test rather than an email.
Client-side, DeimosDateRangeModalComponent compares elapsed milliseconds rather than using dayjs' calendar-aware
diff, so that its validation matches the server's Duration.between across a DST transition. The regression test
uses explicit offsets and asserts on elapsed time, not on the dayjs expression.
Known gaps
These are deliberate omissions, not oversights, and the most likely places to extend the module:
- No persistence. Runs leave no record, which rules out repeat-offender detection, cross-course correlation and audit reconstruction.
- No result view. The completion email is the only output.
- No model cascade. Each participation is classified by exactly one model. Benchmarking showed a two-stage screening-then-escalation arrangement performing better, but that is not implemented.
- No input sanitisation beyond fencing. Adversarial directives in comments and identifiers are fenced and contextualised, not neutralised. Only imitated fence markers are detected deterministically; homoglyphs and zero-width characters inside a marker are not.
- No confidence signal. The model returns a boolean, so there is nothing to threshold or route on.