docs: simplify project guides and add GPLv3
This commit is contained in:
1 parent
e4de6d0f9a
commit
76d32bb79f
59 files changed
+2267
-8843
No files matched your search
@@ -3,12 +3,13 @@
|
||||
Use the source that owns the fact being discussed. Read the relevant source before changing a dependent document or generated artifact.
|
||||
|
||||
- The user's request sets the authorized task scope and product choices for that task.
|
||||
- When present, the root PRD.md defines product requirements, delivery stages, and acceptance criteria. It is a self-contained specification, not an implementation status report.
|
||||
- Source code shows behavior that exists in this checkout. A passing test gives evidence only for the behavior it exercises.
|
||||
- api/core/openapi.yml, api/ml/openapi.yml, and api/runner/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output.
|
||||
- api/core/openapi.yml, api/ml/openapi.yml, api/runner/openapi.yml, and api/labd/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output.
|
||||
- Backend migrations define the database schema. sqlc query files define queries that sqlc generates.
|
||||
- Makefiles and checked-in tool configuration define supported project commands and options. Lockfiles preserve selected application dependency versions. Toolchain declarations define runtime versions; the Go backend uses exact version 1.26.9. Compose and Dockerfiles define image references, including intentionally moving `latest` or `alpine` tags.
|
||||
- Compose, Nginx, and observability configuration define the local deployment scaffold. They do not prove that a remote deployment or production security review occurred.
|
||||
- docs/ru/ARCHITECTURE.md records product and architecture decisions. docs/en/ARCHITECTURE.md is its maintained English counterpart. These documents include planned behavior and must label it as planned.
|
||||
- docs/ru/ARCHITECTURE.md explains the architecture and current service boundaries. docs/en/ARCHITECTURE.md is its maintained English counterpart. Any planned behavior must be labeled as planned.
|
||||
- README.md is the primary Russian entry point; README.en.md is its maintained English counterpart. Neither replaces service guides or contracts.
|
||||
|
||||
When sources disagree, do not resolve the conflict by file age alone. State what the code currently does, what the design asks for, and which source needs correction. Ask for a decision only when the conflict blocks work within the authorized scope.
|
||||
|
||||
@@ -27,8 +27,8 @@ Use PostgreSQL through the repository's pgx and sqlc boundary. Schema changes ar
|
||||
|
||||
Prefer the selected wahrwelt-kit packages only where they provide a useful technical boundary and have a pinned, verified version. Libraries such as logging, HTTP, metrics, and PostgreSQL helpers do not own product behavior. Do not add unused JWT, WebSocket, or other framework dependencies.
|
||||
|
||||
Redis belongs behind the outbound cache port and its secondary adapter. Bootstrap owns its client lifecycle. Redis, PostgreSQL, and the SeaweedFS bucket are required for readiness. Set cache entries with a positive TTL; future product consumers must tolerate misses, eviction, and restart. Do not treat cache entries as authoritative product records or add product caching without defining ownership and invalidation.
|
||||
Redis belongs behind the outbound cache port and its secondary adapter. Bootstrap owns its client lifecycle. Redis, PostgreSQL, and the SeaweedFS bucket are required for readiness. Set cache entries with a positive TTL; consumers must tolerate misses, eviction, and restart. Do not treat cache entries as authoritative product records or add product caching without defining ownership and invalidation.
|
||||
|
||||
SeaweedFS belongs behind the outbound ObjectStorage port and the seaweedfs secondary adapter. Keep AWS SDK and S3 types inside that adapter. Bootstrap owns client resources; HeadBucket checks readiness without creating the bucket. Stream object content and close Get response bodies. Product upload/download authorization, content limits, and retention rules must be defined before exposing file operations.
|
||||
|
||||
Current code is an operational scaffold. Do not describe the health handler, database ping, or wiring as account, assessment, matching, or invitation behavior.
|
||||
Describe implemented behavior from the current usecases, routes, and tests. Health checks and dependency wiring alone do not establish a working product flow.
|
||||
@@ -5,10 +5,11 @@ The repository has separate public and internal OpenAPI contracts:
|
||||
- api/core/openapi.yml describes browser-to-Go operations.
|
||||
- api/ml/openapi.yml describes internal Go-to-ML operations.
|
||||
- api/runner/openapi.yml describes internal operations between Go and the code runner.
|
||||
- api/labd/openapi.yml describes internal lab provisioner operations.
|
||||
|
||||
Edit the split source files referenced by these roots. Use the API Makefile to merge schemas, bundle, and lint every specification. Do not hand-edit bundled files.
|
||||
|
||||
The selected Go server generator is ogen. The generated Go handler is mounted under chi. Orval generates the TypeScript client and related frontend artifacts. The Go ML client is configured in backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. The Go code runner client is configured in backend/codegen/ogen-code-runner.yml and generated into backend/internal/adapter/secondary/code_runner/api/. datamodel-code-generator uses ml/codegen/pyproject.toml to generate Pydantic v2 models in ml/src/lincodex_ml/api/models.py from the ML bundle. There are three code generation unit directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Each consumer owns the configuration for its generated code; contract sources remain shared under api/.
|
||||
ogen generates Go servers and clients; chi mounts the backend HTTP handler. Orval generates frontend clients, hooks, schemas, and mocks. datamodel-code-generator generates ML Pydantic v2 models. Each consumer keeps configuration in its own codegen/ directory: backend, frontend, ml, runner, or labd. Backend client settings are ogen-ml.yml, ogen-code-runner.yml, and ogen-labd.yml; their output stays in the corresponding secondary adapter's api/ directory. Contract sources remain shared under api/.
|
||||
|
||||
OpenAPI 3.2.0 is the target contract version. Verify only the feature subset used by this repository through the pinned bundler, linter, ogen, Go runtime path, Orval, Python Pydantic models, and documentation pipeline. A passing fixture does not establish full support for every OpenAPI 3.2 feature. Record the exact checks run.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Database standard
|
||||
|
||||
PostgreSQL is the planned system of record for product data and future background jobs. The current schema contains only what the technical scaffold needs.
|
||||
PostgreSQL is the system of record for product data and durable jobs. Use the migrations and queries to establish the current schema.
|
||||
|
||||
Put schema changes in ordered backend/db/migrations/ files and queries in backend/db/queries/. sqlc output is derived. Never edit generated SQL models or query code by hand.
|
||||
|
||||
|
||||
@@ -4,14 +4,14 @@ The frontend is a React single-page application built with Vite, TypeScript, and
|
||||
|
||||
When changing the frontend toolchain or dependencies, select current stable releases and commit the matching runtime declarations, package manifest, and lockfile updates. Do not add prereleases unless the task explicitly calls for them. Keep the lockfile so installs remain repeatable after selecting the stable release.
|
||||
|
||||
Use FSD boundaries when product features are added: app composes pages, widgets, features, entities, and shared code. Higher layers can import lower layers; shared code must not depend on product entities. Keep transport DTOs separate from UI models.
|
||||
Use FSD boundaries: app composes pages, widgets, features, entities, and shared code. Higher layers can import lower layers; shared code must not depend on product entities. Keep transport DTOs separate from UI models.
|
||||
|
||||
Use the generated Orval client as the contract-derived transport surface. Put shared fetch behavior in the existing API client. Do not hand-edit generated files. Keep the API prefix in one layer so it is not duplicated.
|
||||
|
||||
Model server data in the selected query library and form drafts in form state. Avoid adding a second store for data already owned by the server cache. Show loading, empty, error, retry, and forbidden states as product flows are implemented.
|
||||
|
||||
MSW fixtures are test inputs. They do not prove that a backend workflow exists. The current interface is a scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, shared UI tokens, and primitives for loading, empty, error, forbidden, and saving states. The sign-in, registration, email confirmation, support, and all cabinet screens are placeholders; business screens are later tasks, so do not document candidate or employer workflows as implemented. /status is a technical API liveness page, not a product readiness indicator.
|
||||
MSW fixtures are test inputs, not evidence of a backend workflow. Check current route and feature implementations before describing a screen as available. Protected cabinet routes restore the server session through SessionGate. /status checks API liveness, not product readiness.
|
||||
|
||||
Vitest runs in the Node environment without a DOM. Component and route tests check rendered markup and query behavior; clicks, keyboard focus, and layout are verified manually in a browser until the planned Playwright suite exists.
|
||||
Vitest runs in the Node environment without a DOM. Component and route tests check rendered markup and query behavior. Use the existing Playwright suite through make -C deploy test-e2e for browser interactions against an isolated local stack; inspect its selected scenarios and skips before claiming coverage.
|
||||
|
||||
All source comments are in English. User-facing interface copy can be localized.
|
||||
@@ -1,12 +1,12 @@
|
||||
# Infrastructure standard
|
||||
|
||||
The local scaffold uses three independent Compose projects: core application, ML, and monitoring. Starting the core project does not start monitoring or ML.
|
||||
Core application, ML, and monitoring use separate Compose projects. Start core first: ML and monitoring join its network. Starting core does not start either project. The code runner and LXD lab provisioner have separate host setup under deploy/labs/. The runner development container uses deploy/docker/docker-compose.runner.dev.yml.
|
||||
|
||||
Upstream container images use the requested moving `latest` or `alpine` tags where the image publishes them. These tags can change; read the current Compose and Dockerfile references instead of recording an old component version. Keep Go at exact version 1.26.9 in `go.mod`, toolchain declarations, and the backend build image. Application dependency lockfiles remain checked in and should not be removed when image tags float.
|
||||
|
||||
The core frontend container serves static assets with Nginx and proxies /api to Go. The default host binding is loopback at port 8080. This scaffold does not terminate production TLS. Grafana is also bound to loopback at port 3000.
|
||||
|
||||
The ML Compose file binds to 127.0.0.1:8000 by default. A remote ML host needs an explicit private bind address, restricted firewall rules, and a deliberate scrape target. Leave ML_METRICS_TARGET empty when Prometheus must not scrape a remote ML host.
|
||||
The ML Compose file binds to 127.0.0.1:8000 by default and requires a shared ML_SERVICE_TOKEN. A remote ML host needs an explicit private bind address and restricted firewall rules. Leave ML_METRICS_TARGET empty when no ML scrape is configured; a nonempty target also needs bearer authentication in Prometheus because ML protects /metrics.
|
||||
|
||||
Start the core project before monitoring because monitoring joins its Docker network. The monitoring Compose project collects only the explicitly configured core services. Do not expose PostgreSQL, Redis, SeaweedFS, Kafka, backend metrics, Prometheus, Loki, exporters, or the Docker socket proxy publicly.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Use make -C ml generate to bundle the contract and generate models. The root gen
|
||||
|
||||
Readiness must describe whether the required model or inference runtime is available. Return not-ready while it is unavailable. Do not invent a successful result or label a fixture as a model response.
|
||||
|
||||
When inference is added, validate structured output, bound input and output size, apply timeouts, and preserve model and schema versions. Avoid logging resume text, contact details, credentials, or full prompts. Treat document contents and model output as untrusted data.
|
||||
Validate inference output, bound input and output size, apply timeouts, and preserve model and schema versions. Avoid logging resume text, contact details, credentials, or full prompts. Treat document contents and model output as untrusted data.
|
||||
|
||||
Use uv with the checked-in lockfile. Keep ordinary lint, type checks, and tests independent of external model downloads and GPU access. Model quality evaluation is a separate, reproducible task with documented data and limits.
|
||||
|
||||
|
||||
@@ -10,6 +10,6 @@ Treat resumes, API payloads, model output, repository documents, dependencies, t
|
||||
|
||||
Keep health routes minimal. Keep /metrics and infrastructure administration surfaces on internal interfaces. Review bind addresses and network access whenever a Compose or Nginx change affects reachability.
|
||||
|
||||
Architecture notes about privacy controls are requirements for future product behavior. They are not proof of legal compliance, completed authorization, or a security audit.
|
||||
Verify privacy controls in the current code and access tests. Architecture notes alone are not proof of enforcement, legal compliance, or a security audit.
|
||||
|
||||
Run configured security checks through `security/Makefile`. Trivy HIGH/CRITICAL findings, including unfixed vulnerabilities, block validation; Gitleaks, govulncheck, configured Semgrep findings, and scanner errors also fail their checks. Scan both repository inputs and built images, and require complete Git history for secret scanning. Keep reports local and redact secret values. Any exception must be specific, reviewed, and record a reason, owner, and expiry; review expiry explicitly where the tool does not enforce it. Do not add broad exclusions to make a scan pass. These checks complement gosec and do not replace authorization tests or a security audit.
|
||||
@@ -6,7 +6,7 @@ Use unit tests for domain and application behavior, component tests for frontend
|
||||
|
||||
Contract changes need bundle and lint checks, regeneration of affected consumers, and generated drift checks. Infrastructure changes need rendered Compose configuration and the validator for each changed monitoring or deployment file.
|
||||
|
||||
The technical deployment smoke checks service routes and infrastructure readiness. It does not validate a candidate or employer workflow. The deploy test-e2e target runs the Playwright suite against an isolated throwaway stack; it currently covers only the SPA, API health, and error routes, so a pass does not validate a business workflow.
|
||||
The technical deployment smoke checks service routes and infrastructure readiness. The deploy test-e2e target runs Playwright against an isolated throwaway stack, including candidate and employer scenarios in frontend/e2e/. Report which scenarios ran, failed, or were skipped; a smoke pass alone does not validate a business workflow.
|
||||
|
||||
Do not report ranking accuracy, assessment validity, production latency, load capacity, privacy correctness, or model quality without the corresponding measured test and its dataset, environment, and limits. Planned targets and synthetic examples are not results.
|
||||
|
||||
|
||||
@@ -10,4 +10,6 @@ Use Make targets instead of maintaining duplicate shell command lists. Generate
|
||||
|
||||
Keep planning identifiers and progress reports inside the local PRD directory. Describe behavior and rationale in code comments, documentation, and commit messages without referring to numbered backlog items. Never stage or commit PRD. Use the configured human Git identity and do not add assistant authorship or coauthor trailers.
|
||||
|
||||
Keep READMEs short: purpose, essential commands, and links to the relevant guide. Document current behavior from code and configuration. Update existing sections instead of appending implementation diaries, old test results, or copies of API schemas. Preserve required setup steps and operational limits in both languages.
|
||||
|
||||
Keep ignore rules in the component that owns the artifacts. Each service has its own .gitignore; the root .gitignore covers only files at the repository root. Do not collect service caches and build outputs in one root ignore file.
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
+35
-35
@@ -2,61 +2,61 @@
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
Lincodex is a platform that helps employers find IT specialists by confirmed skills. The current MVP consists of a Go backend, a React interface, PostgreSQL, Redis, SeaweedFS, and Kafka in Docker Compose, a separate ML service without a model, and optional monitoring.
|
||||
Lincodex helps employers find IT specialists by verified skills. Candidates complete a profile, take assessments, and control their card's visibility. Employers describe hiring needs, search for candidates, and send invitations; contact details become available after the candidate consents.
|
||||
|
||||
Implemented: registration with email confirmation and sign-in; the candidate cabinet with consents, a manual profile without a resume or FSP ID, the questionnaire, an express run without a grade, the full test, results, skill evidence, and privacy settings; the employer cabinet with organizations, the company profile, needs, and deterministic candidate search without ML; support cases and the notification inbox. Invitations work from a draft to the candidate's answer: the organization sends an invitation from a search result, the candidate accepts it with the consent C4 or declines, and after the acceptance the organization reads the disclosed contacts. Planned: withdrawing invitations, salary raise, password reset, resumes and PDF, FSP integration, ML inference, and calibrated grades. The [MVP quick start](docs/en/DEPLOY.md#running-the-mvp-quick-start) lists the details and limits.
|
||||
The core stack is Go + chi, React + TypeScript, PostgreSQL, Redis, SeaweedFS, and Kafka. ML, code execution, lab environments, and monitoring run separately. Demonstration categories do not establish assessment validity for real candidates.
|
||||
|
||||
## Start locally
|
||||
## Quick start
|
||||
|
||||
You need Docker with the Compose plugin, GNU make, python3, and openssl; no GPU, external inference key, or FSP access is needed. Copy .env.example to .env, replace every `replace-this-...` value, set `IDENTITY_KEY_SECRET` to the output of `openssl rand -base64 48`, then run:
|
||||
Install Docker with the Compose plugin, GNU make, Python 3, and openssl.
|
||||
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
1. Copy `.env.example` to `.env` and replace the `replace-this-...` values.
|
||||
2. Generate `IDENTITY_KEY_SECRET` with `openssl rand -base64 48`.
|
||||
3. Build and start the core stack:
|
||||
|
||||
Open http://localhost:8080 (use `localhost`: the address must match `APP_PUBLIC_URL`). The port is bound to loopback and does not provide production TLS. The default `EMAIL_PROVIDER=disabled` sends no mail, so a new account cannot be confirmed. For real mail set `EMAIL_PROVIDER=resend` and a Resend key in the server environment. `make -C deploy smoke` runs a separate throwaway technical check.
|
||||
```sh
|
||||
make -C deploy config
|
||||
make -C deploy build
|
||||
make -C deploy up
|
||||
```
|
||||
|
||||
To start the separate monitoring stack after the core services:
|
||||
Open http://localhost:8080. The address must match `APP_PUBLIC_URL`. The `config` check uses the example environment; it does not validate your `.env` values.
|
||||
|
||||
make -C deploy monitoring-up
|
||||
Mail defaults to `EMAIL_PROVIDER=disabled`, so new accounts cannot verify their email. Configure Resend for real delivery using the [deployment guide](docs/en/DEPLOYMENT.md). `make -C deploy down` stops the services and keeps their data.
|
||||
|
||||
Grafana is available at http://127.0.0.1:3000 on the local machine. See the deployment guide before exposing any service to another host.
|
||||
## Demonstration
|
||||
|
||||
## Demo stand
|
||||
A separate stand provides synthetic data and prepared accounts:
|
||||
|
||||
To show the product, use the isolated stand with synthetic data and prepared candidate and employer accounts that need no mail:
|
||||
```sh
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
```
|
||||
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
Open http://localhost:8090 and follow `/demo`. The command prints account names; `DEMO_ACCOUNT_PASSWORD` in the demo settings supplies their password. These accounts do not require email delivery. See [DEPLOYMENT.md](docs/en/DEPLOYMENT.md) for details and cleanup.
|
||||
|
||||
The stand opens at http://localhost:8090. The jury guide, an eight-minute route across two roles, is at http://localhost:8090/demo. The command prints the logins; the password is `DEMO_ACCOUNT_PASSWORD` from `deploy/demo/demo.env.example` (a published demo credential, not a secret). The [MVP quick start](docs/en/DEPLOY.md#running-the-mvp-quick-start) describes the demonstration route, the stand parameters, the mail, FSP, and ML modes, and how to stop the stands.
|
||||
Start monitoring separately with `make -C deploy monitoring-up`. Grafana defaults to http://127.0.0.1:3000.
|
||||
|
||||
## Development
|
||||
|
||||
The root Makefile provides install, generate, fmt, fmt-check, lint, test, check, verify, and docs-check targets. Run make help for the current command list. The development and testing guides describe the service-specific commands and what the current checks cover.
|
||||
|
||||
## Documentation
|
||||
|
||||
Short directory guides:
|
||||
## Directories
|
||||
|
||||
| Directory | Purpose |
|
||||
| --- | --- |
|
||||
| [api/](api/README.en.md) | Shared OpenAPI contracts |
|
||||
| [backend/](backend/README.en.md) | Main Go service |
|
||||
| [backend/](backend/README.en.md) | Core Go service |
|
||||
| [frontend/](frontend/README.en.md) | React and TypeScript interface |
|
||||
| [ml/](ml/README.en.md) | Separate Python service for ML |
|
||||
| [runner/](runner/README.en.md) | Go code runner with nsjail |
|
||||
| [deploy/](deploy/README.en.md) | Docker Compose, Nginx, and service startup |
|
||||
| [ml/](ml/README.en.md) | ML API and models |
|
||||
| [runner/](runner/README.en.md) | Isolated code execution |
|
||||
| [labd/](labd/README.en.md) | Lab environment provisioning |
|
||||
| [deploy/](deploy/README.en.md) | Compose, Nginx, and deployment |
|
||||
| [observability/](observability/README.en.md) | Metrics, logs, and dashboards |
|
||||
| [security/](security/README.en.md) | Security scanners and rules |
|
||||
| [docs/](docs/README.en.md) | Detailed Russian and English guides |
|
||||
| [requirements/](requirements/README.en.md) | Original specification and brand assets |
|
||||
| [scripts/](scripts/README.en.md) | Shared code generation and validation scripts |
|
||||
| [.github/](.github/workflows/) | GitHub Actions workflows |
|
||||
| [.agents/](.agents/README.en.md) | Agent rules |
|
||||
| [security/](security/README.en.md) | Security checks |
|
||||
| [docs/](docs/README.en.md) | Russian and English guides |
|
||||
| [requirements/](requirements/README.en.md) | Specification and brand assets |
|
||||
| [scripts/](scripts/README.en.md) | Shared scripts and checks |
|
||||
| [.github/](.github/workflows/) | GitHub Actions |
|
||||
| [.agents/](.agents/README.en.md) | Repository working rules |
|
||||
|
||||
- Source materials: [specification](requirements/specification.pdf), [brandbook](requirements/brandbook/).
|
||||
- Russian: [architecture](docs/ru/ARCHITECTURE.md), [development](docs/ru/DEVELOPMENT.md), [deployment](docs/ru/DEPLOY.md), [testing](docs/ru/TESTING.md), [security](docs/ru/SECURITY.md), [MVP package](docs/ru/MVP.md)
|
||||
- English: [architecture](docs/en/ARCHITECTURE.md), [development](docs/en/DEVELOPMENT.md), [deployment](docs/en/DEPLOY.md), [testing](docs/en/TESTING.md), [security](docs/en/SECURITY.md), [MVP package](docs/en/MVP.md)
|
||||
Development commands: `make help`. Start with [DEVELOPMENT.md](docs/en/DEVELOPMENT.md); see [TESTING.md](docs/en/TESTING.md) for checks and [ARCHITECTURE.md](docs/en/ARCHITECTURE.md) for the design.
|
||||
|
||||
## License
|
||||
|
||||
No project-wide license has been assigned in this repository. Check the license terms of each dependency and container image before redistribution.
|
||||
Project code is distributed under [GPL-3.0-only](LICENSE). Dependencies and source materials may have their own terms of use.
|
||||
@@ -2,67 +2,61 @@
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
Lincodex - платформа, на которой работодатели находят IT-специалистов по подтвержденным навыкам. Текущий MVP состоит из Go backend, React-интерфейса, PostgreSQL, Redis, SeaweedFS и Kafka в Docker Compose, отдельного ML-сервиса без модели и отдельно запускаемого мониторинга.
|
||||
Lincodex помогает работодателям находить IT-специалистов по подтвержденным навыкам. Кандидат заполняет профиль, проходит оценку и управляет видимостью карточки. Работодатель описывает потребность, ищет кандидатов и отправляет приглашения; контакты открываются после согласия кандидата.
|
||||
|
||||
Реализовано: регистрация с подтверждением email и вход; кабинет кандидата с согласиями, ручным профилем без резюме и ФСП ID, анкетой, экспресс-запуском без грейда, полным тестом, результатами, доказательствами навыков и настройками приватности; кабинет работодателя с организациями, профилем компании, потребностями и детерминированным поиском кандидатов без ML; обращения в поддержку и inbox уведомлений. Приглашения работают от черновика до ответа: организация отправляет приглашение из результата поиска, кандидат принимает его с согласием C4 или отказывается, после принятия организация читает переданные контакты. Запланированы отзыв приглашения, повышение зарплаты, сброс пароля, резюме и PDF, интеграция с ФСП, ML inference и откалиброванные грейды. Полный перечень и границы описаны в [быстром старте MVP](docs/ru/DEPLOY.md#запуск-mvp-быстрый-старт).
|
||||
Основной стек: Go + chi, React + TypeScript, PostgreSQL, Redis, SeaweedFS и Kafka. ML, исполнитель кода, лабораторные окружения и мониторинг подключаются отдельно. Демонстрационные категории не означают, что оценка уже откалибрована на реальных кандидатах.
|
||||
|
||||
## Локальный запуск
|
||||
## Быстрый старт
|
||||
|
||||
Нужны Docker с Compose plugin, GNU make, python3 и openssl; GPU, ключи внешнего inference и доступ к ФСП не нужны. Скопируйте `.env.example` в `.env`, замените все значения `replace-this-...`, впишите в `IDENTITY_KEY_SECRET` вывод `openssl rand -base64 48` и выполните:
|
||||
Нужны Docker с Compose plugin, GNU make, Python 3 и openssl.
|
||||
|
||||
1. Скопируйте `.env.example` в `.env` и замените значения `replace-this-...`.
|
||||
2. Для `IDENTITY_KEY_SECRET` создайте секрет: `openssl rand -base64 48`.
|
||||
3. Соберите и запустите основной стек:
|
||||
|
||||
```sh
|
||||
make -C deploy config
|
||||
make -C deploy build
|
||||
make -C deploy up
|
||||
```
|
||||
|
||||
Откройте http://localhost:8080 (именно `localhost`: адрес должен совпадать с `APP_PUBLIC_URL`). Порт привязан к loopback-интерфейсу; TLS для продакшена не настроен. По умолчанию `EMAIL_PROVIDER=disabled`: письма не отправляются, поэтому новый аккаунт нельзя подтвердить. Для настоящих писем задайте `EMAIL_PROVIDER=resend` и ключ Resend в окружении сервера. `make -C deploy smoke` запускает отдельную одноразовую техническую проверку.
|
||||
Откройте http://localhost:8080. Адрес должен совпадать с `APP_PUBLIC_URL`. Проверка `config` использует пример окружения; она не подтверждает правильность вашего `.env`.
|
||||
|
||||
Мониторинг запускается отдельно, после основных сервисов:
|
||||
По умолчанию `EMAIL_PROVIDER=disabled`: новый аккаунт нельзя подтвердить без почты. Для реальной отправки настройте Resend по [руководству развертывания](docs/ru/DEPLOYMENT.md). Команда `make -C deploy down` останавливает сервисы, сохраняя данные.
|
||||
|
||||
```sh
|
||||
make -C deploy monitoring-up
|
||||
```
|
||||
## Демонстрация
|
||||
|
||||
Grafana доступна на локальной машине по адресу http://127.0.0.1:3000. Перед открытием доступа с других хостов прочитайте руководство по развертыванию.
|
||||
|
||||
## Демонстрационный стенд
|
||||
|
||||
Для показа продукта используйте изолированный стенд с синтетическими данными и подготовленными аккаунтами кандидатов и работодателей, которым почта не нужна:
|
||||
Отдельный стенд содержит синтетические данные и готовые аккаунты:
|
||||
|
||||
```sh
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
```
|
||||
|
||||
Стенд открывается на http://localhost:8090. Гид для жюри с маршрутом на восемь минут двумя ролями открыт на http://localhost:8090/demo. Логины печатает сама команда, пароль - `DEMO_ACCOUNT_PASSWORD` из `deploy/demo/demo.env.example` (опубликованные демонстрационные учетные данные, а не секрет). Маршрут демонстрации, параметры стендов, режимы почты, ФСП и ML и остановка описаны в [быстром старте MVP](docs/ru/DEPLOY.md#запуск-mvp-быстрый-старт).
|
||||
Адрес стенда: http://localhost:8090, маршрут демонстрации: `/demo`. Команда выводит логины; пароль задает `DEMO_ACCOUNT_PASSWORD` в настройках демонстрации. Эти аккаунты не требуют отправки писем. Подробности и очистка стенда описаны в [DEPLOYMENT.md](docs/ru/DEPLOYMENT.md).
|
||||
|
||||
## Разработка
|
||||
Мониторинг запускается отдельно командой `make -C deploy monitoring-up`. Grafana по умолчанию доступна на http://127.0.0.1:3000.
|
||||
|
||||
Корневой Makefile содержит цели `install`, `generate`, `fmt`, `fmt-check`, `lint`, `test`, `check`, `verify` и `docs-check`. Актуальный список команд доступен через `make help`. Команды отдельных сервисов и границы текущих проверок описаны в руководствах по разработке и тестированию.
|
||||
|
||||
## Документация
|
||||
|
||||
Краткие описания каталогов:
|
||||
## Каталоги
|
||||
|
||||
| Каталог | Назначение |
|
||||
| --- | --- |
|
||||
| [api/](api/README.md) | Общие OpenAPI-контракты |
|
||||
| [backend/](backend/README.md) | Основной сервис на Go |
|
||||
| [frontend/](frontend/README.md) | Интерфейс на React и TypeScript |
|
||||
| [ml/](ml/README.md) | Отдельный Python-сервис для ML |
|
||||
| [runner/](runner/README.md) | Исполнитель кода на Go с nsjail |
|
||||
| [deploy/](deploy/README.md) | Docker Compose, Nginx и запуск сервисов |
|
||||
| [backend/](backend/README.md) | Основной Go-сервис |
|
||||
| [frontend/](frontend/README.md) | Интерфейс React и TypeScript |
|
||||
| [ml/](ml/README.md) | ML API и модели |
|
||||
| [runner/](runner/README.md) | Изолированное выполнение кода |
|
||||
| [labd/](labd/README.md) | Подготовка лабораторных окружений |
|
||||
| [deploy/](deploy/README.md) | Compose, Nginx и развертывание |
|
||||
| [observability/](observability/README.md) | Метрики, логи и дашборды |
|
||||
| [security/](security/README.md) | Сканеры и правила безопасности |
|
||||
| [docs/](docs/README.md) | Подробные руководства на русском и английском |
|
||||
| [requirements/](requirements/README.md) | Исходное ТЗ и брендбук |
|
||||
| [scripts/](scripts/README.md) | Общие скрипты кодогенерации и проверок |
|
||||
| [.github/](.github/workflows/) | Workflow GitHub Actions |
|
||||
| [.agents/](.agents/README.md) | Правила работы агентов |
|
||||
| [security/](security/README.md) | Проверки безопасности |
|
||||
| [docs/](docs/README.md) | Руководства на русском и английском |
|
||||
| [requirements/](requirements/README.md) | ТЗ и брендбук |
|
||||
| [scripts/](scripts/README.md) | Общие скрипты и проверки |
|
||||
| [.github/](.github/workflows/) | GitHub Actions |
|
||||
| [.agents/](.agents/README.md) | Правила работы с репозиторием |
|
||||
|
||||
- Исходные материалы: [ТЗ](requirements/specification.pdf), [брендбук](requirements/brandbook/).
|
||||
- На русском: [архитектура](docs/ru/ARCHITECTURE.md), [разработка](docs/ru/DEVELOPMENT.md), [развертывание](docs/ru/DEPLOY.md), [тестирование](docs/ru/TESTING.md), [безопасность](docs/ru/SECURITY.md), [пакет сдачи MVP](docs/ru/MVP.md).
|
||||
- На английском: [архитектура](docs/en/ARCHITECTURE.md), [разработка](docs/en/DEVELOPMENT.md), [развертывание](docs/en/DEPLOY.md), [тестирование](docs/en/TESTING.md), [безопасность](docs/en/SECURITY.md), [пакет сдачи MVP](docs/en/MVP.md).
|
||||
Команды разработки: `make help`. Начните с [DEVELOPMENT.md](docs/ru/DEVELOPMENT.md); проверки описаны в [TESTING.md](docs/ru/TESTING.md), архитектура - в [ARCHITECTURE.md](docs/ru/ARCHITECTURE.md).
|
||||
|
||||
## Лицензия
|
||||
|
||||
Общая лицензия проекта пока не определена. Перед распространением проверьте условия лицензий каждой зависимости и образа контейнера.
|
||||
Код проекта распространяется на условиях [GPL-3.0-only](LICENSE). Зависимости и исходные материалы могут иметь собственные условия использования.
|
||||
+44
-814
@@ -2,827 +2,57 @@
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
Shared OpenAPI contracts for Go, the frontend, and ML. Contract changes come first; consumers then generate their types, server code, and clients from them.
|
||||
OpenAPI 3.2.0 is the shared source for HTTP contracts. Change the specification first, then generate server adapters, clients, and models.
|
||||
|
||||
- `core/` defines the main backend's public API.
|
||||
- `ml/` defines the ML service's internal HTTP API.
|
||||
- `runner/` defines the internal HTTP API of the own code runner.
|
||||
- `testdata/` contains a specification for checking tool compatibility with OpenAPI 3.2.0.
|
||||
## Structure
|
||||
|
||||
Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`; the code runner server code is generated from `runner/codegen/`.
|
||||
| Directory | API |
|
||||
| --- | --- |
|
||||
| [core/](core/openapi.yml) | Public Go API under `/api/v1` |
|
||||
| [ml/](ml/openapi.yml) | Internal ML API |
|
||||
| [runner/](runner/openapi.yml) | Code execution |
|
||||
| [labd/](labd/openapi.yml) | Lab environment provisioning |
|
||||
| [testdata/](testdata/openapi-3.2.0.yml) | Generator compatibility fixture |
|
||||
|
||||
From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code.
|
||||
Each contract's `openapi.yml` references `routes/` and `components/`. [merge-schemas.py](../scripts/merge-schemas.py) merges schemas grouped by subject, then Redocly builds `openapi.bundle.yml`. Do not edit derived files by hand.
|
||||
|
||||
## Generation
|
||||
|
||||
Run these commands from the repository root:
|
||||
|
||||
```sh
|
||||
make -C api install
|
||||
make -C api check
|
||||
make generate
|
||||
make check-generated
|
||||
```
|
||||
|
||||
`check` builds and validates contracts. `generate` updates every consumer. `check-generated` detects differences from committed output; it does not run generation itself.
|
||||
|
||||
| Consumer | Generator and configuration |
|
||||
| --- | --- |
|
||||
| Go backend | ogen, [backend/codegen/](../backend/codegen/) |
|
||||
| Go runner and labd | ogen, each service's `codegen/` directory |
|
||||
| React | Orval: client, query hooks, Zod schemas, and MSW; [frontend/codegen/](../frontend/codegen/) |
|
||||
| Python ML | datamodel-code-generator: Pydantic; [ml/codegen/](../ml/codegen/) |
|
||||
|
||||
`make -C api check-toolchain` checks the OpenAPI 3.2 features in a dedicated fixture. It verifies the current toolchain, not every feature of the standard.
|
||||
|
||||
Compare the public contract with an existing Git ref using `make -C api check-compat API_BASE_REF=<ref>`.
|
||||
|
||||
## Contract conventions
|
||||
|
||||
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation, the assessment commands, `CreateOrganization`, `CreateOrganizationNeed`, `CreateMySupportCase`, and the invitation commands require Idempotency-Key, but no operation stores keys yet.
|
||||
- Errors: RFC 9457, `application/problem+json`, stable `code`, and safe messages. The `Problem` schema defines the response fields.
|
||||
- Sessions: an HttpOnly cookie; mutating session requests also send `X-CSRF-Token`. The origin must match the application configuration.
|
||||
- Send `Idempotency-Key` where the operation requires it. Reuse the key when retrying the same action; use a new key for different content.
|
||||
- Concurrent updates use `If-Match` or `expected_version` as specified by the operation. On conflict, reload server state and preserve the user's draft.
|
||||
- Lists use bounded cursor pagination. Identifiers are UUIDs and timestamps are UTC date-times. An absent field may differ from `null`.
|
||||
- Read exact codes, limits, required headers, and examples from each operation and its shared components.
|
||||
|
||||
### Errors
|
||||
## Boundaries
|
||||
|
||||
Every error is an RFC 9457 problem with the `application/problem+json` media type and the `Problem` schema. Required fields are `type` (`urn:lincodex:problem:<code>`), `title`, `status`, and `code`; optional ones are `detail`, `instance`, `trace_id` (equal to the `X-Request-ID` response header), and `errors`. Clients branch on `code`. Titles and details are fixed per code and never contain internal error text, stack traces, credentials, contact data, or submitted values.
|
||||
An operation in the specification does not prove its handler is complete. Check `backend/internal/adapter/primary/http/v1/` and its tests. An unimplemented operation can return `501 not_implemented`.
|
||||
|
||||
| Code | Status | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `validation_failed` | 400 | Parameters or body do not match the contract, or the body violates a domain rule; `errors` lists the fields |
|
||||
| `verification_token_invalid` | 400 | The email verification token is unknown, already used, or replaced |
|
||||
| `verification_token_expired` | 400 | The email verification token is past its lifetime |
|
||||
| `unauthenticated` | 401 | No valid session |
|
||||
| `invalid_credentials` | 401 | Login failed; an unknown email and a wrong password are not distinguished |
|
||||
| `forbidden` | 403 | The caller may not perform the operation |
|
||||
| `email_not_verified` | 403 | Correct credentials, but the email is not verified |
|
||||
| `csrf_check_failed` | 403 | Missing or wrong `X-CSRF-Token`, or a disallowed `Origin` |
|
||||
| `not_found` | 404 | Unknown route, or an object that does not exist or is not visible |
|
||||
| `method_not_allowed` | 405 | Unsupported method; see `Allow` |
|
||||
| `idempotency_in_progress` | 409 | A request with the same Idempotency-Key is still running |
|
||||
| `state_conflict` | 409 | The operation is not allowed in the current state of the resource |
|
||||
| `version_conflict` | 412 | If-Match, or a body `expected_version`, does not match the current version |
|
||||
| `payload_too_large` | 413 | The body exceeds the operation limit |
|
||||
| `unsupported_media_type` | 415 | The request Content-Type is not accepted |
|
||||
| `idempotency_key_reused` | 422 | The Idempotency-Key was used with a different request |
|
||||
| `precondition_required` | 428 | The operation requires If-Match |
|
||||
| `rate_limited` | 429 | Too many requests; see `Retry-After` |
|
||||
| `internal` | 500 | Unexpected server error |
|
||||
| `not_implemented` | 501 | The operation is in the contract but not implemented |
|
||||
Internal ML, runner, and labd APIs are not browser entry points. The public health route is `/api/v1/healthz`; service guides cover operational `/healthz`, `/readyz`, and metrics.
|
||||
|
||||
Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as `salary_from <= salary_to`, also answer 400 `validation_failed` with body pointers to the fields involved. Each `errors` item has `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` in the body, an empty string for the whole body, `/limit` for a parameter), `code` (`required` or `invalid`; clients tolerate new values), and a fixed `message`. Body pointers follow the rules in Body pointers below. A body cut by an `http.MaxBytesReader` limit answers 413 `payload_too_large`.
|
||||
|
||||
`state_conflict` covers business state conflicts, such as accepting an invitation that was already withdrawn. `idempotency_in_progress` is reserved for concurrent retries; the reusable responses are `StateConflict` and `IdempotencyInProgress`.
|
||||
|
||||
Every operation declares `default: $ref: ../components/responses.yml#/Problem`; ogen then generates a single error type. An operation adds a specific response (for example `PreconditionFailed`) when clients need it in the generated types. In the Go API, unknown paths under `/api`, including paths outside `/api/v1`, answer 404 `not_found`, and a panic in an operation answers 500 `internal`; only the panic type and stack are logged.
|
||||
|
||||
Both verification token codes use 400 because the token is request content, not the target resource: 404 and 410 describe the URI, 409 a resource state, and 422 stays reserved for Idempotency-Key reuse. A malformed token fails schema validation and answers 400 `validation_failed` with the pointer `/token`. `invalid_credentials` and `unauthenticated` share 401 but mean a failed login and a missing session respectively. `email_not_verified` is returned only after the password matched, so it tells the verification state only to someone who already proved the password.
|
||||
|
||||
#### Body pointers
|
||||
|
||||
The generated decoder records no path of its own. It wraps the error of each object field as `decode field "<name>"` with go-faster/errors, and `problem.Responder` rebuilds the pointer from those wrappers, reading each link through the typed `errors.Formatter` instead of the joined error text. The rules:
|
||||
|
||||
- A missing required field answers `required` with its own pointer at any depth, for example `/terms/communication_method` or `/terms/salary/tax_basis`.
|
||||
- A value that fails during decoding, such as a wrong JSON type, a malformed UUID, or an ambiguous `oneOf` value, answers `invalid` with the pointer of that value, for example `/grade` for a bare grade or `/object/id`.
|
||||
- A value that decodes but breaks a schema rule, such as a length, a pattern, a multiple of 1000, or an enum, answers `invalid` with its full pointer, including array indices, for example `/required_skills/2/status`; this check runs after decoding.
|
||||
- An unknown property answers `invalid` with the pointer of the object that contains it, for example `/terms/salary` for a `candidate_minimum` inside the range; the property name is not echoed.
|
||||
- A failure inside an array element during decoding answers `invalid` with the pointer of the array, for example `/required_skills`, because jx reports no element index.
|
||||
- The whole-body pointer `""` remains only for a malformed JSON document, a missing body, an unknown top-level property, an unknown or missing discriminator of a top-level `oneOf`, and an error chain that the responder does not recognize, which falls back safely to the whole body.
|
||||
|
||||
`responder_test.go` covers a nested object, an array element, a `oneOf` variant field, a top-level field, and an unrecognized chain; the router tests of every contract pin the pointers through the generated server.
|
||||
|
||||
### Retries and Idempotency-Key
|
||||
|
||||
A mutating command declares the `IdempotencyKey` parameter. The client generates a key (a UUID v4 is recommended) and sends it in the `Idempotency-Key` header without quotes: 1-255 characters `A-Z a-z 0-9 . _ : -`. The server scopes the key by caller and operation and fingerprints the request by method, path, and body.
|
||||
|
||||
An anonymous operation defines its key scope and fingerprint in its own description; for `RegisterAccount` see the Identity section below.
|
||||
|
||||
Stored for 24 hours and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 `not_found` or 409 `state_conflict`. A replay does not repeat the side effect.
|
||||
|
||||
Not stored, so a retry with the same key is evaluated again: 400 `validation_failed`, 413, and 415 for the request itself; 401 and 403; 409 `idempotency_in_progress`; 412 `version_conflict` and 428 `precondition_required` (nothing changed; read the resource again and retry); 422 `idempotency_key_reused`; 429; and every 5xx.
|
||||
|
||||
The server checks in this order:
|
||||
|
||||
1. Authentication (401), request validation (400, 413, 415), and authorization (403). Nothing is recorded for the key.
|
||||
2. A stored or running request with the same key and a different fingerprint: 422 `idempotency_key_reused`. This check comes before the in-progress check.
|
||||
3. A running request with the same key and fingerprint: 409 `idempotency_in_progress`; retry later.
|
||||
4. A stored outcome with the same key and fingerprint: the outcome is replayed.
|
||||
5. If-Match (428, 412), then the command itself; a storable outcome is recorded.
|
||||
|
||||
Because the replay check comes before If-Match, a retry of a completed change replays its outcome instead of failing on the version that the change itself advanced. A missing or malformed key returns 400 `validation_failed` with the pointer `/Idempotency-Key`. After 24 hours the key may be accepted as new.
|
||||
|
||||
### Versions: ETag and If-Match
|
||||
|
||||
A response with a versioned resource returns a strong `ETag`, for example `"v7"`. An operation that changes such a resource says in its description that it requires `If-Match` with that value. A missing value returns 428 `precondition_required`; a value that does not equal the current ETag returns 412 `version_conflict` and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and `*` fail validation with 400. The questionnaire carries its version as `expected_version` in the body instead; see Catalog and questionnaire below.
|
||||
|
||||
### Pagination
|
||||
|
||||
Lists use cursor pagination: `limit` from 1 to 100 (20 by default) and an opaque `cursor` of up to 512 characters `A-Z a-z 0-9 _ -`. The response holds the items in a bounded array and `page` (`PageInfo`) with `has_more` and `next_cursor`, which is null on the last page. A malformed cursor returns 400 `validation_failed`.
|
||||
|
||||
### Time and money
|
||||
|
||||
Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with the `Z` suffix (RFC 3339). Servers always emit UTC. ogen generates `Timestamp` as a named Go type over `time.Time`; call `.UTC()` where a value is converted to it. Money is an integer number of whole rubles (`RubAmount`, int64) with an explicit base: `SalaryRange` requires `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`), and `tax_basis` (`net` or `gross`); see Needs below. Invitation terms reuse `SalaryRange` with the same rules.
|
||||
|
||||
### ML service errors
|
||||
|
||||
The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, 501, and 503 (`service_unavailable`, while the model is not ready) to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback.
|
||||
|
||||
### Code runner contract
|
||||
|
||||
`runner/openapi.yml` describes the internal API of the code runner, which only the Go backend calls. ogen generates the Go client from `backend/codegen/ogen-code-runner.yml` into `backend/internal/adapter/secondary/code_runner/api/`; no use case calls it yet.
|
||||
|
||||
- Transport and sign-in. The runner listens on a private interface of its host over HTTPS (TLS 1.3). Every operation except `/healthz` and `/readyz` requires `Authorization: Bearer <token>`; the token is a shared random secret of at least 32 characters from the deployment secret store. A wrong or missing token answers 401 `unauthenticated`. Plain HTTP is allowed only by an explicit switch of the local dev Compose file.
|
||||
- Data. `RunRequest` carries only the language, the source code, the limits, and the test groups; each group has a label, a visibility (`public` or `hidden`), a checker kind, and tests with an input and an expected output. It has no candidate, account, attempt, task, or company field; `scripts/test_runner_contract.py` checks this for every request schema, together with `additionalProperties: false` on every request object.
|
||||
- Idempotency. `PUT /v1/runs/{run_id}` (`SubmitRun`) takes a random UUID from the backend. A new ID with a free slot starts the run and answers 202, the same ID with the same body returns the current state with 200 without running again, and the same ID with a different body answers 422 `idempotency_key_reused`. Bodies are compared by a SHA-256 fingerprint of the decoded request. When every slot is busy or the process is stopping, the answer is 503 `runner_busy` with `Retry-After`; nothing is stored, and the backend keeps the queue.
|
||||
- Result. `GetRun` returns `state` (`running` or `finished`) and, per group, the outcome `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error`, or `infrastructure_failure`, the number of passed tests, the CPU time, and the peak memory. `limit` names the limit that stopped a test (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Only public tests carry a stderr diagnostic; hidden tests never carry program output.
|
||||
- Languages: `python3` and `go`. Go is compiled in a separate phase with its own limits; a compile error gives `compile_error` and no test runs.
|
||||
- A checker is set per group: `exact` (comparison after normalizing CRLF, trailing spaces of lines, and trailing empty lines), `tokens` (token sequences split on ASCII whitespace), `numbers` (like `tokens`, but numbers are equal within `abs_tolerance` or `rel_tolerance`), and `custom` (`program` with the language and source of the task family checker; it runs in nsjail, reads the files input, expected, and actual, and answers with exit status 0 or 1). The server rejects parameters that do not fit the checker kind.
|
||||
- Errors use the api/core `Problem` shape with a runner-specific `ProblemCode` enum: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal`, and `runner_busy`. `scripts/test_runner_contract.py` checks that the shape matches api/core.
|
||||
|
||||
### Identity: sessions, cookie, and CSRF
|
||||
|
||||
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/identity/consent-texts/{purpose}` | `GetConsentText` | public | 200 `ConsentText` | 400 `validation_failed` |
|
||||
| `POST /api/v1/identity/registrations` | `RegisterAccount` | public, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | public | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 |
|
||||
| `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | public | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid`, or `validation_failed`; 403 `csrf_check_failed`; 429 |
|
||||
| `POST /api/v1/identity/email-verifications/code` | `ConfirmEmailByCode` | public | 200 `EmailVerificationResult` | 400 `verification_token_invalid` or `validation_failed`; 403 `csrf_check_failed`; 429 |
|
||||
| `POST /api/v1/identity/sessions` | `Login` | public | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` or `csrf_check_failed`, 429 |
|
||||
| `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | session | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` |
|
||||
| `DELETE /api/v1/identity/sessions/current` | `Logout` | session and CSRF | 204, `Set-Cookie` clears the cookie | 401 `unauthenticated` (also clears the cookie), 403 `csrf_check_failed` |
|
||||
| `GET /api/v1/identity/me` | `GetCurrentAccount` | session | 200 `Account`, `Cache-Control: no-store` | 401 `unauthenticated` |
|
||||
|
||||
Every operation also declares the `default` problem response.
|
||||
|
||||
Registration and verification:
|
||||
|
||||
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login answers the same 401 `invalid_credentials` for an unknown email, a wrong password, or an invalid stored hash; unknown emails and invalid hashes also receive extra Argon2id work. A correct password for an unverified account answers 403 `email_not_verified` and creates no session.
|
||||
- Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists.
|
||||
- Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie; sign-in is a separate endpoint and requires a verified account.
|
||||
- Implementation of registration, resend, and login. A verified address changes nothing and receives no message during registration (the "you already have an account" notice is not implemented). Mail limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours. `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour, range 1 to 10000) limits registration, confirmation, resend, and login per resolved client address. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour, range 1 to 10000) limits login by normalized email whether or not an account exists. `ConfirmEmail` also limits each token to 5 attempts per hour and uses the client limit. A refused request answers 429 `rate_limited` with `Retry-After`. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, the limiter keys, and session CSRF. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend).
|
||||
- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions).
|
||||
- Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check.
|
||||
- `ConfirmEmail` takes both `token` and the `password` selected for that registration; clients that sent only a token must be updated. The password follows `LoginPassword`: NFKC normalization and 1 to 128 code points; the registration blocklist is not applied again. `Origin` must match `APP_PUBLIC_URL`; a missing Origin, the literal value null, or a foreign Origin answers 403 `csrf_check_failed`. Confirmation attempts are limited to 5 per token per hour and also use the shared `IDENTITY_CLIENT_HOURLY_LIMIT`; a refused attempt answers 429 `rate_limited` with `Retry-After`.
|
||||
- `ConfirmEmailByCode` takes `email`, `code` (exactly six digits, `VerificationCode`), and `password`, the password of the registration that issued the code. Every refusal, including an unknown address, a wrong or expired code, a wrong password, and an invalidated token, answers 400 `verification_token_invalid`; a malformed body answers 400 `validation_failed` with the pointer `/code`, `/email`, or `/password`. Five failed checks against one open code invalidate its token, and the link stops working too. The code lives 30 minutes, or until the token ends when that is sooner. The address limit is shared with login (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`), and the client limit is `IDENTITY_CLIENT_HOURLY_LIMIT`. Success answers the same body as `ConfirmEmail` and creates no session. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend).
|
||||
- The verification link is `<frontend origin>/verify-email#token=<token>`. The frontend confirmation screen is still a placeholder. A client page must remove the fragment with `history.replaceState`, wait for an explicit user action, and post both token and registration password; a link scanner that only opens the page does not consume the token.
|
||||
- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error; after confirmation the user can sign in separately. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
|
||||
|
||||
Consent C1 and the account:
|
||||
|
||||
- `GetConsentText(c1)` returns the current C1 text, its `text_version`, and `published_at`. Registration sends that version in `consent_c1`; the server records it with the hash of the same stored text. A version that is no longer current answers 400 `validation_failed` with the pointer `/consent_c1/text_version`, and the client reads the text again. A dedicated code would trigger the same client action, and the field pointer already identifies it, so no new code is added.
|
||||
- Unknown body fields are rejected, so no other consent, including C4, can be part of registration.
|
||||
- Passwords are normalized to NFKC and must have 15-128 Unicode code points, without composition rules. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.
|
||||
- The account has a `scenario` (`candidate` or `employer`) and a saved `onboarding_step` that the server advances; after login the client returns the user to that step. Candidate steps are `candidate_consents`, `candidate_profile`, `candidate_questionnaire`, `candidate_assessment`, and `completed`; the employer has `employer_company` and `completed`. DTOs never contain password hashes, token hashes, or session identifiers.
|
||||
|
||||
Sessions and CSRF:
|
||||
|
||||
- Implemented session operations: Login issues a `__Host-lincodex_session` cookie with `Path=/; Secure; HttpOnly; SameSite=Strict`, no Domain, and Expires/Max-Age at the absolute session deadline. PostgreSQL stores only the SHA-256 hash of the cookie token; the current-session GET returns the account and CSRF token after a reload. Successful login transactionally revokes an active session from the request and creates a new one; only a verified account can sign in. Logout revokes the session and clears the cookie; an expired or revoked cookie is also cleared on 401. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` (range `1m` to `30d`) and `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` (range `1m` to `365d`); idle cannot exceed absolute, and invalid values stop startup. Requests extend only the idle deadline.
|
||||
- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the current session's token from `Session.csrf_token`. The backend derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, compares it in constant time, and does not store it in the database. All instances must share one `IDENTITY_KEY_SECRET` (at least 32 bytes), stable across restarts; changing it invalidates old CSRF values but does not revoke PostgreSQL sessions. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`.
|
||||
- Every unsafe public identity operation requires exactly one `Origin` header matching `APP_PUBLIC_URL`, including `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`. Unsafe operations protected by a session also require the session-bound CSRF token. Origin checks do not use `Host` or forwarded headers. Public identity operations are rate-limited (429 with `Retry-After`).
|
||||
- Responses with a session or account carry `Cache-Control: no-store`.
|
||||
- The root `security` requires `sessionCookie`, so an operation that does not declare `security: []` is protected by default.
|
||||
|
||||
How the generated server (ogen v1.24.0) evaluates the schemes, and how `v1.SessionSecurity` applies the current session boundary, are pinned by `TestGeneratedServerSecurityOrder`:
|
||||
|
||||
- It calls `HandleSessionCookie` before `HandleSessionCsrf` and passes the context returned by a successful call on. An absent value (no cookie, empty `X-CSRF-Token`) does not call the handler, and a handler that returns `ogenerrors.ErrSkipServerSecurity` counts as unsatisfied; both continue with the next scheme, so `HandleSessionCsrf` also runs without a cookie, with the original context.
|
||||
- Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field.
|
||||
- Implemented mapping: `HandleSessionCookie` authenticates every operation whose contract requires `sessionCookie`; missing, unknown, expired, revoked, or unverified sessions leave the requirement unsatisfied and answer 401 `unauthenticated`. For protected unsafe operations, `HandleSessionCsrf` checks the exact Origin and the token for that same session. Without a verified principal the result is 401; with one, a missing or wrong Origin or CSRF token is 403 `csrf_check_failed`. A 401 from `Logout` also clears the cookie, while a 403 leaves a valid session intact.
|
||||
|
||||
### Catalog and questionnaire
|
||||
|
||||
The `catalog` and `candidate` tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The catalog is public and answers 501 `not_implemented` until its handler exists. The questionnaire is protected: a guest answers 401 `unauthenticated`, while a valid session passes the security boundary and reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/specializations` | `GetSpecializationCatalog` | public | 200 `SpecializationCatalog` | none |
|
||||
| `GET /api/v1/me/questionnaire` | `GetMyQuestionnaire` | session | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/questionnaire` | `SaveMyQuestionnaire` | session and CSRF | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` |
|
||||
|
||||
Every operation also declares the `default` problem response.
|
||||
|
||||
Catalog:
|
||||
|
||||
- Five directions and nine specializations: Development (`backend`, `frontend`, `mobile`), Infrastructure (`network_engineer`, `devops_sre`), Data (`data_analyst`, `ds_ml`), Security (`information_security`), Quality (`qa`). The MVP grade scale is `intern`, `junior`, `middle`, `senior`; Lead and Architect come after the MVP. The codes are enums, so adding a value is a contract change. Titles are Russian plain text.
|
||||
- A category is a specialization together with a confirmed grade. Task languages (`python`, `go`) and stack tags are attributes of a chosen specialization and never form a category: Backend with Go is the category `backend`. Algorithms is a shared assessment module, not a specialization.
|
||||
- Each specialization has `test_availability`: `status` (`available` or `in_development`), the `grades` with a published task bank, and the `task_languages` that bank offers. The MVP opens an assessment only for a category with a published bank. The server derives the values from the published banks, so they change without a contract change; the example in the contract is illustrative and says nothing about a deployed bank.
|
||||
- The catalog is public (`security: []`): it is the same for every caller, contains no personal data, is shown before registration, and can be cached.
|
||||
|
||||
Questionnaire:
|
||||
|
||||
- The candidate comes from the session; an employer account answers 403 `forbidden`. A candidate without a saved questionnaire gets 200 with `version: 0`, no specializations, and null `work_context` and `updated_at` rather than 404, so the first save reads the version the same way as later ones.
|
||||
- Each chosen specialization has `self_assessed_grade`, `task_languages`, `stack`, and `experience` in months or null when not stated; `work_context` holds only the acceptable work formats and no personal data. The questionnaire never contains a confirmed grade or a category, and unknown fields such as `confirmed_grade` answer 400. The self-assessed grade is the expected grade that the `candidate_assessment` onboarding step offers first; it influences where the assessment starts but adds no points, and no self-assessed grade or stack tag such as "Senior" assigns a category. A real profile stays invisible to employers until an assessment confirms a category.
|
||||
- The schema allows one or two specializations on save and rejects an unknown specialization, grade, task language, or work format. JSON Schema `uniqueItems` cannot compare array items by one field, so the server rejects a repeated specialization with 400 and the pointer `/specializations/<index>/specialization`. It also rejects a task language that the specialization's published bank does not offer, with the pointer of that language. A specialization whose test is `in_development` can be chosen; no assessment starts for it.
|
||||
- Concurrency uses `expected_version` in the body instead of If-Match, because the generated client cannot read the `ETag` header yet. The first save sends 0. A stale value answers 412 `version_conflict`, the same status and code as a failed If-Match, because the client does the same thing: it reads the questionnaire again. `version_conflict` keeps its 412 status, so `state_conflict` (409) is not used here.
|
||||
- PUT replaces the whole questionnaire and needs no Idempotency-Key. A body equal to the stored state changes nothing, keeps the version, and answers 200 even with an older `expected_version`, so a retry after a lost response does not fail with 412.
|
||||
- Order of checks for a save: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), domain rules (400), version (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server.
|
||||
|
||||
### Candidate profile
|
||||
|
||||
The `candidate` tag includes implemented `GetMyProfile` and `SaveMyProfile` operations for the private manual profile. A verified candidate reads and edits only their own profile; an employer receives 403 and a guest receives 401. PUT requires the session CSRF token and exact Origin. Data, version, overlap confirmations, history, and the step transition commit in one transaction. Without DATABASE_URL, the operations retain their 501 fallback. `confirmed_categories` is read-only: one category per specialization in catalog order, from assessment results, with `basis` (`synthetic_demo` for a demonstration category), `confirmed_at`, and `attempt_id`; no request carries it.
|
||||
|
||||
| Method and path | operationId | Protection | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/profile` | `GetMyProfile` | session | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/profile` | `SaveMyProfile` | session and CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` |
|
||||
| `POST /api/v1/me/profile/repository-checks` | `RequestMyRepositoryChecks` | session and CSRF | 202 `ProfileRepositoryCheckRequest`, `Cache-Control: no-store` | 401, 403 `csrf_check_failed` or `forbidden`, 429 `rate_limited` with Retry-After |
|
||||
|
||||
Each operation also declares the default problem response. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, and `version_conflict`.
|
||||
|
||||
`experience_overlaps` lists intersecting inclusive month ranges and their decision state. A changed save requires explicit `confirmed_parallel_periods` with indices and exact dates for that version; an earlier decision survives only for the same indices and dates. A stored unconfirmed overlap permits an exact no-op, but no other edit without a decision. History is appended only on change. A successful PUT advances only `candidate_profile` to `candidate_questionnaire`; the earlier `candidate_consents` and later steps stay unchanged. Consent-step completion has no separate operation yet.
|
||||
|
||||
What the profile holds:
|
||||
|
||||
- The full name and contacts (`full_name`, `contacts.email`, `contacts.phone`, `contacts.telegram`), the stack (`stack`, `StackTag` tags), roles (`roles`: a catalog specialization and a self-assessed grade), work experience (`experience`: entries with a month-precision period `YYYY-MM`, a specialization, and a description of the tasks rather than a job title), soft skills (`soft_skills`, free text), and terms (`terms`: place, readiness to relocate, and the lowest salary with its currency, period, and tax basis). This is personal data of the candidate; the description of each such schema says so, and the values never reach logs, metrics, URLs, or events.
|
||||
- Contacts are exactly the four kinds that the consent C4 can disclose (`ContactFieldKind`), with the same formats (E.164, the leading `@` of a Telegram name, a single line of up to 200 characters for the name), so a disclosure never converts or drops a stored value. The contact email of the profile is not the login of the account: the server sends no mail to it and does not verify it.
|
||||
- Acceptable work formats are not repeated in the profile: they stay only in the `WorkContext` of the questionnaire.
|
||||
- The profile is private: only its owner reads it, and no organization, invitation, or need schema refers to it (`$ref`). An organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant. The lowest salary is never disclosed to an organization; an invitation shows only a compatibility indicator that the server computes.
|
||||
|
||||
Self-assessment and confirmed category:
|
||||
|
||||
- The grade of a role (`roles[].self_assessed_grade`) is a claim of the candidate, the same one that the questionnaire calls `self_assessed_grade`; it adds nothing and never becomes a confirmed grade. The confirmed category is a separate list, `confirmed_categories` (specialization, grade, time, and the assessment attempt that confirmed it). It is read-only, the server derives it from assessment results, no request carries it, and the profile storage has no column for it. A request with `confirmed_grade`, `category`, or `confirmed_categories` is rejected as an unknown field.
|
||||
|
||||
Source and confirmation:
|
||||
|
||||
- Every value carries `status` and `source`. For a single field `status` is `confirmed`, `extracted`, or `unknown`; for `unknown` the value and the source are null, and the server fills in no default. For a list item `status` is `confirmed` or `extracted`. `source` holds `origin` (`manual`; `extracted_from_resume` and `imported` are planned and no MVP operation produces them), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`.
|
||||
- Every claim of the profile has `trust_level` 0, whatever its source: a schema limit (`minimum` and `maximum` are 0), a CHECK in the database, and a type in the domain. Confirming a suggestion changes its status, not its level; higher levels belong to evidence (an assessment result, a confirmation by a third party), which is stored separately and never written into a claim.
|
||||
- A request carries a decision for each value (`value` and `status`): `confirmed` sets a manual value or confirms a stored suggestion with the same value (the source and the quote are kept), and `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the same value. Any other use of `extracted` answers 400 with the pointer of that status, for example `/stack/1/status`, so a form submitted unchanged confirms nothing by accident, as for needs. The client never sends the source, the trust level, or the confirmation time.
|
||||
|
||||
Version and retries:
|
||||
|
||||
- The version starts at 0 for a candidate without a saved profile; such a candidate gets 200 with every field `unknown` and empty lists, not 404. `PUT` replaces the whole profile and a list replaces the list; a field sent as null becomes unknown and is removed.
|
||||
- Concurrent edits are controlled by `expected_version` in the body, as in the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing, and the client reads the profile again, so an edit from another tab is never lost silently. A body that changes nothing keeps the version and answers 200 even with an older version, so no Idempotency-Key is needed. Every saved change advances the version by one.
|
||||
- Order of checks: session (401), CSRF and Origin (403 `csrf_check_failed`), request validation (400), account scenario (403 `forbidden` for an employer), a version above the current one (412), domain rules that depend on the body alone (400), then the rules that depend on the stored claims, with the version: a decision `extracted` for something that is not a stored suggestion answers 412 on a stale version (another tab may have confirmed the value) and 400 on the current one; an unchanged body is 200; any other change over a stale version is 412. A version above the current one never existed and answers 412 even for an unchanged body. The domain rules that the schema cannot express are: a repeated tag, skill, or role specialization (without regard to letter case for tags and skills), a period that ends before it starts or lies in the future, and a decision `extracted` for something that is not a stored suggestion. The 400 response never repeats a submitted value.
|
||||
|
||||
No file, ML, or FSP:
|
||||
|
||||
- The profile is filled in entirely by hand. No field requires a resume, ML extraction, or an FSP account, and the migration and queries create no mandatory link to a file, ML, or FSP. Resume upload and linking an FSP ID are planned additive features; they will add their own fields and sources without changing these.
|
||||
|
||||
Relation to the questionnaire:
|
||||
|
||||
- The questionnaire (`/me/questionnaire`) names at most two specializations for assessment; the profile is what the candidate presents about themselves. Same-named concepts are not duplicated under different meanings: the self-assessed grade and the stack are the same claim in two places (in the questionnaire for the start of the assessment and per specialization, in the profile for display), saved separately, and the server never copies one into the other; the total months of experience in the questionnaire and the experience entries of the profile are different claims; work formats live only in the questionnaire, while place, relocation, and salary live only in the profile. The schema descriptions of both sides refer to each other.
|
||||
|
||||
Storage (migration 00013): `candidate_profiles` (the profile row: `user_id`, `version`, times) and `candidate_profile_claims` (one row per stored claim: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). A missing row means `unknown`. Each kind of value has a CHECK for the format and bounds of the contract; `trust_level` is always 0; the tables have no file column, no FSP column, and no confirmed grade. Details are in [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-profile).
|
||||
|
||||
Open questions for the product owner and legal:
|
||||
|
||||
- Contact kinds: only the four C4 kinds are allowed. Whether links to GitHub, social networks, or a website are needed (the PRD hides them until an invitation is accepted); that would be a contract change in `ContactFieldKind` too.
|
||||
- The 152-FZ basis: which consent covers storing the profile (C1 at registration or a separate one), whether the name and the contacts need separate consents, the retention periods, and the deletion procedure. Today deleting an account cascades to its profile, and there are no retention rules.
|
||||
- The order of the version and the domain rules: the version is checked before the rules that depend on stored claims (a stale tab gets 412, not 400); the product owner should confirm.
|
||||
- Full replacement: `PUT` drops stored import suggestions that the client did not render and send back with the status `extracted`; whether that is acceptable or the server should keep suggestions that were never shown.
|
||||
- The minimum for the onboarding step `candidate_profile`: the current contract requires no field, so any successful PUT completes that step, including an empty no-op. Requiring fields later needs a separate product decision and contract change.
|
||||
- One source between the questionnaire and the profile: keep the self-assessment and the stack independent, or store one claim and show it in both places.
|
||||
- Soft skills: there is no taxonomy, only free text, up to 10 items of 50 characters; whether a dictionary is needed.
|
||||
- Experience: employer names and descriptions are personal data; how the anonymous card generalizes them (PRD: industry and size) is for the card contract, not this one.
|
||||
- Contact verification (confirming the phone or the email of the profile) is not provided: contacts are claims of level 0.
|
||||
|
||||
`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation`, and `TestProfileAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/profile-contract.test.ts` pins the generated Zod rules, the request types without a confirmed grade, and the absence of profile fields from the organization, invitation, and need schemas.
|
||||
|
||||
|
||||
Projects: the optional `projects` list of the `SaveMyProfile` body (up to 10; an absent list keeps the projects, an empty array removes them) with a title, description, tags, and an address `https://github.com/<owner>/<repo>`; other addresses answer 400 with the pointer `/projects/<n>/repository_url`. The `CandidateProfile` response carries `projects[].repository_check` (`pending`, `verified`, `not_found`, `unavailable`). `RequestMyRepositoryChecks` repeats the checks on `api.github.com` at most once per stand interval. Publishing projects on the card is the separate `projects` value of `CardField` (see [architecture](../docs/en/ARCHITECTURE.md#candidate-projects-and-github-repositories)).
|
||||
### Assessment
|
||||
|
||||
The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | session | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
|
||||
| `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | session | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 |
|
||||
| `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 |
|
||||
| `POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs` | `CreateMyAssessmentPracticeRun` | session and CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 429 `rate_limited`, 503 `service_unavailable` |
|
||||
| `GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}` | `GetMyAssessmentPracticeRun` | session | 200 `PracticeRun`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (another page holds it, or the attempt has no work session) |
|
||||
| `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 |
|
||||
| `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422 |
|
||||
| `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | session | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` |
|
||||
| `GET /api/v1/me/assessment-results` | `ListMyAssessmentResults` | session | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
|
||||
| `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | session | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | session and CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` |
|
||||
|
||||
Every operation also declares the `default` problem response.
|
||||
|
||||
The signal notice (`assessment-signal-notice`) lists the signals collected during a real attempt: browser events (focus loss, copy, paste and cut with a size, fullscreen exit, a screenshot key, and a guess that the developer tools are open; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, change of User-Agent, comparison of answer digests; only one-way keyed digests are stored, never addresses, User-Agents, or session tokens). `GET` returns the notice version the server requires and whether the candidate acknowledged it; `PUT` stores the acknowledgement for the account and that version. The acknowledgement is a record that the candidate was informed, not a consent: it does not change C3, and the signal operation neither reads it nor refuses a batch without it. `PUT` needs no Idempotency-Key, because a repeat keeps the first time and answers 200; another version answers 409 `state_conflict`. The notice also lists the measures the page applies during a real attempt (fullscreen, covering the task, blocks on copying, selecting, and printing the task text, the paste rule, the one-window rule, and the watermark of the task screen and text) and says plainly that a screenshot or a phone photo cannot be prevented and that signals lead only to a manual check; it is text version 4, and an acknowledgement of an earlier version never counts for the current one. The `demo_express` mode collects no signals and needs no acknowledgement.
|
||||
|
||||
Access:
|
||||
|
||||
- The candidate comes only from the session; no operation takes a candidate identifier. An employer account answers 403 `forbidden`. An attempt of another candidate answers 404 `not_found`, the same as an unknown identifier, so attempt identifiers cannot be probed.
|
||||
- No operation offers an employer answers, attempt history, or anti-cheat signals. Employers see the current category on the anonymous card and the permitted skill evidence of that card ([Skill evidence](#skill-evidence)), never a result.
|
||||
|
||||
Modes and versions:
|
||||
|
||||
- `kind` is required on creation: `root`, `corrective`, or `demo_express`. A real attempt uses `demo_basic` or `adaptive`; the server picks the mode from the published bank and the client never sends it. `demo_basic` scores a fixed form of reviewed demo items by their keys against the pass mark of the versioned basic grading policy, computes no ability estimate, and decides in one step: it never offers an additional practice. `adaptive` is the adaptive test of FR04. A candidate may explicitly request `demo_express`, a separate interactive 3 to 5 minute training run with no category, target grade, percentile, real-assessment quota, or qualification evidence.
|
||||
- A corrective real attempt includes `root_attempt_id`. The server allows only a strictly lower target grade not already tried in that chain. Creating the root reserves one slot in the three-root-attempts-per-180-days quota; corrections share that slot and the root's immutable `chain_deadline` (72 hours from the root start under the current policy), while keeping their own item, practice, and session limits. A correction spends no additional root slot, cannot extend the deadline, and does not reset the 30/90-day timers. A root preflight refusal creates no attempt and reserves no slot. An expired or incomplete attempt does not create a free new chain, and an insufficient bank does not grant another root slot. `demo_express` is outside correction chains and real-assessment availability.
|
||||
- Creation fixes `versions`: `policy_version` (the number of the `product` policy version), `bank_version`, and `algorithm_version`. The attempt and its result keep them, so a result is reproduced from the stored answers and these versions, and a later version never rewrites it.
|
||||
- The attempt `version` advances by exactly one with each committed change, including a verdict, an explicit session start, expiry, or automatic finalization. GET operations are projections only: they never change the state, consume session quota, or advance the version. A command or background transition commits due outcomes.
|
||||
|
||||
Attempt lifecycle, with the commands each state accepts:
|
||||
|
||||
| State | Meaning | Accepts |
|
||||
| --- | --- | --- |
|
||||
| `in_progress` | Items are being answered; `current_item` is the item to answer | an answer to `current_item` |
|
||||
| `practice_pending` | The item part is done; the main practice has no finished verdict (not submitted, `pending`, or `failed`) | a practice solution while it is `not_started` or `failed` |
|
||||
| `additional_practice_pending` | Adaptive only: finalize found the probability in the band below confirmation and offered one additional practice in the same attempt | the additional practice solution while it is `not_started` or `failed`; finalize in the same statuses declines the offer |
|
||||
| `ready_to_finalize` | Every required part is done | finalize |
|
||||
| `completed` | A decision was made; the result is available | only the repeat of finalize |
|
||||
| `expired` | The time or session limit passed before the candidate finished; the result confirms no grade | none |
|
||||
| `insufficient_bank` | The bank could not cover the blueprint within the limit; the result confirms no grade | none |
|
||||
|
||||
- Additional practice (PRD FR04): with 0.50 <= P_G < 0.80 in the demo policy, the first finalize of an adaptive attempt completes nothing. It appends a practice of kind `additional` to `practices`, moves the attempt to `additional_practice_pending`, and returns the attempt. The practice continues the same attempt, keeps its time and session limits, and spends no new attempt. The next finalize after its verdict decides; P_G still below 0.80 gives `not_confirmed`. Finalizing without submitting it declines the offer with the same outcome. `practices` is a list with a `kind` rather than one more nullable field, so later practice kinds stay additive.
|
||||
- Finalize therefore always answers with `AssessmentAttempt`, never with a result or a `oneOf` of both. When the state is `completed`, the client reads `GetMyAssessmentResult`. One response type keeps generated clients unambiguous and leaves room for non-terminal decisions without a breaking change.
|
||||
- Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. After an idle timeout the candidate explicitly calls `StartMyAssessmentAttemptSession` with the latest `expected_version`; it starts the next session only if quota and deadline allow. Calling it during an active session is a no-op. Session start does not extend `expires_at` or `chain_deadline`.
|
||||
- At the limits: a practice already `pending` is graded first. A command or background transition then finalizes `ready_to_finalize` as `completed`, declines an unsubmitted additional practice (`completed`, `not_confirmed`), or moves `in_progress` and `practice_pending` to `expired`. GET never commits these transitions. `GetMyAssessmentResult` answers 409 while a due transition has not yet been stored.
|
||||
- Insufficient bank is a distinct state in two places. Before a root attempt starts, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or enough unseen families, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating an attempt or reserving a root slot. A correction with an expired chain deadline or insufficient safe bank is also refused; it does not create a new chain. During an existing attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families.
|
||||
- Confirmed grade. `confirmed_grade` and `confirmed_basis` of each questionnaire specialization are read together from the current category, in one snapshot. `confirmed_basis` is `synthetic_demo` for a demonstration grade and null exactly when no grade is confirmed. An attempt does not set them directly: only a category upgrade changes them.
|
||||
- No new problem code is added, so attempt creation gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry.
|
||||
- Availability shows the limits of each grade before the start: `time_limit_seconds`, `max_sessions`, `max_items`, and `practice_required`, null when unknown.
|
||||
- Root-attempt quota and retry timers are separate. Only root creation reserves one of the three root slots per 180 days; corrections in that chain do not reserve another. `insufficient_bank` or an unavailable sandbox does not create a new attempt or open a free chain. After a failure, including the first test, a strictly lower grade can be tested through the same chain; lower-grade corrections do not reset the 30-day same-grade or 90-day promotion timers.
|
||||
|
||||
Items and answers:
|
||||
|
||||
- An item has an `id` (the instance), `sequence`, a plain-text `prompt`, and `content` (`ItemContent`) in one of the formats `choice`, `number`, `string`, `order`, `find_error`, `configuration`, and `practice`. It never contains an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check, and seed items look like scored ones. `multiple`, `max_selections`, and `max_length` are properties of the format or the task family and never derived from the key. The variant is fixed when first served, so a reload, a retry, or a resumed session returns the same instance.
|
||||
- Watermark. A real attempt (`root` or `corrective`) carries `watermark.code`, a keyed pseudonym of the attempt such as `7K3QD-9XM2T`, which the client shows with the time as a faint tile over the task screen; a `demo_express` attempt omits the field. The `prompt` of a real attempt also carries an invisible mark and interchangeable wordings chosen by the same server secret; they change neither the meaning nor the reference answer, and a client keeps the invisible characters (zero width space, non-joiner, joiner, word joiner) out of the accessibility tree. Neither the code nor the mark names the candidate, and no operation gives either to an employer. See [Watermark of the task text](../docs/en/ARCHITECTURE.md#watermark-of-the-task-text).
|
||||
- One open window. A real attempt allows one open page at a time. The page generates a random identifier when it loads and sends it as `X-Attempt-Client` (16 to 64 characters of `A-Za-z0-9_-`) to `HoldMyAssessmentWorkSession`, which holds the work session for 120 seconds and asks the page to renew every 15 seconds, and to `ReleaseMyAssessmentWorkSession` when it closes. `StartMyAssessmentAttemptSession` and `SubmitMyAssessmentAnswer` take the same header as an optional parameter; while another page holds the session, a request from a different page or from none answers 409 `state_conflict` and changes nothing, and that refusal is not stored under the Idempotency-Key. An attempt that nobody holds, a released hold, and a hold that stopped renewing admit every page. It is a one-page-at-a-time rule, not a security boundary, and it is separate from `sessions` (`used`, `max`, `idle_timeout_seconds`), which count sequential work sessions. The server keeps only keyed digests of the page identifier and of the User-Agent bound to the attempt. No new problem code is added, so the page reads 409 on these operations as "open in another window".
|
||||
- An answer (`AssessmentAnswer`) has the same seven formats and carries only the answer. Unknown fields such as `score`, `duration`, or `seed` answer 400. The server records the times and scores the answer with the key of the item instance; time never enters the grade decision. Responses never say whether an answer was correct.
|
||||
- The practice solution runs asynchronously in the sandbox against three hidden check groups; the client polls the attempt while it is `pending`. The verdict shows only the score 0-3 and the pass state of each group. Every outcome caused by the solution (a compilation or runtime error, a time or memory limit) is `finished` with groups not passed. `failed` (`sandbox_busy` or `sandbox_error`) means only that the infrastructure could not run it; it consumes nothing. This keeps `failed` from acting as an oracle for hidden checks and from allowing endless retries. After `finished` no other solution is accepted.
|
||||
- Debug runs (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) run a solution against the public examples and up to ten tests of the candidate while the practice is the current item. They never run, list, or score a hidden check, and change neither the practice state, the verdict, nor the attempt version. A run is queued and read by its own identifier; a repeat with the same Idempotency-Key and body returns the stored run. A per-candidate rate limit and one unfinished run per practice answer 429 `rate_limited` with `Retry-After`. The sandbox queue holds one running and ten waiting runs and solutions together; when it is full, a run answers 503 `service_unavailable` with `Retry-After`, and a final solution leaves the practice `failed` with `sandbox_busy`, which consumes nothing. Without a configured sandbox the operation answers 503 `service_unavailable` without `Retry-After`. A refusal stores nothing.
|
||||
- If the latest submission is still `failed` when the limit passes, the result is `not_determined` with the reason `sandbox_unavailable`. A practice never submitted gives `practice_incomplete`.
|
||||
- An attempt has no practice only in `demo_basic` while code practice is disabled until the sandbox isolation is verified; the result then lists the `practice_not_included` limitation.
|
||||
|
||||
Commands, retries, and versions:
|
||||
|
||||
- Create, start/resume session, answer, and finalize require Idempotency-Key with the 24-hour replay described above, so a repeated command returns the same outcome. Session start, answers, and finalize carry `expected_version`, the attempt `version` the client read. Creation has no version to compare and relies on the key; the single active real attempt per specialization is enforced by the state.
|
||||
- Each item accepts one answer. Sending the stored answer again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Equality is defined per format: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. A different answer for an answered item answers 409 `state_conflict` with the current version; with a stale version the version check comes first and answers 412.
|
||||
- Exception: a practice whose latest verdict is `failed` is outside the repeat rule. A submission with the same or a different solution and the current version queues it again and advances the version.
|
||||
- Finalizing a `completed` attempt answers 200 with that attempt, so the result is computed once. A retry of the finalize that offered an additional practice, sent with a new key, carries the old version and answers 412, so it never declines the offer by accident.
|
||||
- A stale `expected_version` answers 412 `version_conflict`, not 409. This keeps the repository rule and questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the work session ended, the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes lead to different client actions.
|
||||
- A premature finalize answers 409 `state_conflict` without listing the unfinished items, because `Problem` allows no extension fields. The client reads them from the attempt: `state`, `progress`, `current_item`, and `practices`.
|
||||
- Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), attempt ownership (404), the attempt version (412 when supplied), due time or session transitions, then the command state (409 `state_conflict`) and domain rules (400 with pointers such as `/answer/option_ids/0`). An explicit session-start command returns the updated attempt when it commits a due terminal transition. Following the Idempotency-Key convention, stored 404 and 409 responses replay under the key; 400, 412, 429, and 5xx are not stored. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server.
|
||||
|
||||
Result:
|
||||
|
||||
- `GetMyAssessmentResult` answers for a terminal attempt and 409 `state_conflict` for an active one, including `additional_practice_pending`. `outcome` is `confirmed`, `not_confirmed`, or `not_determined` with `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). A result never lowers a confirmed grade: `previous_confirmed_grade` stays in force when the attempt confirmed nothing.
|
||||
- Attempt and result responses carry the `kind` discriminator: `root`, `corrective`, or `demo_express`. Real results always include the correction-chain field pair: both are null for a root attempt, and both are populated for a corrective result. A `demo_express` result is a separate educational shape with a short summary and `demonstration_only`; it has null category, target grade, confirmed grade, strength, uncertainty, and score, and empty practices, gaps, and next steps. It cannot be used as qualification evidence and is never visible to employers.
|
||||
- `calibration_status` and `limitations` describe the method. Fields that the method does not compute are null, never zero: `demo_basic` has null `uncertainty` and `strength`, and `adaptive` has null `basic_score`. `uncertainty` holds `theta`, `standard_error`, `interval_95`, and `p_grade`. `practices` lists the verdicts by kind. `durations` is a separate label and never enters the decision.
|
||||
- `next_steps` come from the server: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (the command is planned), and `take_higher_grade`. A first confirmation is not a promotion, so `take_higher_grade` after it has a null `available_at`; after a promotion the next one waits for the 90-day promotion interval.
|
||||
- The result never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals.
|
||||
- Category from a `demo_basic` result. A real result carries `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), the grade in force before and after the attempt, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`), and `calibration_status`. The threshold comes from the accepted policy version pinned to the attempt: reaching it counts, and no request parameter sets it. A category is assigned only when `ASSESSMENT_DEMO_CATEGORIES_ENABLED` is on, the policy version is a complete demonstration policy with `demo_basic` (its threshold is its own `basic_pass_mark_bp`), and an operator attestation exists for the opening, its manifest, and the policy version; otherwise `status` is `not_eligible` and `confirmed_grade` is null even though `outcome` may be `confirmed`. `confirmed_grade` is set only when a reviewed source accepted the confirmation (`assigned` or `unchanged`). A failure, an equal grade, or a lower grade neither lowers nor changes the current category. `demo_express` never gets a `category_decision` and never creates a category. A result stored before category decisions existed has no `category_decision`: its current grade is not reconstructed afterwards.
|
||||
- `GET /api/v1/me/assessment-results` returns the history of the candidate only: completed `root` and `corrective` results, newest first by `decided_at` and `attempt_id`. The cursor is opaque, bound to the candidate, and uses only `[A-Za-z0-9_-]`; a foreign, altered, or malformed cursor answers 400 `validation_failed` with pointer `/cursor`. An employer account gets 403. A later change of the current policy, bank, or category changes no stored record. An employer receives only the current category (specialization, grade, the coarse strength `standard`, and the basis `basis`) through the anonymous card when the candidate published the `categories` field; the projection holds no attempt, score, version, or reason for a missing confirmation.
|
||||
|
||||
Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the server signals of the anti-cheat layer (answer time, parallel sessions, address changes), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05).
|
||||
|
||||
### Needs
|
||||
|
||||
The `need` tag covers the hiring needs of an organization (PRD FR08, with the versions of FR10): requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/organizations/{org_id}/needs` | `ListOrganizationNeeds` | session | 200 `NeedList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `POST /api/v1/organizations/{org_id}/needs` | `CreateOrganizationNeed` | session and CSRF, Idempotency-Key | 201 `Need`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `GET /api/v1/organizations/{org_id}/needs/{need_id}` | `GetOrganizationNeed` | session | 200 `Need`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `PATCH /api/v1/organizations/{org_id}/needs/{need_id}` | `UpdateOrganizationNeed` | session and CSRF | 200 `Need`, `Cache-Control: no-store` | 400, 401, 403, 404, 412 `version_conflict`, 429 |
|
||||
|
||||
Every operation also declares the `default` problem response. A malformed `org_id` or `need_id` answers 400 with the path pointer.
|
||||
|
||||
Access:
|
||||
|
||||
- `org_id` in the path is the only source of the organization, and the server checks it against the active membership of the session account; no request has an organization, membership, or role field. The organization contract owns organizations and memberships and reuses the same path parameter, `parameters.yml#/OrganizationId`.
|
||||
- An account without an active membership in `org_id`, an unknown organization, an unknown need, and a need of another organization all answer 404 `not_found`, so identifiers cannot be probed. A candidate account answers 403 `forbidden`, and so does a member whose role does not allow the operation.
|
||||
- In the MVP only the owner of the organization works with needs. The other roles of the PRD FR07 matrix (recruiter, hiring manager and technical expert for assigned needs) are planned and change no field of the contract.
|
||||
|
||||
Fields and provenance:
|
||||
|
||||
- `requirements` (`NeedRequirementSet`) holds `specialization`, `grade`, `required_skills`, `desired_skills`, `tasks`, `domain`, `work_formats`, `location`, and `salary`. A field in a response is `{status, value, source}`; a list item has its own `status` and `source`.
|
||||
- `status` is `confirmed` (a member entered or confirmed the value), `extracted` (a suggestion that waits for confirmation), or `unknown` (no value). An unknown field has null `value` and `source`; the server never fills it with a default or a guess such as Senior, remote, or a zero salary. Only confirmed values feed readiness, recommendations, search, and invitations.
|
||||
- `source` has `origin` (`manual`, `extracted_from_text`, or the planned `imported`), `quote` (an exact excerpt of up to 300 characters, or null), `extracted_in_version`, and `extraction_version`. The quote is an excerpt of the `source_text` of `extracted_in_version`, not necessarily of the current text: a confirmed value keeps its quote after the text changes. Confirming a suggestion keeps its provenance; changing the value makes it `manual`.
|
||||
- A skill has `taxonomy_code`. It is null for a skill that the platform taxonomy does not know: the name stays as given, no code is guessed, and recommendations count the skill as not covered.
|
||||
- With `source_text`, the server extracts suggestions with deterministic rules and a dictionary before it answers, so needs work while ML is disabled. ML suggestions with quotes are planned as an asynchronous addition that creates a new version and never overwrites a confirmed value.
|
||||
- The text is stored as written and may contain requirements that discriminate by a protected characteristic; the extractor never turns them into a need field. The field for what a candidate must not have, with the Labor Code article 64 check, is deferred to the requirement validation feature and will be added without a breaking change.
|
||||
|
||||
Requests, confirmation, and changes:
|
||||
|
||||
- Every requirement field in a request is a decision `{value, status}` (`NeedSpecializationInput`, `NeedGradeInput`, `NeedDomainInput`, `NeedWorkFormatsInput`, `NeedLocationInput`, `NeedSalaryInput`), and every list item is `{name or text, status}`. `status` is `confirmed` or `extracted`. A bare value fails validation, so confirmation is always explicit.
|
||||
- `confirmed` with the stored suggested value confirms it and keeps its provenance; `confirmed` with another value sets a confirmed manual value. `extracted` keeps a stored suggestion open and is allowed only with exactly the stored suggested value; any other value, or a field or item without a suggestion, answers 400 with the pointer of that status, such as `/grade/status` or `/required_skills/2/status`. A client that sends back an unchanged form therefore confirms nothing by accident: it sends each suggestion with `extracted` or leaves the field out.
|
||||
- A need never requires a vacancy: only `title` is required, and `vacancy_id` is optional and nullable. Until vacancies exist in the contract, any vacancy identifier answers 400 with the pointer `/vacancy_id`.
|
||||
- On creation every decision must be `confirmed`, because a new need has no stored suggestion. An absent field is extracted from `source_text` or stays unknown. A nullable field sent as null stays unknown, and a skill or task list sent empty stays empty; neither is extracted. An empty `work_formats` value fails `minItems`.
|
||||
- `UpdateOrganizationNeed` uses explicit field replacement in `application/json`, not JSON Merge Patch (RFC 7396): a present field replaces that field as a whole, an absent field stays unchanged, a decision and a list are never merged, and a stored item left out of a sent list is deleted. Null removes a nullable field (it becomes `unknown`, or `vacancy_id` is unlinked); an empty skill or task list deletes every item; a list sent as null answers 400. ogen generates one optional, or optional and nullable, value per decision (`OptNilNeedGradeInput`, `OptNilNeedSalaryInput`).
|
||||
- A different `source_text` extracts again. New suggestions replace only the `extracted` values and items of fields not named in the body; confirmed values are never overwritten, a suggested skill whose name is already in either skill list is skipped, and a suggestion that a member deleted is not proposed again for this need.
|
||||
- The server also rejects a repeated skill or task and a skill in both lists, with 400 and the pointer of the later item, such as `/required_skills/1/name`.
|
||||
|
||||
Versions and concurrency:
|
||||
|
||||
- `version` starts at 1 and advances by exactly one with each committed change, including server-side ones. Each version is an immutable snapshot. GET always returns the latest version.
|
||||
- `requirements_version` is the version in which the confirmed requirements were last changed. Confirming, changing, or removing a requirement sets it to the new `version`; a change of the title, the vacancy link, the text, or suggestions only keeps it and invalidates neither the recommendations nor search results. Search runs, selection snapshots (FR10), and invitations refer to `(need_id, requirements_version)`, and only a new `requirements_version` calls for a new selection snapshot. Reading and comparing earlier versions are planned as separate operations that return `NeedRequirementSet` for a version; they add nothing to `Need`.
|
||||
- A change carries `expected_version`, the version the client read, in the body for the same reason as the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for If-Match and a body version alike. A body that changes nothing answers 200 with the current need even with an older version, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored.
|
||||
|
||||
Readiness:
|
||||
|
||||
- `readiness.missing_fields` lists each critical field without a confirmed value: `specialization`, `grade`, `required_skills` (at least one confirmed skill), `work_formats`, `salary`, and `location` when the confirmed formats include `office` or `hybrid`. Each item has `reason` (`unknown` or `unconfirmed`) and a specific Russian `question`.
|
||||
- An incomplete need is saved (201 or 200), not rejected. `Problem` allows no extension fields, so the missing fields live in the resource, not in a problem. Each later operation, such as search or an invitation, states which readiness it requires.
|
||||
|
||||
Salary:
|
||||
|
||||
- `SalaryRange` `[A; B]` has `salary_from` and `salary_to` (`RubAmount`, whole rubles), `currency` (`RUB` only), `period` (`month` only), and `tax_basis` (`net` or `gross`); every field is required. Requests send it as `salary: {value, status}`, so its pointers are under `/salary/value`.
|
||||
- The schema requires bounds that are positive multiples of 1000 up to 100000000 and rejects another currency, period, or basis, for example with `/salary/value/tax_basis`. A missing field of the nested range answers `required` with its pointer, such as `/salary/value/tax_basis`.
|
||||
- The server checks the cross-field rules of PRD FR13 in integer arithmetic: `A < B` and a width `(B - A) / ((A + B) / 2)` from 10% to 40% inclusive, that is `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B`. A violation, including equal bounds, answers 400 with the pointer `/salary/value/salary_to`. `[95000; 105000]` (exactly 10%) and `[80000; 120000]` (exactly 40%) are accepted. FR13 applies the same rules to the range of a need and of an invitation, and `docs/*/ARCHITECTURE.md` now states them for invitations instead of `0 < salary_from <= salary_to`.
|
||||
- Limit against probing hidden minimums (FR13, enforcement planned): setting a confirmed range, on creation or on a change, counts against a counter shared by the whole organization, every member and every need, so a new need does not reset it. At most three range settings a day; over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private organization risk signals.
|
||||
|
||||
Recommendations:
|
||||
|
||||
- `recommendations` is computed by the server from the confirmed requirements of `requirements_version` with a versioned policy (`policy_version`, `algorithm_version`, `computed_at`). `status` is `computed`, `pending`, or `not_available` without a confirmed skill. The server may recompute them for the same `requirements_version`, for a new policy or a changed pool of candidates, without a new need version; `computed_at` and `policy_version` then change.
|
||||
- Each category (`specialization` and `grade`) has `score`, `skill_overlap` (weighted share with weight 2 for required and 1 for desired skills, covered and uncovered skills), `money`, and `supply` as a band: `fewer_than_5`, `from_5_to_29`, `30_or_more`. The list order is the ranking.
|
||||
- `money.status` is `computed`, `insufficient_data` (fewer than five candidates with a comparable known minimum), `no_salary`, or `withheld`; the last three use the neutral 0.5 and a null share. `money.share` is rounded down to a quarter (0, 0.25, 0.5, 0.75, 1): each probe of a new upper bound then tells at most which quarter of the group accepts it, and in the smallest allowed group of five a single minimum often does not move the value, while the share still separates a range that most candidates accept from one that few accept.
|
||||
- `score` is `0.5 * Overlap + 0.3 * Money + 0.2 * Supply`, rounded half up to two decimals, computed from the published components: the exact overlap, the quarter-rounded share or the neutral 0.5, and `Supply = min(1, active / 30)`. It is null when `supply` is `fewer_than_5`. The ranking uses Supply only at band precision below five: every group of fewer than five candidates enters it with Supply 0, so neither the score nor the order reveals the exact size of a group below five, which FR08 forbids. For five or more candidates the exact Supply is used, so the recommendation fixture (Overlap 1, Money 0.5, 15 active candidates) gives `score` 0.75.
|
||||
- Deviation from the PRD formula: the money share in the score and ranking is the quarter-rounded share, not the exact one, and a category with fewer than five candidates has no score. Otherwise the score with the exact share would reveal the share that `money.share` rounds, and a score with the exact Supply of a small group would reveal its size. The displayed breakdown consists of the published components.
|
||||
- Requests cannot set a recommendation, its score, membership, or a candidate minimum: bodies have `additionalProperties: false`, and unknown fields such as `rec_score`, `members`, `candidate_minimum`, `version`, `requirements_version`, or `recommendations` answer 400 with the whole-body pointer. `TestNeedSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` checks the list decoding, and `frontend/src/shared/api/needs-contract.test.ts` pins the generated Zod limits, the explicit status of every decision, and the absence of these fields in the request types.
|
||||
|
||||
Planned, additive: reading and comparing versions, exclusions, the market range hint (P25-P75) of FR08, the check plan "vacancy -> tasks", a need status for archiving, list filters, and need assignments.
|
||||
|
||||
### Support cases
|
||||
|
||||
The `support` tag covers the cases of the current account (PRD FR18, with the manual assessment of FR04 and C3): questions to support, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The operations are implemented: a guest answers 401 `unauthenticated`, and a verified session passes request validation and the domain rules. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/support-cases` | `ListMySupportCases` | session | 200 `SupportCaseList` of `SupportCaseSummary`, `Cache-Control: no-store` | 400 `validation_failed`, 401 |
|
||||
| `POST /api/v1/me/support-cases` | `CreateMySupportCase` | session and CSRF, Idempotency-Key | 201 `SupportCase`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404 `not_found`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `GET /api/v1/me/support-cases/{case_id}` | `GetMySupportCase` | session | 200 `SupportCase`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 404 `not_found` |
|
||||
|
||||
Every operation also declares the `default` problem response.
|
||||
|
||||
Access:
|
||||
|
||||
- The author is the account of the session; no request has a user, account, or organization field. PRD FR18 lets both candidates and company employees contact support, so `/me` serves both scenarios: an employer account opens `support` cases, and the other types answer 403 `forbidden` for it. A case belongs to the account that created it, not to an organization: other members of the same organization never see it.
|
||||
- Another account's case answers 404 `not_found`, the same as an unknown identifier. The contract answers 404, so identifiers cannot be probed, and the client shows the same "not found" state for a foreign and an unknown case. The author reads the case whatever happened to the object since then, so a refused test or a revoked access never hides it.
|
||||
- The moderation queues are separate staff operations with their own DTOs; they add nothing to these operations.
|
||||
|
||||
Types and object references:
|
||||
|
||||
| Type | Accounts | Object reference | Other fields | Response target |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | policy value |
|
||||
| `complaint` | candidate | required; an `organization` the caller can see or an `invitation` addressed to the caller | required `complaint_reason` | policy value |
|
||||
| `grade_appeal` | candidate | required; a terminal `assessment_attempt` of the caller, or a `support_case` of the caller of type `manual_assessment`, `resolved` with the outcome `assessed` | none | 10 business days |
|
||||
| `anticheat_appeal` | candidate | required; an `assessment_attempt` of the caller with an anti-cheat review decision | none | 10 business days |
|
||||
| `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target`; the server fixes `rubric_version` | 5 business days |
|
||||
|
||||
- The request is a `oneOf` of five variants selected by `type` (`SupportCaseCreateSupport`, `SupportCaseCreateComplaint`, `SupportCaseCreateGradeAppeal`, `SupportCaseCreateAnticheatAppeal`, `SupportCaseCreateManualAssessment`). Each variant restricts its reference schema, so the schema already rejects an organization in a grade appeal or a case in a complaint with the pointer `/object/type`, and a missing field of the type with its pointer, such as `/object` or `/assessment_target`. ogen selects the variant by the value of `type`. An unknown or missing type and a field of another variant such as `complaint_reason` in a support case answer 400 with the whole-body pointer `""`, because they concern the top-level variant; an `object.id` that is not a UUID answers 400 with `/object/id` (example `SupportCaseMalformedReference`).
|
||||
- A category assigned without an attempt is appealed too (FR18): a grade appeal may reference the caller's own manual assessment case once it is `resolved` with `assessed`. An unknown case and another account's case answer 404 `not_found`; an own case of another type, not resolved yet, or resolved with another outcome answers 409 `state_conflict`.
|
||||
- An organization is visible to a candidate that it invited or whose profile the organization contract shows to the candidate, and to an employer account with an active membership. The server checks every reference against the session account: an unknown object and someone else's object both answer 404 `not_found`, so a reference never reveals whether a foreign object exists. The case stores only `{type, id}`.
|
||||
- Invitations are in the contract (see Invitations and contact grants below) but not implemented, and anti-cheat review decisions are not in the contract yet. Until they are implemented, every `invitation` reference answers 404 and every anti-cheat appeal answers 409 `state_conflict`; the request shapes stay the same.
|
||||
- `offer_content` and `salary_terms_violation` complaints require an invitation; another object answers 400 with the pointer `/object/type` (a domain rule after the schema).
|
||||
- A failed first test or no attempt at all never blocks a manual assessment. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt; a manual assessment does not depend on C3. A candidate who revoked C3 (`DELETE /api/v1/me/consents/c3`) or never gave it creates the same request, and the request neither reads nor changes the consent ledger. A retry with the same `Idempotency-Key` returns the original case; a new key (for example after a page reload) while a manual assessment of the same specialization is open answers 409 `state_conflict`, and the open case stays the only one. `rubric_version` is `null` when the target has no single current reviewed category; the server does not guess a rubric, and the case still waits for an expert with no automatic result.
|
||||
|
||||
Content and fields the client never sets:
|
||||
|
||||
- `description` is plain text of 1-4000 characters with at least one character that is not white space (`pattern: \S`); line breaks are allowed. ogen converts `\S` to the ECMAScript white space set, so the Go server and generated Zod both reject an empty text or one of spaces such as U+00A0 or U+3000 with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the implementation adds a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 with the pointer `/description`; Zod accepts it and the server stays authoritative. The server stores the text as written and never writes it to logs or notifications.
|
||||
- Every variant has `additionalProperties: false`. The client cannot set the status, the decision or its outcome, the priority, the response target, the rubric, the assignee, the moderator, or a contact: such fields, for example `status`, `decision`, `moderator_id`, `response_target`, `rubric_version`, or `reply_to`, answer 400 with the whole-body pointer.
|
||||
|
||||
Case:
|
||||
|
||||
- `number` is a human-readable number assigned on creation, `SC-<UTC year>-<sequence>` with at least six digits, for example `SC-2026-000123`. The sequence is global and never reused, so the number is unique and never changes. The API addresses a case only by its UUID `id`; the number is for letters and calls. A global sequence tells the approximate number of cases created so far, which is acceptable for the MVP.
|
||||
- `status` is `submitted`, `in_review`, `waiting_for_user`, `waiting_expert`, `resolved` (terminal, with `decision`), or `closed` (terminal, without a decision on the merits, for example a duplicate). Only the server changes it. `waiting_for_user` is in the enum but not set yet: it starts with the planned operation that lets the author reply. An appeal and a manual assessment move to `waiting_expert` by a `system` event in the same transaction as their creation, so the 201 already shows it; they stay there until a person decides.
|
||||
- `response_target` is the response deadline of FR18: `kind` `operational_goal` (a goal of the team, not a deadline set by law), `business_days`, `due_at` from the configured business calendar, `answered_at`, `late`, and `policy_version`. For `support` and `complaint` the first public reply, a decision, or a closure meets it; for the appeals and `manual_assessment` only a decision or a closure. Missing it never closes the case or changes a grade.
|
||||
- `decision` is null until `resolved` and then holds `outcome` (`upheld`, `partially_upheld`, `not_upheld`, `answered` for support, `assessed` for a manual assessment), the public `reason`, and `decided_at`. An upheld grade appeal never rewrites the original result; the corrected result is a separate decision of the assessment.
|
||||
- `history` lists every public event in order, starting with `created`: `kind` (`created`, `status_changed`, `reply`, `decision`), `actor` by kind only (`user`, `support`, `system`), `occurred_at`, the resulting `status`, and a public `message`. It is never truncated. Server invariant: a case holds at most 200 events, and the server rejects a staff reply or status change that would leave no room for the terminal event, so every case fits and can still be resolved or closed; further correspondence goes into a new case that references it as `support_case`. A truncation flag with paginated events was rejected: it would make the full case depend on a second read, while human staff cannot realistically produce 200 public events on one case.
|
||||
- A case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person.
|
||||
- Replies reach the user through the case. The server may also notify the verified email address of the account with the number and a link, never with the description, the reply, or assessment details; no request field names another address, so the operation cannot send mail to an address that the user typed.
|
||||
- `ListMySupportCases` returns `SupportCaseSummary` items, newest first, with cursor pagination: the number, type, status, object reference, category, response target, `decision_outcome`, and timestamps, without the description and the history. The full case comes only from `GetMySupportCase`.
|
||||
|
||||
Commands and limits:
|
||||
|
||||
- Create requires Idempotency-Key with the 24-hour replay: a retry returns the 201 snapshot stored at creation, with the same case and number, following the repository convention; the client reads the current state with `GetMySupportCase`. 404 and 409 `state_conflict` are stored and replayed; 400, 403, and 429 are not.
|
||||
- An attempt and a resolved manual assessment each accept at most one grade appeal, and an attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a support case that references the appeal as `support_case`. A specialization accepts one open manual assessment and an object one open complaint. A second one, and a grade appeal of an active attempt, answer 409 `state_conflict`.
|
||||
- Every create that passed authentication, validation, and the account scenario counts against a per-account limit from the product policy, including replays, 404, and 409, so the limit also bounds probing of references; over the limit the server answers 429 with `Retry-After`.
|
||||
- Order of checks for create: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the per-account case limit (429), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), domain rules (400), the object reference (404), then the state and the limits (409 `state_conflict`). The general rate limit can answer 429 before any check.
|
||||
- No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract. An unavailable anti-cheat appeal and a repeated appeal both use 409 `state_conflict`, and the case or the attempt tells the client why.
|
||||
- `TestSupportCaseSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, and `frontend/src/shared/api/support-contract.test.ts` pins the generated Zod rules, the absence of status, decision, moderator, and contact fields in the request types, and the absence of moderator identity and internal fields in the case and the summary.
|
||||
|
||||
Open product question for manual assessment: whether repeated manual assessments of the same category follow the retest rules of FR04 (the same grade after 30 days, at most three attempts in 180 days) or their own rule. The contract only allows one open manual assessment per specialization and invents no interval.
|
||||
|
||||
Open questions for manual assessment after a C3 refusal: whether the request needs a structured reason (for example a "C3 refused" marker) instead of the free-text `description`; whether a target with two current categories for the same specialization and grade (different task languages) should get a rubric chosen by language instead of `null`; whether a repeat with a new key should return the existing open case instead of 409. The contract invents none of these.
|
||||
|
||||
Planned, additive (a new operation or an optional field): replies of the author, attachments, withdrawal of a case, list filters by status and type, the resulting category of a manual assessment in the decision, a next step for the author, staff queues and decisions, and the pause rules of the response target.
|
||||
|
||||
Planned contract changes (new enum values; like the catalog codes, generated clients reject an unknown value, so each one is released with regenerated clients): object types `vacancy` and `application` for the vacancies and protected applications of FR16, and an object type for the profile analysis findings. `waiting_for_user` and `support_case` are already in the enums, so the reply operation and follow-up cases need no such change. No new event kind or actor kind is planned: an author reply is a `reply` with the actor `user`, a decision revision is another `decision` event, and experts and moderators are `support`.
|
||||
|
||||
### Invitations and contact grants
|
||||
|
||||
The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, the current visibility of the candidate, the pending limit of a need, and the 30-day pause after a decline, and only then charges the weekly organization quota; the pause after a no deal is not checked yet, because no operation produces that state; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` are implemented as described below, with one limit: the cancellation is not implemented yet. A read and a view at or after the deadline first move a waiting invitation to `expired` with the reason `invitation_timeout` (the read records no view), and a late decline answers 409 `state_conflict`; a declined invitation has `contact_consent` and `contact_grant` null. `AcceptMyInvitation` is implemented as the rules below describe, but the contact read and the revocation of a grant are not implemented yet ([architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/organizations/{org_id}/invitations` | `ListOrganizationInvitations` | session | 200 `OrganizationInvitationList` | 400, 401, 403 `forbidden`, 404 |
|
||||
| `POST /api/v1/organizations/{org_id}/invitations` | `CreateOrganizationInvitation` | session and CSRF, Idempotency-Key | 201 `OrganizationInvitation` (`draft`) | 400, 401, 403, 404, 409 `idempotency_in_progress`, 422, 429 |
|
||||
| `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `GetOrganizationInvitation` | session | 200 `OrganizationInvitation` | 400, 401, 403, 404 |
|
||||
| `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `UpdateOrganizationInvitation` | session and CSRF | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409 `state_conflict`, 412, 429 |
|
||||
| `POST .../invitations/{invitation_id}/send` | `SendOrganizationInvitation` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`delivered`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `POST .../invitations/{invitation_id}/salary-raise` | `RaiseOrganizationInvitationSalary` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `POST .../invitations/{invitation_id}/withdraw` | `WithdrawOrganizationInvitation` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`withdrawn`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `GET .../invitations/{invitation_id}/contacts` | `GetOrganizationInvitationContacts` | session | 200 `ContactDisclosure` | 400, 401, 403, 404 |
|
||||
| `GET /api/v1/me/invitations` | `ListMyInvitations` | session | 200 `CandidateInvitationList` | 400, 401, 403 |
|
||||
| `GET /api/v1/me/invitations/{invitation_id}` | `GetMyInvitation` | session | 200 `CandidateInvitation` | 400, 401, 403, 404 |
|
||||
| `POST /api/v1/me/invitations/{invitation_id}/view` | `ViewMyInvitation` | session and CSRF | 200 `CandidateInvitation` (`viewed`) | 400, 401, 403, 404, 429 |
|
||||
| `POST /api/v1/me/invitations/{invitation_id}/accept` | `AcceptMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`accepted`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `POST /api/v1/me/invitations/{invitation_id}/decline` | `DeclineMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`declined`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `POST /api/v1/me/invitations/{invitation_id}/cancel` | `CancelMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`cancelled_by_candidate`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
|
||||
Every success has `Cache-Control: no-store`, and every operation also declares the `default` problem response. The paths `...` start with `/api/v1/organizations/{org_id}`. 403 on an unsafe operation is `csrf_check_failed` or `forbidden`; 409 on a command is `state_conflict` or `idempotency_in_progress`; 412 is `version_conflict`; 422 is `idempotency_key_reused`. 429 on a command is the general rate limit with Retry-After, which can answer before any check; on create, update, and send it is also the salary limit or the weekly quota. The contact read and the plain reads declare no 429 of their own, like the other reads of the contract.
|
||||
|
||||
Access:
|
||||
|
||||
- Organization side: `org_id` in the path is the only source of the organization, checked against the active membership of the session account, as for needs. An account without the membership, an unknown organization, an unknown invitation, and an invitation of another organization all answer 404 `not_found`; a candidate account and a member whose role does not allow the operation answer 403 `forbidden`. In the MVP only the owner works with invitations; the other roles of FR07 are planned.
|
||||
- Candidate side: `/me/invitations` is bound to the session account. A draft, an invitation addressed to another candidate, and an unknown identifier answer 404 `not_found`; an employer account answers 403 `forbidden`. No request has a user, candidate, organization, or role field.
|
||||
- The candidate is named only by `candidate_handle` (`CandidateHandle` in `common_schemas.yml`, shared with the search results of FR11), never by an email address, a phone number, or an account or profile identifier. An unknown handle, a handle of another organization, and a profile that the organization may no longer see all answer 400 with the pointer `/candidate_handle`.
|
||||
|
||||
Terms (`InvitationTerms`):
|
||||
|
||||
- The terms are complete from the first draft and every field is required: `role_title`, `specialization`, `grade`, `offer_type` (`full_time`, `part_time`, `contract`, `internship`), `tasks`, `team`, `tech_stack`, `work_formats`, `location` (null only for a remote-only role; required for `office` or `hybrid` by a domain rule with the pointer `/terms/location`), `communication_method` (`channel` and an optional note), `salary` (`SalaryRange`), and `package`. A draft without the tax basis or the communication method therefore cannot exist: such a body answers 400 `required` with `/terms/salary/tax_basis` or `/terms/communication_method` (examples `InvitationWithoutTaxBasis` and `InvitationWithoutCommunicationMethod`).
|
||||
- `package` has `bonus`, `equipment`, `training`, and `health_insurance` (ДМС). Each is a `oneOf`: `{status: provided, description}` or `{status: not_provided}` ("Не предусмотрено" in the interface). "Not provided" is an explicit choice: a condition left out answers `required` with its pointer, such as `/terms/package/training`; a `provided` one without a description answers `required` at its `description`; a `not_provided` one with a description answers `invalid` at the item. Generated Zod is not strict and strips that description, so only the server rejects it.
|
||||
- Deliberate deviation from the wording of the acceptance criteria: the PRD package lists the work format next to the bonus, equipment, training, and ДМС, but here the format is the required `work_formats` term without a "not provided" variant, because a role always has a format and the indicator and the search compare it. This is an open question for the product owner.
|
||||
- The same schema is the request field and the stored snapshot, so a response can be sent back unchanged. The terms never contain data of the candidate.
|
||||
|
||||
Versions and conflicts:
|
||||
|
||||
- `version` advances with every committed change, including the view and the server expiry. `terms_version` advances only when the terms change: a draft change of `terms`, or the one raise of the upper bound after sending. Each terms version is immutable.
|
||||
- Every command except the view carries `expected_version`; `AcceptMyInvitation` also carries `terms_version`. 412 `version_conflict`: `expected_version` or, on acceptance, `terms_version` is not current (the stale terms case, example `InvitationStaleTerms`); nothing changed, nothing is stored under the key, and the client reads the invitation again. 409 `state_conflict`: the state does not allow the command, for example an acceptance of a withdrawn or expired invitation, a command at the deadline or later, a send blocked by the pending limit of a need or by the 30-day pause, a change of a sent invitation, or a second raise; it is stored under the key. The repository rule keeps 412 for any stale version, as for needs and the questionnaire.
|
||||
- Order: after the invitation is found and a due expiry is applied, and after the repeat check, a terminal state (`declined`, `expired`, `withdrawn`, `cancelled_by_candidate`) or, for accept and decline, a passed deadline answers 409 before the version is compared, so the client gets 409 for a withdrawn, expired, or late invitation even with stale versions and shows the final state instead of rereading and retrying. Then come the versions (412) and the remaining state rules (409). This applies to accept, decline, cancel, withdraw, and the salary raise.
|
||||
- Repeats return the same result: a retry with the same Idempotency-Key replays the stored outcome, and a repeated command whose transition already happened answers 200 with the current invitation even with a new key or an older version: a send of a sent invitation, a withdrawal of a withdrawn one, a decline with the same reason and comment, a cancellation of a cancelled one, the same raise, and an acceptance whose `terms_version` and fields equal those of `contact_grant`, the version and fields the candidate accepted, even when a later raise advanced the current `terms_version`. No second consent, grant, quota charge, or audit event is created.
|
||||
- `UpdateOrganizationInvitation` follows the convention of `UpdateOrganizationNeed`: no Idempotency-Key, explicit field replacement, and a body that changes nothing answers 200.
|
||||
|
||||
States and the view:
|
||||
|
||||
- `InvitationState` lists every state of the FR12 table: `draft`, `delivered`, `viewed`, `counter`, `accepted`, `interview_scheduled`, `interviewed`, `negotiation`, `terms_agreed`, `no_deal`, `declined`, `expired`, `withdrawn`, `cancelled_by_candidate`. MVP operations produce `draft`, `delivered`, `viewed`, `accepted`, `declined`, `expired`, `withdrawn`, and `cancelled_by_candidate`; the others are listed now so that generated clients accept them when the counter offer, the interview, and the sealed final arrive. The internal `SENT` step is never visible: a send answers with `delivered` after the inbox entry exists.
|
||||
- `expiry_reason` is `invitation_timeout` or the planned `negotiation_timeout`, non-null exactly in `expired`.
|
||||
- The view is an explicit command, `ViewMyInvitation`: it moves `delivered` to `viewed`, keeps the deadline, and returns the current invitation unchanged in any other state. It is idempotent by its effect, so it needs neither an Idempotency-Key nor an `expected_version`, and it never fails because the invitation changed after the client read it. `GetMyInvitation` and `ListMyInvitations` have no side effect; a read only shows a due expiry, which the server applies at the deadline anyway. The command keeps prefetches, retries, and cache refreshes from changing the state that the organization sees.
|
||||
- `withdrawn` is the organization's command from any unfinished state, including `draft` and `accepted`, and keeps an existing grant. `cancelled_by_candidate` is the candidate's command from any unfinished state after delivery and revokes the grant of this invitation. A decline is the structured answer before an acceptance.
|
||||
- The deadline is `delivered_at + response_period_days` (3, 7, or 14 days, 7 by default). A view, an email, or a raise never moves it; a command received at the deadline or later is late.
|
||||
|
||||
Salary and the hidden minimum:
|
||||
|
||||
- The terms reuse `SalaryRange` with the rules of the Needs section: RUB, month, `net` or `gross`, positive multiples of 1000, `A < B`, and a width of 10-40%, checked by the server with the pointer `/terms/salary/salary_to`.
|
||||
- The organization receives only `salary_fit`: `within_range`, `up_to_10_percent_above`, `above`, `withheld`, or `not_available` (no minimum for the offered formats, or one in the other tax basis). The exact minimum appears in no response, example, log, or problem. The server never rejects a range because of the minimum, since a rejection would reveal it. The candidate DTOs carry no indicator; the candidate compares with the own minimum in the profile.
|
||||
- Every change that can move the indicator is an indicator-relevant setting: the range on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, because the indicator compares with the minimum for the offered formats. Each counts against the organization-wide limit of three settings a day, shared with the ranges of needs (429 with Retry-After), and against the withheld counter. A change that keeps the range, the basis, and the formats does not count.
|
||||
- `withheld`: after five indicator-relevant settings within seven days the indicator is off for seven days from the fifth. The response to the fifth setting already shows `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.
|
||||
- Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting.
|
||||
- After a send the base is fixed and the lower bound never decreases. `RaiseOrganizationInvitationSalary` raises `salary_to` once in the whole history of the invitation, creates the next terms version, and answers 409 on a second raise. It follows its own once-only rule and does not count against the daily limit, but it counts against the withheld counter because it moves the upper bound that the indicator compares.
|
||||
|
||||
Consent C4 and the contact grant:
|
||||
|
||||
- `GetMyInvitation` shows in `contact_consent` the C4 text for this organization and the kinds of contact that the profile holds. It is null when an acceptance is impossible: the state or the deadline does not allow it, or the profile holds no contact. In the last case the client asks the candidate to add a contact first, because a grant must cover at least one field.
|
||||
- `AcceptMyInvitation` sends `terms_version`, `expected_version`, and `consent_c4` (`ContactConsentAcceptance`): the shown C4 text version, `accepted: true`, and `fields`, at least one of `full_name`, `email`, `phone`, `telegram`, with no default and no preselection. A text version that is not published answers 400 `/consent_c4/text_version`, and a field the profile does not hold answers 400 `/consent_c4/fields/<i>`. The consent is analogous to the C1 acceptance by its `text_version`, and the record matches the C4 consent ledger (purpose, text version and hash, organization, field set, source invitation). The permission to pass the data on to the organization's ATS (C4 and FR19) is planned as an additive optional flag that defaults to no transfer.
|
||||
- In one transaction the acceptance moves the invitation to `accepted`, records C4, creates the grant for exactly the selected fields, and writes the audit event. It never publishes the profile (C2) and never lifts a hiding.
|
||||
- The candidate's `contact_grant` has `status` (`active` or `revoked`), `readable`, and `blocked_by`. A grant created while the profile was not published or was hidden from the organization stays `active` with `readable: false` and `blocked_by: visibility`, so the candidate sees why the organization cannot read it (PRD FR12); it becomes readable once the candidate publishes the profile or unhides it. Any visibility change after the grant exists revokes it (`visibility_closed`), and a later publication never reopens it.
|
||||
- Contact values travel only in `ContactDisclosure` from `GetOrganizationInvitationContacts`, separate from the terms and the invitation. Each read checks the membership, C4, the grant and its fields, and the current visibility, without a cache. Without a readable grant the operation answers 404 `not_found`, the same as an unknown invitation. The organization's `contact_access` is `not_granted` (no grant), `available` (with the field kinds), or `closed`, which covers a revoked grant and a grant blocked from the start without saying which. This is the least revealing rule: a revocation, a hiding, and a missing publication look the same, and since every visibility change after the grant revokes it, the organization never observes a later toggle; only a grant blocked from the start can turn `available`, by the candidate's own choice. Fields that the grant does not cover are null.
|
||||
- Revocation: `CancelMyInvitation` revokes the grant of this invitation (`participation_cancelled`); revoking C4 for the organization closes all its grants (`consent_revoked`); revoking C2 or hiding the profile closes them (`visibility_closed`). A withdrawal, a no deal, and a negotiation timeout never revoke a grant; only a new explicit C4 creates a new one. A standalone grant revocation operation belongs to the consent contract.
|
||||
- Implementation: the contact read, the C4 and C2 revocations, the closing of the publication, and hiding are implemented, owner only, and close the grants as the bullet above states (architecture: [Contact reads and revocation](../docs/en/ARCHITECTURE.md#contact-reads-and-revocation)). The organization's `contact_access` is derived on every read of an invitation (`GetOrganizationInvitation`, the list, and the create, update, and send responses) with the checks of the contact read, so it shows `available` only where a read would succeed, and it never names a reason. `CancelMyInvitation` is not implemented yet.
|
||||
- Value formats: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never converts or drops a stored value.
|
||||
|
||||
Decline and privacy:
|
||||
|
||||
- `DeclineMyInvitation` takes `reason` (`salary`, `tasks`, `stack`, `work_format`, `package`, `company`, `not_looking`, `other_offer`, `other`) and an optional `comment` of up to 500 characters; `other` needs no comment. The organization sees only `declined` and `responded_at`, never the reason or the comment: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size (planned). The candidate reads both back in `decline`.
|
||||
- No invitation DTO of either side carries the candidate's name, email address, phone number, Telegram username, account or profile identifier, or salary minimum; examples use synthetic data only. `TestInvitationSchemaValidationPrecedesImplementation` checks the schema rejections and pointers through the generated server, `TestInvitationDTOsCarryNoContactOrMinimum` checks the generated Go DTOs, and `frontend/src/shared/api/invitation-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of contact, minimum, and decline fields.
|
||||
|
||||
Open product questions: whether a second unfinished invitation of the same organization to the same candidate is allowed (the PRD is silent, so the contract invents no rule), the package format deviation above, the offer types, the contact kinds, and the decline reasons.
|
||||
|
||||
Planned, additive: the counter offer and the company answer, reading earlier terms versions, interview and sealed final operations, list filters, the responsiveness metrics of the organization for the candidate, the approximate amount in the other tax basis, decline aggregates, the ATS flag of C4, and FSP fields as new contact kinds (a new enum value, released with regenerated clients).
|
||||
|
||||
No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract, and `version_conflict` and `state_conflict` cover the stale terms and the state conflicts.
|
||||
|
||||
### Consents
|
||||
|
||||
The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. Implemented handlers provide public C1 text, current settings text and the caller's own history, settings grants of C1/C2/C3/C5, revocation of C2/C3/C5, scoped C4 revocation for one organization, and a durable C1 account-deletion request. The request does not synchronously delete the account. Protected operations require an active verified PostgreSQL session; mutations also require the session-bound CSRF token and the sole `Origin` matching `APP_PUBLIC_URL`. Guests receive 401; a disallowed account role, Origin, or CSRF token receives 403.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/identity/consent-texts/c1` | `GetConsentText` | public | 200 `ConsentText` | 400 `validation_failed` |
|
||||
| `GET /api/v1/me/consent-texts/{purpose}` | `GetMyConsentText` | session | 200 `ConsentText`, `Cache-Control: no-store` | 400, 401 |
|
||||
| `GET /api/v1/me/consents` | `ListMyConsents` | session | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 |
|
||||
| `PUT /api/v1/me/consents/{purpose}` | `GrantMyConsent` | session and CSRF | 200 `ConsentRecord`, `Cache-Control: no-store` | 400, 401, 403 |
|
||||
| `DELETE /api/v1/me/consents/{purpose}` | `RevokeMyConsent` | session and CSRF | 204 | 401, 403 |
|
||||
| `DELETE /api/v1/me/consents/c4/organizations/{org_id}` | `RevokeMyOrganizationContactConsent` | session and CSRF | 204 | 400, 401, 403 |
|
||||
| `POST /api/v1/me/account-deletion-requests` | `RequestMyAccountDeletion` | session and CSRF | 202 `ConsentDeletionRequest`, `Cache-Control: no-store` | 401, 403 |
|
||||
|
||||
- Purposes (`ConsentPurposeCode`): `c1` personal data processing, `c2` publication of the candidate card, `c3` automatic categorization, `c4` transfer of selected contacts to one organization, `c5` import of FSP results. Public `GetConsentText` remains C1-only. `GetMyConsentText` returns the current C1/C2/C3/C5 text before a settings grant. C4 text remains part of an invitation with its specific scope.
|
||||
- The subject comes from the session; no parameter names an account, so the response holds only the caller's own records. A page lists records newest grant first with cursor pagination; the optional `state` filter takes `active`, `superseded`, or `revoked`, and an unknown value answers 400 with the pointer `/state`.
|
||||
- A `ConsentRecord` has the purpose, the accepted `text_version`, the `source` (`registration`, `consent_settings`, or `invitation_acceptance`), `granted_at`, the computed `state`, and `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A `c4` record also names the `organization` (`ConsentOrganization`, whose `name` is the snapshot the consent text showed, so a later rename does not change it), the contact `fields` (`ContactFieldKind`), the `invitation_id`, and the `invitation_terms_version`; they are null for every other purpose. A `c2` record proves the consent to the publication text; which fields were published, and when, is evidence of the publication history ([Candidate visibility](#candidate-visibility)), and a field scope on `c2` records would be an additive change. The record never carries a contact value, the subject, or the text hash: the server stores the SHA-256 of exactly the text the subject saw, and the client never sends or receives it, as for C1 at registration.
|
||||
- Settings grants require explicit `accepted: true` and the current version of the text the user read. C1 is available to candidate and employer accounts; C2/C3/C5 are candidate-only. C4 is excluded from the general settings grant and is granted only when accepting a specific invitation.
|
||||
- The ledger is append-only. A newer text version is a new record and the earlier one becomes `superseded` without changes; revocation stamps every unrevoked record of the purpose, including earlier versions. C4 revocation is limited to one organization and takes its fields from stored records, never from request data. Repeated revocation is harmless and creates no duplicate event.
|
||||
- C2 revocation closes the current publication, clears its fields, appends privacy history, and writes a bounded outbox intent in one transaction. A later C2 grant does not reopen the old publication. C3 revocation does not block the manual assessment path. C5 revocation immediately closes the consent gate for future imports and writes a stop/delete intent; no external FSP adapter exists, so actual deletion at FSP is not claimed.
|
||||
- A C1 deletion request revokes C1 and creates or returns an active durable request plus an outbox intent in one transaction. Repeats return the same request; a later C1 grant never cancels it. The future account-deletion processor is not synchronous and is not implemented yet.
|
||||
- The C4 permission to pass data on to an ATS and the C4 of an application (PRD Q9) are planned as an additive flag and an additional `source` value.
|
||||
|
||||
Open legal item: whether `c2` is a consent to the distribution of personal data under article 10.1 of 152-FZ, which requires its own consent with the categories of data.
|
||||
|
||||
No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, and `csrf_check_failed`. Contract tests pin the security schemes and validation order, `TestConsentSettingsOverHTTP` exercises consent behavior with real PostgreSQL and Redis, and `frontend/src/shared/api/consent-contract.test.ts` pins generated Zod rules and the absence of hashes, subjects, and contacts from the DTOs.
|
||||
|
||||
### Organizations
|
||||
|
||||
The `organization` tag includes implemented creation, reading, editing, and the current account's organization directory. A verified employer creates an organization with an active owner; organization-scoped operations require an active owner on each request. Unsafe operations require the session CSRF token and exact Origin. The common middleware also protects unimplemented need and invitation operations before their 501 fallback. See [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships).
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/organizations` | `ListMyOrganizations` | session | 200 `MyOrganizationList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
|
||||
| `POST /api/v1/organizations` | `CreateOrganization` | session and CSRF, Idempotency-Key | 201 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `GET /api/v1/organizations/{org_id}` | `GetOrganization` | session | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `PATCH /api/v1/organizations/{org_id}` | `UpdateOrganization` | session and CSRF | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404, 412 `version_conflict`, 429 |
|
||||
|
||||
Every operation also declares the `default` problem response. A malformed `org_id` answers 400 with the path pointer.
|
||||
|
||||
Active organization context:
|
||||
|
||||
- The context is not stored on the server. Every organization-scoped operation, including the needs and invitations of this contract, names its organization in the path `org_id`, and the server checks that identifier against the active membership of the session account on every request. The identifier grants nothing; a switch between organizations is another `org_id` in the client's routes.
|
||||
- Reason: a session attribute would be a cache of the membership that a removal, a suspension, or a leave would have to invalidate (the next read must be closed without waiting for the browser cache to expire), it would make two tabs in two organizations fight over one value, and the path form is already the contract of needs and invitations. Organization switching clears the tenant-scoped client queries on a switch, which fits a client-side context.
|
||||
- `ListMyOrganizations` is the directory of contexts: the organizations where the caller has an `active` membership, newest membership first, with the caller's role and state. A client picks the context from it, may remember the last choice in the browser as a convenience, and reads the list again after a 404 from an organization path. A person with several memberships sees all of them and works in one at a time; the rights and the data of the organizations stay separate.
|
||||
|
||||
Access:
|
||||
|
||||
- An employer account only. A candidate account answers 403 `forbidden` on all four operations, and an account without a session answers 401.
|
||||
- `GetOrganization` and `UpdateOrganization` answer 404 `not_found` for an account without an active membership in `org_id` and for an unknown organization alike, and also for a `suspended`, `removed`, or `left` member, so organizations cannot be enumerated and a revoked member loses the next read at once. A member whose role does not manage the organization answers 403 `forbidden` on `GetOrganization` and `UpdateOrganization`; the FR07 matrix gives managing the company and its staff to the owner only. In the MVP every member is an owner, because the operations that add members are planned.
|
||||
- `CreateOrganization` creates the organization and the owner membership of the caller in one transaction (role `owner`, state `active`), so an organization never exists without an owner; the database refuses to commit one that has none. The body has no owner, role, membership, or verification field.
|
||||
|
||||
Memberships:
|
||||
|
||||
- A membership is `(user, organization, role, state)` and is unique per pair in any state. `OrganizationRole` has `owner`, `recruiter`, `hiring_manager`, and `technical_expert` (PRD 2.2 and Q3). `MembershipState` has `active`, `suspended` (access stopped, restorable), `removed` (ended by the owner or the platform), and `left` (ended by the member). Only `active` gives access, and the listing returns only `active` memberships; `joined_at` is the moment the membership was first created (a member who returns keeps it, and the latest activation time is a planned `activated_at` field); a membership `removed` by the platform must not be reactivated by the owner, by an invitation acceptance, or by the member management on their own, and who removed the member and why become additive fields of the member management; the other states are in the enum so that member management can show them without a contract change. Adding a role or a state is a contract change.
|
||||
- The role lives in the membership only. `Organization`, `OrganizationCreate`, `OrganizationUpdate`, and `CandidateOrganizationCard` have no role, owner, or member field. The caller reads their own role in `OrganizationMembership` from `ListMyOrganizations`; the DTO names no account.
|
||||
- There is no `invited` state: an employee joins only through an invitation to an email address (PRD 2.2), which the member-invitation tasks store as a separate record and turn into an `active` membership when the owner of the address accepts it. A person may hold independent memberships in several organizations.
|
||||
- Applying the full role matrix (recruiter, hiring manager, technical expert) to needs, invitations, and contacts is planned as part of role-based access control. Until then the other roles grant nothing: the operations of needs and invitations answer 403 `forbidden` for them, as their sections say. Listing and managing members, changing roles, removing members, and the rule that the last owner cannot be removed are planned as part of membership management and add operations, not fields, to this contract.
|
||||
|
||||
Profile:
|
||||
|
||||
- `OrganizationCreate` requires only `name`. The profile fields are `name` (1-200 characters, no surrounding whitespace or line break, because a consent record keeps a copy), `description` (1-2000 characters, nullable, line breaks allowed), `sphere` (1-100 characters, nullable, free text: the PRD has no sphere taxonomy, and a taxonomy code would be an additive field), `contacts`, and `representatives`.
|
||||
- `contacts` is one object with `website`, `email`, `phone`, and `telegram`, all required and nullable, so it is the request field and the stored value alike. They are public company channels: an https website without credentials, a port, or an IP address, a careers mailbox, an E.164 phone number, and a Telegram username with the leading `@`. The contract holds no personal contact of an employee, and the server cannot tell a personal address from a company one, so the owner answers for the content; a complaint about an organization goes through a support case. The server never fetches the website.
|
||||
- `representatives` is a list of up to ten `{name, job_title}` entries in the order the owner gave them. A representative is presentation only: not a member, with no account link, no contact, and no right, and a member does not become one by joining. The name is personal data of an employee that the owner publishes, which makes the open question below.
|
||||
- `UpdateOrganization` uses explicit field replacement, as `UpdateOrganizationNeed` does: a present field replaces that field as a whole, an absent field stays unchanged, and `contacts` and `representatives` are never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. ogen generates `OptNil` values for the nullable fields and a plain slice for `representatives`, where nil is absent and `[]` is an empty replacement; a handler must test it with `!= nil`, never with `len` (`TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`).
|
||||
- Text is plain: clients show every field as text, never as HTML. Domain rules that need more than the schema, such as the host rules of the website, answer 400 with a pointer (`/contacts/website`, `/representatives/0/job_title`); the examples show the shapes.
|
||||
|
||||
Verification level:
|
||||
|
||||
- `OrganizationVerificationLevel` is `e0`, `e1`, `e2`, or `e3` (PRD FR07). A new organization starts at `e0` on the basis `confirmed_email`, whatever its profile looks like. The server reports a higher level only after a verification process recorded it; the processes for `e1`, `e2`, and `e3` do not exist yet (the planned verification flow adds E0/E1 with evidence, a scope, and a history), so a client treats every level but `e0` as unavailable and the contract never reports `e1`, `e2`, or `e3` as reached on its own.
|
||||
- No request sets or raises a level or its basis: `OrganizationCreate` and `OrganizationUpdate` are closed objects with only the profile fields, no operation of the contract changes the level, and editing the description, the contacts, or the representatives leaves it as it is. The database keeps the level and the basis in their own columns that the profile statement never writes, and a CHECK ties each level to its own bases. `OrganizationVerification` is read-only: `level`, `basis`, and `changed_at`; the scope of the check and the history of changes (PRD FR07) arrive as additive fields with the first process.
|
||||
- The level selects the quota tier (E0 10 invitations and 50 cards, E1 40 and 150, E2 100 and 400 in the demo policy); `domain.OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the tiers of the policy and has none for `e3`, which the PRD gives a separate policy. Quota enforcement is a separate planned feature.
|
||||
|
||||
Candidate card and versions:
|
||||
|
||||
- `Organization.candidate_card` is the card as a candidate sees it, built by the server from the profile and the level: the preview of PRD FR07. Only a candidate who received an invitation from the organization sees it; it is not a public page, and no operation shows it to anyone else until the question about the names of representatives below is decided. It repeats the profile fields and adds the level only; it has no membership, role, account, version, or basis. Its `representatives` is optional and nullable: absent or null means that they are not published, not that there are none. The invitation contract names the organization with `InvitationOrganization` and plans to return this card to the candidate additively.
|
||||
- `version` starts at 1 and advances with every committed change of the profile. A change carries `expected_version` in the body for the reason the needs give: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for a stale version, as for needs. A body that changes nothing answers 200 with the current organization, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored.
|
||||
- Order of the checks of `UpdateOrganization`: session (401), CSRF and Origin (403), request validation (400), account scenario (403), membership (404) and role (403), a body that changes nothing (200), the version (412), domain rules (400).
|
||||
|
||||
Foreign keys to organizations: `memberships` and `organization_representatives` reference `organizations(id)` now. The consent ledger, the needs, and the invitations carry an `organization_id` and reference it with a restricting foreign key in the migration that creates the invitation records, because the C4 scope needs both references at once and the consent ledger tests use synthetic organization identifiers. The application never deletes an organization.
|
||||
|
||||
Open questions for the product owner:
|
||||
|
||||
- Representatives: may the card show their names to every candidate before an invitation is accepted, and who answers for the right to publish an employee's name (152-FZ)? The alternative is to show representatives only in an invitation sent by their organization.
|
||||
- Sphere: free text now; a taxonomy for the sphere, matching the domains of needs, is a decision for the search filters.
|
||||
- Contacts: whether the card needs a fifth kind, such as a careers page, and whether the email must share the domain of the website.
|
||||
|
||||
Decided by the product owner: organizations per account are not limited. The organizations of one account form a holding, and the E0 quotas (in the demo policy 10 invitations per 7 days and 50 distinct card views per 24 hours) are shared by the E0 organizations of that holding; an organization at E1 and above counts its own quotas. The contract does not change: the holding is internal and no operation exposes it.
|
||||
|
||||
Planned, additive: member invitations, listing, role changes, and removal, the full role matrix, the verification processes and their history, the quotas by level, the card in the candidate's invitation, and a sphere code.
|
||||
|
||||
No new problem code is added: the contract reuses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused`, and `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`, and `TestOrganizationContractFollowsThePRD` pin the generated server and the bundle, and `frontend/src/shared/api/organization-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of role, owner, member, and verification fields in the requests.
|
||||
|
||||
### Candidate visibility
|
||||
|
||||
The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD). The operations are in the contract but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)).
|
||||
|
||||
| Method and path | operationId | Protection | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/privacy` | `GetMyPrivacySettings` | session | 200 `PrivacySettings`, `Cache-Control: no-store` | 401, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/privacy/publication` | `SetMyPublication` | session and CSRF | 200 `Publication`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict`, 412 `version_conflict` |
|
||||
| `GET /api/v1/me/privacy/preview` | `GetMyCardPreview` | session | 200 `CardPreview`, `Cache-Control: no-store` | 401, 403 |
|
||||
| `PUT /api/v1/me/privacy/search-status` | `SetMySearchStatus` | session and CSRF | 200 `SearchStatus`, `Cache-Control: no-store` | 400, 401, 403, 412 |
|
||||
| `GET /api/v1/me/privacy/hidden-organizations` | `ListMyHiddenOrganizations` | session | 200 `HiddenOrganizationList`, `Cache-Control: no-store` | 400, 401, 403 |
|
||||
| `PUT /api/v1/me/privacy/hidden-organizations/{org_id}` | `HideOrganization` | session and CSRF | 200 `HiddenOrganization`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 409 `state_conflict`, 429 |
|
||||
| `DELETE /api/v1/me/privacy/hidden-organizations/{org_id}` | `UnhideOrganization` | session and CSRF | 204 | 400, 401, 403 |
|
||||
| `GET /api/v1/me/privacy/history` | `ListMyPrivacyHistory` | session | 200 `PrivacyEventList`, `Cache-Control: no-store` | 400, 401, 403 |
|
||||
| `GET /api/v1/me/privacy/access-history` | `ListMyCardAccessHistory` | session | 200 `CardAccessList`, `Cache-Control: no-store` | 400, 401, 403 |
|
||||
|
||||
Each operation also declares the problem response `default`. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `state_conflict`, `version_conflict`, and `rate_limited`. An employer account answers 403 `forbidden` on all nine operations.
|
||||
|
||||
Closed by default and three independent settings:
|
||||
|
||||
- A profile is closed by default. A candidate who never published reads `publication.state` `closed`, `closed_reason` `never_published`, an empty field set, and version 0; saving the profile, filling in the questionnaire, or taking an assessment never publishes it. Every setting has its own `version` (0 is "never set"), its own operation, and its own `expected_version` in the body, so a change of one never makes another stale.
|
||||
- The publication and C2 are separate. The consent C2 stays in the consent ledger (`ListMyConsents`) and proves that the candidate accepted the publication text. `Publication` records which fields are published and when, and refers to the C2 record behind them (`consent_id`, the `id` of a `ConsentRecord` of the same account). It does not duplicate the consent: `state` is `published` only while that record is unrevoked, so a revocation of C2 closes the card at once, and `closed_reason` says `consent_revoked`. A new C2 grant never reopens it: the candidate publishes again and the new publication binds to the new record. The body of `SetMyPublication` names no consent: the server binds the current unrevoked C2 record of the account, and without one answers 409 `state_conflict` (the candidate gives C2 first; the grant operation is planned in the consent settings).
|
||||
- The search status is not a consent. `SearchStatus` and `SearchStatusUpdate` have no consent, publication, or organization property, no schema of one family reaches another (a test walks the references), and `SetMySearchStatus` changes nothing but the status. A candidate whose profile is closed who sets `looking` becomes visible to no one.
|
||||
- Hidden organizations are records of the candidate (`HiddenOrganization`: the organization with its current name and `hidden_at`). One record per candidate and organization, at most 1000 per candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published. Hiding and lifting a hiding change neither C2, nor the publication, nor the search status.
|
||||
- Hiding is a PUT of a state, so it is idempotent and takes no Idempotency-Key: hiding an organization again answers 200 with the original record and writes no history. Lifting is a DELETE that answers 204 whether the organization was hidden or not.
|
||||
|
||||
The search status and its 30 days:
|
||||
|
||||
- `looking` ("Ищу") stores `confirmed_at` and `lapses_at`. The interval is not a constant of the contract or the code: it is `search_status.searching_confirmation_interval_days` of the effective `product` policy version (30 in the demo version 1), read when the status is confirmed. The stored row names the policy version it used and fixes `lapses_at`, so a later policy change moves no stored time. The owner changes the interval by publishing a new policy version.
|
||||
- After `lapses_at` the status holds as `not_looking` with `lapsed` true. The lapse is computed on every read and never written, so it needs no job and can only narrow: it never publishes, never unhides, and never changes C2 or the hidden organizations. The candidate confirms again with `SetMySearchStatus` and `looking`, which replaces `confirmed_at` and advances the version. A reminder before the lapse is a planned notification.
|
||||
- A lapsed status is never "more public": the non-public `not_looking` is the only state a lapse reaches. Whether `looking` gates the appearance of a published card in search results is a search contract decision, not decided here.
|
||||
|
||||
The anonymous card and the preview:
|
||||
|
||||
- `CardField` is a closed set of groups of card values that the candidate chooses to publish: `categories` (the categories confirmed by assessment results), `stack`, `experience` (total months), `soft_skills`, `location`, and `relocation`. The full name, any contact, and the lowest salary have no value, so no request can publish them; contacts reach an organization only through the contact grant of an accepted invitation (C4), and the lowest salary never does. A self-assessed grade is not a category and is never published. The server stores and answers the set in ascending order of the codes.
|
||||
- `AnonymousCardContent` is the card as an organization reads it: a closed object of the six properties above, each null when it is not published or has no value, so the card does not tell the two apart. It has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and no schema of the private profile, a contact, a consent, an invitation, or an organization is reachable from it (`TestAnonymousCardReachesNoProfileOrContactSchema` walks the references). `GetMyCardPreview` returns it with the published fields, or `card` null while the profile is closed, as a private read that creates no view and no history record. The card of an organization's search result must reuse this content and cannot add a property that identifies the candidate.
|
||||
|
||||
Versions and checks:
|
||||
|
||||
- Both `PUT` operations of the settings follow the profile pattern: the complete new state in the body, `expected_version` in the body (the generated client cannot read the ETag yet), 412 `version_conflict` for a stale or non-existent version, and an unchanged body answers 200 with the current state even over a stale version, so no Idempotency-Key is needed. Order of checks: session (401), CSRF and Origin (403), request validation (400), account scenario (403), a version above the current one (412), an unchanged state (200), a stale version (412), then the C2 for a publication (409). A published state without a field and a closed state with a field answer 400 with the pointer `/fields`; the schema rejects an unknown or repeated card field and unknown properties such as a consent identifier or a confirmation time. `looking` always changes the stored confirmation, so it answers 412 for a stale version even as a repeat. The two 409 `state_conflict` answers are told apart by `errors`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. A closing over a stored publication whose C2 was revoked is a real change (it stores the closing, records `publication_closed`, and revokes the grants); the C2 revocation path closes the stored publication and revokes the grants in its own transaction. Publishing, hiding, and the history need a verified email (a usecase requirement). `Problem.errors` is not only for `validation_failed`: a `state_conflict` carries one entry as a disambiguator (`consent_required`, `limit_reached`), so a future problem writer must not strip `errors` from non-validation responses. Only values that the candidate confirmed reach the card, a free text value that looks like a contact (email, phone, URL, Telegram link, @handle) is dropped, and adding a card field is a contract change and a migration.
|
||||
- 404 and anti-enumeration. `HideOrganization` answers the same 404 `not_found`, with the same body and without a different timing, for an organization that does not exist and for one that the candidate cannot see, so it is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned). The identifiers are random, and the general rate limit can answer 429 with Retry-After before any check. `UnhideOrganization` reveals nothing: 204 for any well-formed identifier. A malformed `org_id` answers 400 with the pointer `/org_id`.
|
||||
- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke that grant with the reason `visibility_closed`, in the same transaction as the change (planned together with the operations; the reason is fixed in the invitation contract). Lifting a hiding or publishing again never reopens a grant. The search status never revokes a grant.
|
||||
|
||||
History:
|
||||
|
||||
- `ListMyPrivacyHistory` returns the append-only history of the settings, newest first (the history stores only the organization identifier, and the current name is resolved when it is read): `publication_opened`, `publication_changed` (with the published fields and the `consent_id` behind them), `publication_closed`, `search_status_confirmed`, `search_status_cleared`, `organization_hidden`, and `organization_unhidden` (with the organization's current name). This is the evidence of the published field set and its changes with their times that the C2 record does not carry. A revocation of C2 and a lapse are computed and are not events; the consent history shows the revocation. The history holds no profile value.
|
||||
- `ListMyCardAccessHistory` returns the accesses of organizations to the card: `card_viewed` and `contact_read`. A view by an organization that has no invitation relation with the candidate has `organization` null; a contact read always names the organization. The entries carry no query or ranking. Its storage comes with the search and contact-read tasks, so the operation is contract-only.
|
||||
|
||||
Open questions for the product owner and the lawyer:
|
||||
|
||||
- The search status values: the contract has `looking` and `not_looking`. Whether the PRD needs a third status such as "open to offers" is not decided; a value is an additive change.
|
||||
- Whether `looking` gates the appearance of a published card in search (an organization sees only candidates who are searching) or is only a label. This decides the meaning of a lapse for visibility and belongs to the search contract.
|
||||
- The set of card fields. The six values are a proposal that matches the profile; the PRD card (FR11) may add, split, or drop some, for example a generalized employer industry and size instead of employers, and each is an additive contract change.
|
||||
- Whether publishing needs a minimum: at least one confirmed category, or a saved profile. The contract only requires one card field and an active C2.
|
||||
- Whether narrowing the published fields, not only closing the publication or hiding an organization, must revoke the contact grants. The invitation contract says any visibility change after a grant revokes it; this contract revokes on closing and hiding only.
|
||||
- How a candidate finds an organization to hide before any invitation. The contract hides by identifier and answers 404 for an organization the candidate cannot see, so hiding the current employer in advance needs an organization lookup for candidates (by name or domain), which must itself be safe against enumeration (a minimum query length, a rate limit, public data only). Without it, hiding works only for organizations that have written to the candidate.
|
||||
- Whether the candidate should learn the name of an organization that viewed the card without an invitation (`CardAccess.organization`), and how long accesses are kept.
|
||||
- The limit of hidden organizations (1000 now) and the retention of the settings and their history together with the consent evidence (152-FZ, PRD 7.3). The history references the account with `ON DELETE CASCADE`, guarded by two triggers: UPDATE is always refused, and DELETE (and the deletion of the account) is refused while the account is verified, the same condition as the consent ledger; the unverified account cleanup removes the history of an account it deletes, and the account deletion procedure extends the condition.
|
||||
- Free text in the card (stack tags, soft skills, location) is guarded only by `CardTextLooksLikeContact`, which errs on the side of dropping (Socket.io is dropped, a bare obfuscation can still slip through); the residual risk still requires a closed taxonomy in the card builder instead of free text.
|
||||
- Whether C2 is a consent to the distribution of personal data under article 10.1 of 152-FZ and needs its own field scope (see Consents); the history keeps the fields and times in the meantime.
|
||||
- Whether a new C2 text version requires the candidate to consent again for an existing publication. Now a publication stays effective while its C2 record is unrevoked, so a newer text version that the candidate has not accepted does not close it.
|
||||
- Quasi-identifiers and k-anonymity of the card: a rare combination of location, stack, and experience can identify a candidate even without a name. The generalization of rare features and a minimum group size are acceptance criteria for the card builder; the contract here only fixes the closed set of fields, the confirmed-values-only rule, and the dropping of free text that looks like a contact.
|
||||
- Retention and the right to erasure for the settings history. The hide and unhide records are sensitive (they say which employer a candidate avoids). The history is kept like the consent evidence and is not deletable while the account is confirmed; whether a candidate can erase it, when, and how this meets the three-year consent retention (PRD 7.3) is an open legal question. The account deletion procedure extends the delete condition of the table.
|
||||
|
||||
No new problem code is added. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation`, and `TestPrivacyAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/privacy-contract.test.ts` pins the generated Zod rules, the absence of a consent, a time, a contact, or a salary in the request and card types, and the absence of settings in the organization, invitation, need, profile, and consent files.
|
||||
|
||||
### Skill evidence
|
||||
|
||||
The tag `evidence` describes the facts that confirmed assessments leave about a candidate's skills (FR06 in the PRD). It has two read operations; the logic behind them is implemented (see [architecture](../docs/en/ARCHITECTURE.md#skill-evidence)).
|
||||
|
||||
| Method and path | operationId | Protection | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/evidence` | `ListMyEvidence` | session | 200 `EvidenceFactList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` |
|
||||
| `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence` | `GetOrganizationCandidateEvidence` | session | 200 `OrganizationEvidence`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
|
||||
|
||||
Each operation also declares the problem response `default`. No new problem code is added.
|
||||
|
||||
- One event is one fact. `EvidenceFact` is a source event; `skills` are the tags of that event (a non-empty set), so a second tag never makes a second fact. `source` names the event and the immutable result (`event_id` and `result_id`, equal for an assessment because a result is keyed by its attempt; the candidate opens it at `GetMyAssessmentResult`).
|
||||
- A claim is not a measurement. `kind` is `claim` (trust 0) or `measurement` (trust 1 to 3). `EvidenceTrustLevel` is an integer from 0 to 3; an online assessment without a reliable confirmation of the identity is trust 1, and repetition never raises it. Only measurements from assessments are produced today.
|
||||
- What a fact says is `result`: the grade that was passed, the `basis` (`synthetic_demo`), and the `calibration_status` (`uncalibrated`), so the candidate never reads a demonstration category as a validated measurement. The organization projection and the preview carry both labels as well. A fact has no score, answer, item, failed attempt, or anti-cheat datum, and a failed attempt, a result without a reviewed category source, and a `demo_express` run produce no fact.
|
||||
- `ListMyEvidence` lists only the caller's facts, newest event first, hidden facts included (`visibility` `hidden`), with the shared `limit` (1 to 100, default 20) and an opaque `cursor` bound to the candidate. A malformed or foreign cursor and a limit out of range answer 400; an employer account answers 403.
|
||||
- `GetOrganizationCandidateEvidence` is a section of the anonymous card. It answers only while `GetOrganizationCandidateCard` would answer for the same handle and the card shows at least one category; every other case (unknown handle, handle of another organization, closed or revoked publication, hidden organization, minimum cohort, card without categories) is the same 404, so the answer reveals nothing the card does not. For each category of the card it returns one `OrganizationEvidenceFact`: the earliest visible assessment that passed exactly the confirmed grade, with only `skill`, `grade`, `trust`, `observed_year` (the year, UTC), and `basis` and `calibration_status` (`synthetic_demo`, `uncalibrated`; the same for every candidate, so they add no fingerprint and say the fact is a demonstration). A lower grade, a retake, the other tags, the source, the basis, the month, and every identifier stay with the candidate; at most nine facts, ordered by skill, and a hidden fact is absent. No key joins the answer to a person, but it is not unlinkable: with the other values of the card, the skill, grade, trust, and year can narrow a small pool, and the minimum cohort does not cover the year. The read consumes the card-view quota and appears in the access history with the field `categories`.
|
||||
- The preview. `CardPreview.evidence` is the same section computed for the candidate (`OrganizationEvidence`, or null exactly when `card` is null), so the candidate sees what an organization would read with the `categories` field. It applies no organization or cohort, so an organization can receive less.
|
||||
- Closed schemas and the privacy walk. Every evidence object has `additionalProperties: false` and requires all its properties. `TestNoOrganizationOperationReachesRawAssessmentData` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and `ListMyEvidence` through all references and fail on an assessment, signal, or review schema or on a raw answer, score, or failure property.
|
||||
|
||||
Open questions: whether the C2 consent text needs a new version now that publishing `categories` also sends one supporting assessment fact (skill, grade, trust level, year) to an organization - a decision for the owner and the lawyer, and the consent texts are not changed here; whether the evidence needs its own card field instead of the `categories` field; whether the year is the right precision for an employer; an operation for the candidate to hide or show a fact (the stored visibility exists, no operation changes it); and when claims of the profile and facts from other sources join the list.
|
||||
|
||||
### Match search
|
||||
|
||||
The tag `organization` has one search operation for the organization-visible candidate bank (PRD FR09). It is implemented as a deterministic search without ML; the model, the groups, and the data it reads are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations).
|
||||
|
||||
| Method and path | operationId | Protection | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | session, CSRF, `Origin`, active owner | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` |
|
||||
|
||||
The operation changes nothing and needs no Idempotency-Key; `POST` carries the body. The 200 response also declares no 429.
|
||||
|
||||
- Access. The organization comes from the path and the active owner membership of the session account. A missing session answers 401, a candidate account, a member who is not the owner, a missing CSRF token, and a foreign `Origin` answer 403, and an unknown organization, an organization without an active membership, a need of another organization, an unknown need, or a `requirements_version` that no change of the confirmed requirements created answer 404. Hidden profiles, a revoked or missing C2 publication, the organization's own hiding, and the minimum cohort of the card are applied before any entry exists: a handle in the result is a handle that `GetOrganizationCandidateCard` opens at that moment.
|
||||
- Basis. `MatchSearchByNeed` searches the immutable `requirements_version` snapshot (not the general `version`), and its optional `filters` narrow it; `MatchSearchByBank` searches all organization-visible entries with explicit filters. The response `source` repeats the basis: the need reference, or the bank filters with every key present and null for a filter that was not sent (the stack is sorted).
|
||||
- Entries. Every entry is one candidate specialization under the organization-scoped `candidate_handle`. `main` and `near` hold confirmed categories (`near` when a required skill of the request earns less than 0.25), `unconfirmed` holds the declared specializations, sorted by Fit, then Coverage, then an internal identifier that is never returned. An unconfirmed entry has `category: null`, `strength: null`, and only `fit` and `coverage`. The groups are not one scale, and one handle can be confirmed in one specialization and unconfirmed in another.
|
||||
- Category basis. Each confirmed category of an entry carries `basis` (`synthetic_demo` for a demonstration category). The organization sees a demonstration as such, not as a standard confirmation; the field is required in `MatchCategory`.
|
||||
- Neutral and unknown values. The semantics component is the calibrated cosine of the stored vectors of the need and the card, and 0.5 with `ml_unavailable` without them; `percentile` is null with `cohort_below_30` and T is 0.5 (no comparable real cohort exists, and demonstration results never form one); domain, freshness, and responsiveness are 0.5 with their flags; competition is 0 and is neither a penalty nor an unknown; a card value that is not published is `null` in `public_context` with `not_in_public_card`.
|
||||
- A search is charged like card reads, because an entry carries card content. The whole visible bank is ranked, and each group returns at most `max_results_per_group` entries of the policy version (demo 10, so at most 30 reveals for one search, below the 50 views per day of tier E0); no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate counts as one distinct card view of the organization (the same reservation as `GetOrganizationCandidateCard`, so a candidate already viewed inside the window costs nothing again, and repeating the search or opening the card afterwards does not charge twice) and gets one `card_viewed` entry in the access history per search with the fields actually returned. When the allowance ends, the entries already paid for are returned with `truncated: true`, nothing is written for the rest, and no error and no new problem code is returned. `truncated` is also true when a group exceeded its limit and never carries a count. The response `truncated` is required.
|
||||
- No contact, candidate location, salary amount or minimum, raw answer, failed attempt, or reason for withheld data is in any entry; the explanation uses the bounded `MatchEvidenceCode` and `MatchEvidenceState` values only. A deployment whose effective policy has no `matching` section answers an internal error and never ranks with defaults.
|
||||
- `semantic_evidence` (up to 12, 6 by default) explains a need search: a requirement of the need, the closest item of the published card (`project`, `stack`, `roles`), the band `high` or `medium`, and `repository_verified`. A project is named only by its published title (the card field `projects`), never by the repository address or owner; no model text enters the explanation ([architecture](../docs/en/ARCHITECTURE.md#semantic-layer-and-explanations)).
|
||||
|
||||
Accepted residual risks: `truncated` is one bit about the size of the visible bank, and the response time grows with it; both are bounded by the group limit and carry no count. When the real comparable cohort of a category reaches the policy minimum, the percentile is still null with the reason `percentile_not_computed` and the search does not fail. A change of the visible cohort during a search repeats it up to three times; two simultaneous searches of one organization are serialized by its quota lock.
|
||||
|
||||
Open questions: the demo value 10 of `max_results_per_group` and whether the output needs paging beyond it; whether a search should charge a candidate for a summary entry at the price of a full card view; whether the grade of a need should be an implicit filter or only an explanation; whether the PRD values should keep an online Backend result (trust 0.6 times the broad relation 0.4 gives 0.24) below the near threshold 0.25 while a stated tag (0.25) reaches it, so that a candidate whose only evidence for a required technology is an assessment of the specialization is always in `near` for it; whether the `stack` filter should require every tag (as implemented) or any; and whether the demonstration relation between specializations and technologies (Backend over Go, PostgreSQL, Kafka, and Docker; DevOps over Docker) is the taxonomy the owner wants.
|
||||
|
||||
### Notifications
|
||||
|
||||
The tag `notification` describes the in-platform inbox of the current account, in the candidate cabinet and in the cabinet of one organization. It has four operations; the logic behind them is implemented, and no product module produces a real notification yet (see [architecture](../docs/en/ARCHITECTURE.md#internal-notifications)).
|
||||
|
||||
| Method and path | operationId | Protection | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/notifications` | `ListMyNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (an employer account) |
|
||||
| `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
|
||||
| `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (a candidate account) or `email_not_verified`, 404 `not_found` |
|
||||
| `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
|
||||
|
||||
Each operation also declares the problem response `default`. No new problem code is added.
|
||||
|
||||
- The inbox is the delivery state inside the platform. An item exists once the event reached the platform, whether or not an email was sent, and a failed or missing email never blocks it. A repeated delivery of the same event is the same item (`id` is the event identifier).
|
||||
- The inbox stores references, not text. `content` is resolved from the current source for the recipient on every read and is `null` when the source is gone or the recipient may not see it now (for example the candidate hid the organization); the item stays in the list, can be marked, and a client shows a generic line, never an earlier copy. `content.link_path` is a same-origin absolute path (`^/[A-Za-z0-9/_-]{0,255}$`) or `null`.
|
||||
- The recipient is the session account. The organization route also needs an active membership of any role in `org_id` and lists only the caller's items of that organization. A candidate on the organization route and an employer on the candidate route get 403 `forbidden`, and an employer with an unconfirmed email gets 403 `email_not_verified` on the organization route. A missing membership, an unknown organization, an item of another account or of another organization, and an unknown identifier get the same 404 `not_found`, so identifiers cannot be enumerated.
|
||||
- Pagination follows the shared `limit` (1-100, default 20) and `cursor`, newest delivery first with the identifier as the tie-breaker. The cursor is bound to the account and the cabinet; a cursor of another account or cabinet gets 400.
|
||||
- A mark is idempotent by its effect and needs no Idempotency-Key: the first read time is stored and every repeat returns it. It reads no source and returns no content. `kind` is `invitation_delivered` (no module produces it yet) or `synthetic` (a notice with no product meaning that exercises the path).
|
||||
- Closed schemas and checks. Every notification object has `additionalProperties: false` and all properties required. `TestNotificationOperationsFollowTheConventions` and `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) check the tag, the security of reads and marks, the statuses, no-store, the parameters, and that an item carries no text, name, or contact outside `content`.
|
||||
|
||||
### Generator checks
|
||||
|
||||
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
|
||||
|
||||
`make -C api check-toolchain` lints the fixture and runs the three generators on it; it needs the backend Go toolchain, pnpm, and uv, so pass the same `UV` override as for `make generate`.
|
||||
|
||||
| Target | Generator | Exercised conventions |
|
||||
| --- | --- | --- |
|
||||
| `make -C backend check-ogen-compat` | ogen | All of them: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Its tests check validation errors, the retry scenario, the preconditions, and the 413 body limit against the backend problem mapping |
|
||||
| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. The output is type-checked with the frontend compiler settings |
|
||||
| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. The models pass `mypy --strict` and a validation script |
|
||||
|
||||
Each target writes its output to a temporary directory and removes it.
|
||||
|
||||
Known generator limitations:
|
||||
|
||||
- Orval 8.40 writes no Zod schema for `components/responses` but imports a `<Name>Response` type for each reference. `frontend/codegen/orval.config.ts` therefore inlines response references before generation.
|
||||
- Orval passes header parameters as a typed argument only with `headers: true`. With `exactOptionalPropertyTypes`, an optional header such as `If-Match` fits `RequestInit` only when Zod emits exact optional properties, so the configuration also sets `override.zod.exactOptional`.
|
||||
- Orval generates no type for response headers, and `apiRequest` returns only the body, so a generated client cannot read `ETag` yet. The first operation with a versioned resource must expose it, for example through the response body or the mutator.
|
||||
- datamodel-code-generator 0.83.0 generates models only for schemas and query and path parameters; header parameters and response headers (Idempotency-Key, If-Match, ETag) produce no Python model.
|
||||
- Orval does not generate `additionalOperations` methods.
|
||||
- ogen writes the header name in its canonical Go form (`Etag`); HTTP header names are case-insensitive.
|
||||
- ogen requires a `SecurityHandler` as soon as the contract has security schemes and evaluates the schemes in the order of their generated type names, so renaming a scheme can change the order; `TestGeneratedServerSecurityOrder` fails if it does. Security failures reach `NewError` without a response header, so clearing the cookie on a 401 from `Logout` needs handwritten code.
|
||||
- Orval does not expose security scheme values as typed arguments, so `X-CSRF-Token` is not a generated parameter; the shared API client is planned to attach it to mutating requests. Orval also generates no type for `Set-Cookie`, which the browser handles.
|
||||
- Orval Zod schemas ignore `uniqueItems` and do not reject unknown fields of `additionalProperties: false` objects; the server stays authoritative for both.
|
||||
- ogen generates an optional nullable field as `OptNil<T>`, which tells absent (`IsSet` false), null (`IsNull`), and a value apart. An optional array that is not nullable is a plain slice instead, where nil and `[]` mean different things: an absent field decodes to nil (unchanged) and `[]` to an empty non-nil slice (delete every item), and null fails decoding. An `UpdateOrganizationNeed` handler must therefore test lists with `!= nil`, never with `len`; `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` pins this.
|
||||
- Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root.
|
||||
- The post-Orval step `frontend/codegen/mock-patterns.ts` finds the length bounds of a patterned string by its property name and pattern, so two properties with the same name and pattern must have the same bounds. The invitation terms therefore name the technologies `tech_stack` (`SkillName`, up to 100 characters) next to the questionnaire `stack` (`StackTag`, up to 50), and a package condition carries `description` rather than `value`, which the need decisions use with other bounds.
|
||||
|
||||
#### Format unions
|
||||
|
||||
- Format unions such as `ItemContent` and `AssessmentAnswer` are `oneOf` without a `discriminator` object. Redocly resolves `discriminator.mapping` values as references, and `scripts/merge-schemas.py` rewrites only `$ref`, so a mapping in a split schema file cannot resolve in the merged `components/schemas.yml`. Every variant fixes `format` with a one-value enum; ogen discriminates by that value and by the fields unique to a variant and rejects a body that matches several variants, and Orval generates a Zod union.
|
||||
- Orval names the constants of an inline property `<Schema><Property>`, so a property name that repeats another schema name collides in `index.ts` (TS2308). The union of item formats is therefore `ItemContent`, not `AssessmentItemContent`, next to the `AssessmentItem.content` property, and the parts of `Need` are `NeedRequirementSet`, `NeedReadinessReport`, and `NeedCategoryRecommendations`, not `NeedRequirements`, `NeedReadiness`, and `NeedRecommendations`. The response target of a case is `SupportResponseTarget`, not `SupportCaseResponseTarget`, next to the `SupportCase.response_target` property.
|
||||
|
||||
Generated Zod is not strict. A body that mixes the fields of two formats or carries an extra `score` or `seed` is accepted after unknown keys are silently stripped, and `uniqueItems` is not checked; only the server rejects such bodies. `frontend/src/shared/api/assessment-contract.test.ts` pins the accepted formats and that no answer or item DTO has a score, key, seed, or correctness field.
|
||||
|
||||
See the [development guide](../docs/en/DEVELOPMENT.md).
|
||||
See [DEVELOPMENT.md](../docs/en/DEVELOPMENT.md) for contract changes and [TESTING.md](../docs/en/TESTING.md) for checks.
|
||||
+44
-814
@@ -2,827 +2,57 @@
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
Общие OpenAPI-контракты для Go, frontend и ML. Сначала изменяется контракт, затем из него генерируются типы, серверный код и клиенты нужных сервисов.
|
||||
OpenAPI 3.2.0 - общий источник HTTP-контрактов. Сначала меняется спецификация, затем генерируются серверные адаптеры, клиенты и модели.
|
||||
|
||||
- `core/` - публичный API основного backend.
|
||||
- `ml/` - внутренний HTTP API ML-сервиса.
|
||||
- `runner/` - внутренний HTTP API собственного исполнителя кода.
|
||||
- `testdata/` - спецификация для проверки совместимости инструментов с OpenAPI 3.2.0.
|
||||
## Структура
|
||||
|
||||
Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`; серверный код исполнителя генерируется по `runner/codegen/`.
|
||||
| Каталог | API |
|
||||
| --- | --- |
|
||||
| [core/](core/openapi.yml) | Публичный Go API под `/api/v1` |
|
||||
| [ml/](ml/openapi.yml) | Внутренний ML API |
|
||||
| [runner/](runner/openapi.yml) | Исполнитель кода |
|
||||
| [labd/](labd/openapi.yml) | Подготовка лабораторных окружений |
|
||||
| [testdata/](testdata/openapi-3.2.0.yml) | Проверка совместимости генераторов |
|
||||
|
||||
Из корня: `make -C api check` проверяет контракты, `make generate` обновляет весь сгенерированный код.
|
||||
В каждом контракте `openapi.yml` подключает `routes/` и `components/`. Тематические схемы объединяет [merge-schemas.py](../scripts/merge-schemas.py), после чего Redocly создает `openapi.bundle.yml`. Производные файлы вручную не редактируются.
|
||||
|
||||
## Генерация
|
||||
|
||||
Команды выполняются из корня репозитория:
|
||||
|
||||
```sh
|
||||
make -C api install
|
||||
make -C api check
|
||||
make generate
|
||||
make check-generated
|
||||
```
|
||||
|
||||
`check` собирает и проверяет контракты. `generate` обновляет всех потребителей. `check-generated` ищет отличия от закоммиченного результата и сам генерацию не запускает.
|
||||
|
||||
| Потребитель | Генератор и настройки |
|
||||
| --- | --- |
|
||||
| Go backend | ogen, [backend/codegen/](../backend/codegen/) |
|
||||
| Go runner и labd | ogen, настройки в `codegen/` каждого сервиса |
|
||||
| React | Orval: клиент, query hooks, Zod-схемы и MSW; [frontend/codegen/](../frontend/codegen/) |
|
||||
| Python ML | datamodel-code-generator: Pydantic; [ml/codegen/](../ml/codegen/) |
|
||||
|
||||
`make -C api check-toolchain` проверяет используемые возможности OpenAPI 3.2 на отдельной спецификации. Это проверка текущего набора инструментов, а не обещание поддержки всех возможностей стандарта.
|
||||
|
||||
Для сравнения публичного контракта с существующим Git ref: `make -C api check-compat API_BASE_REF=<ref>`.
|
||||
|
||||
## Соглашения контракта
|
||||
|
||||
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount`, команды оценки, `CreateOrganization`, `CreateOrganizationNeed`, `CreateMySupportCase` и команды приглашений требуют Idempotency-Key, но ни одна операция пока не хранит ключи.
|
||||
- Ошибки: RFC 9457, `application/problem+json`, стабильный `code` и безопасные сообщения. Поля ответа задает схема `Problem`.
|
||||
- Сессия: HttpOnly cookie; изменяющие запросы с сессией также передают `X-CSRF-Token`. Origin должен соответствовать настройке приложения.
|
||||
- `Idempotency-Key` передается для операций, где он требуется контрактом. Повтор того же действия использует прежний ключ; другое содержимое требует нового.
|
||||
- Конкурентные изменения используют `If-Match` или `expected_version` согласно операции. При конфликте клиент перечитывает состояние и сохраняет пользовательский черновик.
|
||||
- Списки используют ограниченную cursor pagination. Идентификаторы - UUID, время - UTC date-time. Отсутствующее поле и `null` могут иметь разный смысл.
|
||||
- Коды, лимиты, обязательные заголовки и примеры берутся из конкретной операции и общих компонентов.
|
||||
|
||||
### Ошибки
|
||||
## Границы
|
||||
|
||||
Любая ошибка - problem по RFC 9457 с media type `application/problem+json` и схемой `Problem`. Обязательные поля: `type` (`urn:lincodex:problem:<code>`), `title`, `status` и `code`; необязательные: `detail`, `instance`, `trace_id` (равен заголовку ответа `X-Request-ID`) и `errors`. Клиенты принимают решения по `code`. Заголовок и описание фиксированы для каждого кода и никогда не содержат текст внутренних ошибок, stack trace, учетные данные, контакты или отправленные значения.
|
||||
Наличие операции в спецификации не доказывает готовность ее обработчика. Проверяйте реализацию в `backend/internal/adapter/primary/http/v1/` и ее тесты. Нереализованная операция может вернуть `501 not_implemented`.
|
||||
|
||||
| Код | Статус | Значение |
|
||||
| --- | --- | --- |
|
||||
| `validation_failed` | 400 | Параметры или тело не соответствуют контракту или тело нарушает доменное правило; `errors` перечисляет поля |
|
||||
| `verification_token_invalid` | 400 | Токен подтверждения email неизвестен, уже использован или заменен |
|
||||
| `verification_token_expired` | 400 | Срок действия токена подтверждения email истек |
|
||||
| `unauthenticated` | 401 | Нет действующей сессии |
|
||||
| `invalid_credentials` | 401 | Вход не удался; неизвестный email и неверный пароль не различаются |
|
||||
| `forbidden` | 403 | Вызывающему запрещена операция |
|
||||
| `email_not_verified` | 403 | Учетные данные верны, но email не подтвержден |
|
||||
| `csrf_check_failed` | 403 | Нет или неверен `X-CSRF-Token`, либо `Origin` не разрешен |
|
||||
| `not_found` | 404 | Неизвестный маршрут или объект, который не существует или недоступен |
|
||||
| `method_not_allowed` | 405 | Метод не поддерживается; см. `Allow` |
|
||||
| `idempotency_in_progress` | 409 | Запрос с тем же Idempotency-Key еще выполняется |
|
||||
| `state_conflict` | 409 | Операция недопустима в текущем состоянии ресурса |
|
||||
| `version_conflict` | 412 | If-Match или `expected_version` в теле не совпадает с текущей версией |
|
||||
| `payload_too_large` | 413 | Тело превышает лимит операции |
|
||||
| `unsupported_media_type` | 415 | Content-Type запроса не принимается |
|
||||
| `idempotency_key_reused` | 422 | Idempotency-Key уже использован с другим запросом |
|
||||
| `precondition_required` | 428 | Операция требует If-Match |
|
||||
| `rate_limited` | 429 | Слишком много запросов; см. `Retry-After` |
|
||||
| `internal` | 500 | Непредвиденная ошибка сервера |
|
||||
| `not_implemented` | 501 | Операция есть в контракте, но не реализована |
|
||||
Внутренние API ML, runner и labd не предназначены для прямого доступа из браузера. Публичный health-маршрут - `/api/v1/healthz`; служебные `/healthz`, `/readyz` и метрики описаны в руководствах сервисов.
|
||||
|
||||
Для валидации запроса выбран 400, а не 422. Сгенерированный ogen-сервер сообщает о синтаксически неверных и не прошедших проверку схемы параметрах и теле через одни и те же ошибки декодирования, а для параметров не отделяет синтаксис от нарушения схемы; единый статус упрощает обработку на клиенте. Поэтому 422 остается для повторного использования Idempotency-Key, как рекомендует черновик IETF о заголовке Idempotency-Key. Доменные правила тела, например `salary_from <= salary_to`, тоже отвечают 400 `validation_failed` с body pointer на участвующие поля. Каждый элемент `errors` содержит `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` в теле, пустая строка для всего тела, `/limit` для параметра), `code` (`required` или `invalid`; клиенты допускают новые значения) и фиксированный `message`. Pointer тела строится по правилам из раздела Pointer тела ниже. Тело, обрезанное лимитом `http.MaxBytesReader`, дает 413 `payload_too_large`.
|
||||
|
||||
`state_conflict` обозначает конфликты бизнес-состояния, например принятие уже отозванного приглашения. `idempotency_in_progress` зарезервирован для параллельных повторов; переиспользуемые ответы - `StateConflict` и `IdempotencyInProgress`.
|
||||
|
||||
Каждая операция объявляет `default: $ref: ../components/responses.yml#/Problem`; тогда ogen генерирует единый тип ошибки. Конкретный ответ (например, `PreconditionFailed`) операция добавляет, когда он нужен клиентам в сгенерированных типах. В Go API неизвестные пути под `/api`, включая пути вне `/api/v1`, отвечают 404 `not_found`, а panic в операции - 500 `internal`; в лог попадают только тип panic и stack.
|
||||
|
||||
Оба кода токена подтверждения используют 400, потому что токен - содержимое запроса, а не целевой ресурс: 404 и 410 описывают URI, 409 - состояние ресурса, а 422 зарезервирован для повторного использования Idempotency-Key. Синтаксически неверный токен не проходит проверку схемы и дает 400 `validation_failed` с pointer `/token`. `invalid_credentials` и `unauthenticated` используют 401, но означают соответственно неудачный вход и отсутствие сессии. `email_not_verified` возвращается только после совпадения пароля, поэтому раскрывает состояние подтверждения только тому, кто уже доказал знание пароля.
|
||||
|
||||
#### Pointer тела
|
||||
|
||||
Сгенерированный декодер сам путь не записывает. Ошибку каждого поля объекта он оборачивает как `decode field "<name>"` через go-faster/errors, а `problem.Responder` восстанавливает pointer по этим оберткам, читая каждое звено через типизированный `errors.Formatter`, а не через склеенный текст ошибки. Правила:
|
||||
|
||||
- Отсутствующее обязательное поле дает `required` со своим pointer на любой глубине, например `/terms/communication_method` или `/terms/salary/tax_basis`.
|
||||
- Значение, которое не декодируется, например неверный тип JSON, некорректный UUID или неоднозначное значение `oneOf`, дает `invalid` с pointer этого значения, например `/grade` для грейда без решения или `/object/id`.
|
||||
- Значение, которое декодируется, но нарушает правило схемы (длину, pattern, кратность 1000, enum), дает `invalid` с полным pointer, включая индексы массивов, например `/required_skills/2/status`; эта проверка идет после декодирования.
|
||||
- Неизвестное свойство дает `invalid` с pointer объекта, который его содержит, например `/terms/salary` для `candidate_minimum` внутри вилки; имя свойства не повторяется.
|
||||
- Ошибка внутри элемента массива при декодировании дает `invalid` с pointer массива, например `/required_skills`, потому что jx не сообщает индекс элемента.
|
||||
- Pointer на все тело `""` остается только для некорректного JSON-документа, отсутствующего тела, неизвестного свойства верхнего уровня, неизвестного или отсутствующего дискриминатора `oneOf` верхнего уровня и цепочки ошибок, которую responder не распознал: она безопасно сводится ко всему телу.
|
||||
|
||||
`responder_test.go` покрывает вложенный объект, элемент массива, поле варианта `oneOf`, поле верхнего уровня и нераспознанную цепочку; router-тесты каждого контракта закрепляют pointer через сгенерированный сервер.
|
||||
|
||||
### Повторы и Idempotency-Key
|
||||
|
||||
Изменяющая команда объявляет параметр `IdempotencyKey`. Клиент создает ключ (рекомендуется UUID v4) и передает его в заголовке `Idempotency-Key` без кавычек: 1-255 символов `A-Z a-z 0-9 . _ : -`. Сервер ограничивает ключ вызывающим и операцией и снимает отпечаток запроса по методу, пути и телу.
|
||||
|
||||
Анонимная операция сама определяет область ключа и отпечаток в своем описании; для `RegisterAccount` они описаны в разделе Identity ниже.
|
||||
|
||||
Хранятся 24 часа и воспроизводятся с теми же статусом, заголовками и телом: итоговый 2xx-результат и итоговые детерминированные бизнес-результаты 4xx, например 404 `not_found` или 409 `state_conflict`. Воспроизведение не повторяет побочный эффект.
|
||||
|
||||
Не хранятся, поэтому повтор с тем же ключом обрабатывается заново: 400 `validation_failed`, 413 и 415 для самого запроса; 401 и 403; 409 `idempotency_in_progress`; 412 `version_conflict` и 428 `precondition_required` (ничего не изменилось; прочитайте ресурс снова и повторите); 422 `idempotency_key_reused`; 429; любой 5xx.
|
||||
|
||||
Порядок проверок на сервере:
|
||||
|
||||
1. Аутентификация (401), валидация запроса (400, 413, 415) и авторизация (403). Для ключа ничего не записывается.
|
||||
2. Сохраненный или выполняющийся запрос с тем же ключом и другим отпечатком: 422 `idempotency_key_reused`. Эта проверка идет раньше проверки выполнения.
|
||||
3. Выполняющийся запрос с тем же ключом и отпечатком: 409 `idempotency_in_progress`; повторите позже.
|
||||
4. Сохраненный результат с тем же ключом и отпечатком: результат воспроизводится.
|
||||
5. If-Match (428, 412), затем сама команда; результат, который можно хранить, записывается.
|
||||
|
||||
Поскольку проверка воспроизведения идет раньше If-Match, повтор завершенного изменения воспроизводит его результат, а не падает на версии, которую само изменение и увеличило. Отсутствующий или некорректный ключ дает 400 `validation_failed` с pointer `/Idempotency-Key`. Через 24 часа ключ может быть принят как новый.
|
||||
|
||||
### Версии: ETag и If-Match
|
||||
|
||||
Ответ с версионируемым ресурсом возвращает сильный `ETag`, например `"v7"`. Операция, изменяющая такой ресурс, указывает в описании, что требует `If-Match` с этим значением. Отсутствующее значение дает 428 `precondition_required`; значение, не равное текущему ETag, дает 412 `version_conflict` без изменений. В схеме параметр необязательный, чтобы отсутствие заголовка доходило до приложения, которое отвечает 428. Слабые теги, списки и `*` не проходят валидацию и дают 400. Анкета вместо этого передает версию в теле как `expected_version`; см. раздел "Каталог и анкета" ниже.
|
||||
|
||||
### Пагинация
|
||||
|
||||
Списки используют cursor pagination: `limit` от 1 до 100 (по умолчанию 20) и непрозрачный `cursor` длиной до 512 символов `A-Z a-z 0-9 _ -`. Ответ содержит элементы в ограниченном массиве и `page` (`PageInfo`) с `has_more` и `next_cursor`, который равен null на последней странице. Некорректный cursor дает 400 `validation_failed`.
|
||||
|
||||
### Время и деньги
|
||||
|
||||
Метки времени используют схему `Timestamp`: `string`, `format: date-time`, UTC с суффиксом `Z` (RFC 3339). Серверы всегда отдают UTC. ogen генерирует `Timestamp` как именованный Go-тип поверх `time.Time`; при преобразовании к нему вызывайте `.UTC()`. Деньги - целое число полных рублей (`RubAmount`, int64) с явной базой: `SalaryRange` требует `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`) и `tax_basis` (`net` или `gross`); см. раздел Потребности ниже. Условия приглашения переиспользуют `SalaryRange` с теми же правилами.
|
||||
|
||||
### Ошибки ML-сервиса
|
||||
|
||||
ML-сервис отвечает на ошибки той же схемой `Problem`. Его перечисление `ProblemCode` сохраняет публичные коды identity, чтобы оба контракта имели одну форму, но сервис их никогда не возвращает. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, 501 и 503 (`service_unavailable`, пока модель не готова) - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback.
|
||||
|
||||
### Контракт исполнителя кода
|
||||
|
||||
`runner/openapi.yml` описывает внутренний API исполнителя кода, который вызывает только Go backend. Go-клиент генерируется ogen по `backend/codegen/ogen-code-runner.yml` в `backend/internal/adapter/secondary/code_runner/api/`; его пока не вызывает ни один usecase.
|
||||
|
||||
- Транспорт и вход. Исполнитель слушает частный интерфейс своего хоста по HTTPS (TLS 1.3). Все операции, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>`; токен - общий случайный секрет не короче 32 символов из хранилища секретов развертывания. Неверный или отсутствующий токен дает 401 `unauthenticated`. Простой HTTP разрешен только явным переключателем локального dev Compose.
|
||||
- Данные. `RunRequest` содержит только язык, исходный код, лимиты и группы тестов; у каждой группы есть метка, видимость (`public` или `hidden`), вид checker и тесты с входом и ожидаемым выводом. Полей кандидата, аккаунта, попытки, задания или компании нет; `scripts/test_runner_contract.py` проверяет это для всех схем запросов, а также `additionalProperties: false` у каждого объекта запроса.
|
||||
- Идемпотентность. `PUT /v1/runs/{run_id}` (`SubmitRun`) принимает случайный UUID от backend. Новый ID при свободном слоте запускает прогон и отвечает 202, тот же ID с тем же телом возвращает текущее состояние с 200 без повторного запуска, тот же ID с другим телом дает 422 `idempotency_key_reused`. Тела сравниваются по SHA-256 отпечатку разобранного запроса. Когда все слоты заняты или процесс останавливается, ответ - 503 `runner_busy` с `Retry-After`; ничего не сохраняется, очередь держит backend.
|
||||
- Результат. `GetRun` возвращает `state` (`running` или `finished`) и итог по каждой группе: `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` или `infrastructure_failure`, число пройденных тестов, время CPU и пиковую память. `limit` называет сработавший лимит (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Диагностика stderr есть только у публичных тестов; у скрытых тестов нет вывода программы.
|
||||
- Языки: `python3` и `go`. Go компилируется отдельной фазой со своими лимитами; ошибка компиляции дает `compile_error` без запуска тестов.
|
||||
- Checker задается для группы: `exact` (сравнение после нормализации CRLF, хвостовых пробелов строк и пустых строк в конце), `tokens` (последовательности токенов по ASCII-пробелам), `numbers` (как `tokens`, но числа равны в пределах `abs_tolerance` или `rel_tolerance`) и `custom` (`program` с языком и исходником checker семейства заданий; он работает в nsjail, читает файлы input, expected и actual и отвечает кодом выхода 0 или 1). Сервер отклоняет параметры, не подходящие виду checker.
|
||||
- Ошибки используют форму `Problem` из api/core; перечисление `ProblemCode` свое: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal` и `runner_busy`. Совпадение формы с api/core проверяет `scripts/test_runner_contract.py`.
|
||||
|
||||
### Identity: сессии, cookie и CSRF
|
||||
|
||||
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/identity/consent-texts/{purpose}` | `GetConsentText` | публичная | 200 `ConsentText` | 400 `validation_failed` |
|
||||
| `POST /api/v1/identity/registrations` | `RegisterAccount` | публичная, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | публичная | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 |
|
||||
| `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 |
|
||||
| `POST /api/v1/identity/email-verifications/code` | `ConfirmEmailByCode` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 |
|
||||
| `POST /api/v1/identity/sessions` | `Login` | публичная | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` или `csrf_check_failed`, 429 |
|
||||
| `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | сессия | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` |
|
||||
| `DELETE /api/v1/identity/sessions/current` | `Logout` | сессия и CSRF | 204, `Set-Cookie` удаляет cookie | 401 `unauthenticated` (тоже удаляет cookie), 403 `csrf_check_failed` |
|
||||
| `GET /api/v1/identity/me` | `GetCurrentAccount` | сессия | 200 `Account`, `Cache-Control: no-store` | 401 `unauthenticated` |
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`.
|
||||
|
||||
Регистрация и подтверждение:
|
||||
|
||||
- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email. Вход отвечает одинаковым 401 `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша; для неизвестного email и некорректного хеша выполняется дополнительная работа Argon2id. Верный пароль неподтвержденной учетной записи дает 403 `email_not_verified` и не создает сессию.
|
||||
- До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта.
|
||||
- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля, сценарий и первый шаг онбординга) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует прежние токены. `ConfirmEmail` требует пароль этой регистрации и проверяет его по отложенному хешу именно нажатого токена. В одной транзакции сервер проверяет текущую версию регистрации и связанную с ней запись C1, погашает токен, отмечает email подтвержденным, применяет отложенные данные токена к аккаунту, очищает поля `pending_*` и записывает ровно одно событие `identity.email_verified`. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный или устаревший токен, неверный пароль и отсутствие отложенных данных дают 400 `verification_token_invalid`; истекший токен дает 400 `verification_token_expired`. Так владелец адреса, перешедший по чужой ссылке, не принимает пароль, выбранный другим регистрантом, и наоборот. Подтверждение не создает сессию или cookie; вход доступен отдельно и принимает только пароль подтвержденной учетной записи.
|
||||
- Реализация регистрации, повторной отправки и входа. Подтвержденный адрес при регистрации: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на почту (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа. `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час, диапазон 1..10000) ограничивает регистрацию, подтверждение, повторную отправку и вход по адресу клиента, если он разрешен доверенной цепочкой. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (по умолчанию 10 в час, диапазон 1..10000) ограничивает вход по нормализованному email независимо от наличия аккаунта. `ConfirmEmail` дополнительно ограничивает каждый токен до 5 попыток в час и использует лимит клиента. Отклоненный запрос дает 429 `rate_limited` с `Retry-After`. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток, лимиты и session CSRF. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
|
||||
- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии с отложенными данными этой регистрации, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики).
|
||||
- Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля.
|
||||
- Запрос `ConfirmEmail` принимает и `token`, и выбранный при этой регистрации `password`; прежние клиенты, отправлявшие только токен, нужно обновить. Пароль обрабатывается по правилам `LoginPassword`: NFKC-нормализация и от 1 до 128 кодовых точек; blocklist регистрации повторно не применяется. `Origin` должен совпадать с `APP_PUBLIC_URL`; отсутствующий Origin, значение null или посторонний Origin дают 403 `csrf_check_failed`. Endpoint ограничивает попытки подтверждения одним токеном до 5 в час и применяет общий лимит клиента `IDENTITY_CLIENT_HOURLY_LIMIT`; отказ по лимиту дает 429 `rate_limited` с `Retry-After`.
|
||||
- Запрос `ConfirmEmailByCode` принимает `email`, `code` (ровно шесть цифр, `VerificationCode`) и `password` - пароль регистрации, которая выпустила код. Любой отказ, включая неизвестный адрес, неверный или истекший код, неверный пароль и аннулированный токен, отвечает 400 `verification_token_invalid`; некорректное тело отвечает 400 `validation_failed` с указателем `/code`, `/email` или `/password`. Пять неудачных проверок одного открытого кода аннулируют его токен, и ссылка тоже перестает работать. Код действует 30 минут или до конца срока токена, если токен заканчивается раньше. Лимит адреса общий со входом (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`), лимит клиента - `IDENTITY_CLIENT_HOURLY_LIMIT`. Успех отвечает тем же телом, что и `ConfirmEmail`, и сессию не создает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
|
||||
- Ссылка подтверждения имеет вид `<frontend origin>/verify-email#token=<token>`. Экран подтверждения во frontend пока остается заглушкой. Клиентская страница должна удалить фрагмент через `history.replaceState`, запросить явное действие пользователя и отправить токен вместе с паролем регистрации; сканер ссылок, который только открывает страницу, не расходует токен.
|
||||
- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку; после подтверждения пользователь может отдельно войти. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос.
|
||||
|
||||
Согласие C1 и аккаунт:
|
||||
|
||||
- `GetConsentText(c1)` возвращает текущий текст C1, его `text_version` и `published_at`. Регистрация передает эту версию в `consent_c1`; сервер записывает ее вместе с хешем того же сохраненного текста. Версия, которая больше не текущая, дает 400 `validation_failed` с pointer `/consent_c1/text_version`, и клиент читает текст заново. Отдельный код вызвал бы то же действие клиента, а pointer поля уже указывает причину, поэтому новый код не добавлен.
|
||||
- Неизвестные поля тела отклоняются, поэтому никакое другое согласие, включая C4, не может войти в регистрацию.
|
||||
- Пароль нормализуется в NFKC и должен содержать от 15 до 128 кодовых точек Unicode, без правил состава. Сгенерированные Zod-валидаторы считают кодовые единицы UTF-16, поэтому длину окончательно проверяет сервер.
|
||||
- У аккаунта есть `scenario` (`candidate` или `employer`) и сохраненный `onboarding_step`, который продвигает сервер; после входа клиент возвращает пользователя на этот шаг. Шаги кандидата: `candidate_consents`, `candidate_profile`, `candidate_questionnaire`, `candidate_assessment` и `completed`; у работодателя - `employer_company` и `completed`. DTO никогда не содержат хеши паролей, хеши токенов или идентификаторы сессий.
|
||||
|
||||
Сессии и CSRF:
|
||||
|
||||
- Реализованные операции сессии: Login выдает cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict`, без Domain, и с Expires/Max-Age до абсолютного срока. PostgreSQL хранит только SHA-256 хеш cookie token; GET текущей сессии возвращает аккаунт и CSRF-токен после перезагрузки. Успешный вход отзывает действующую сессию из запроса и создает новую транзакционно; войти может только подтвержденный аккаунт. Logout отзывает сессию и очищает cookie; устаревшая или отозванная cookie также очищается с ответом 401. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h` (от `1m` до `30d`), а `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h` (от `1m` до `365d`); idle timeout не может превышать absolute lifetime, некорректные значения останавливают запуск. Запросы продлевают только idle deadline.
|
||||
- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с токеном для текущей сессии из `Session.csrf_token`. Backend выводит его через domain-separated HMAC-SHA-256 из cookie token и `IDENTITY_KEY_SECRET`, сравнивает за постоянное время и не хранит в БД. Все экземпляры должны использовать один `IDENTITY_KEY_SECRET` (не менее 32 байт), одинаковый между перезапусками; смена ключа делает прежние CSRF-токены недействительными, но не отзывает сессии PostgreSQL. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`.
|
||||
- Каждая небезопасная публичная identity-операция требует ровно один заголовок `Origin`, совпадающий с `APP_PUBLIC_URL`, включая `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail` и `Login`. Небезопасные защищенные операции также требуют session-bound CSRF-токен. Проверка Origin не использует `Host` или forwarded headers. Публичные identity-операции ограничены по частоте (429 с `Retry-After`).
|
||||
- Ответы с сессией или аккаунтом несут `Cache-Control: no-store`.
|
||||
- Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию.
|
||||
|
||||
Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и как `v1.SessionSecurity` применяет текущую session boundary, закреплено тестом `TestGeneratedServerSecurityOrder`:
|
||||
|
||||
- Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом.
|
||||
- Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`.
|
||||
- Реализованное отображение: `HandleSessionCookie` аутентифицирует каждую операцию, для которой контракт требует `sessionCookie`; отсутствующая, неизвестная, истекшая, отозванная или неподтвержденная сессия отвечает 401 `unauthenticated`. Для небезопасных защищенных операций `HandleSessionCsrf` проверяет точный Origin и токен той же сессии. Без подтвержденного principal результат - 401; с ним отсутствующий или неверный Origin либо CSRF дает 403 `csrf_check_failed`. Ответ 401 от `Logout` также очищает cookie, а 403 сохраняет действующую сессию.
|
||||
|
||||
### Каталог и анкета
|
||||
|
||||
Теги `catalog` и `candidate` описывают каталог специализаций и анкету кандидата (FR03 в PRD). Каталог публичный и отвечает 501 `not_implemented`, пока не появится его обработчик. Анкета защищена: гость получает 401 `unauthenticated`, а запрос с действующей сессией проходит security boundary и после проверки запроса достигает 501 `not_implemented`. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/specializations` | `GetSpecializationCatalog` | публичная | 200 `SpecializationCatalog` | нет |
|
||||
| `GET /api/v1/me/questionnaire` | `GetMyQuestionnaire` | сессия | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/questionnaire` | `SaveMyQuestionnaire` | сессия и CSRF | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 412 `version_conflict` |
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`.
|
||||
|
||||
Каталог:
|
||||
|
||||
- Пять направлений и девять специализаций: Разработка (`backend`, `frontend`, `mobile`), Инфраструктура (`network_engineer`, `devops_sre`), Данные (`data_analyst`, `ds_ml`), Безопасность (`information_security`), Качество (`qa`). Шкала грейдов MVP: `intern`, `junior`, `middle`, `senior`; Lead и Architect появятся после MVP. Коды заданы перечислениями, поэтому новое значение - изменение контракта. Названия - русский простой текст.
|
||||
- Категория - это специализация вместе с подтвержденным грейдом. Языки заданий (`python`, `go`) и теги стека - атрибуты выбранной специализации и никогда не образуют категорию: Backend с Go - это категория `backend`. Алгоритмы - общий модуль оценки, а не специализация.
|
||||
- У каждой специализации есть `test_availability`: `status` (`available` или `in_development`), `grades` с опубликованным банком заданий и `task_languages`, которые этот банк предлагает. MVP открывает оценку только для категории с опубликованным банком. Сервер выводит значения из опубликованных банков, поэтому они меняются без изменения контракта; пример в контракте иллюстративный и ничего не говорит о развернутом банке.
|
||||
- Каталог публичный (`security: []`): он одинаков для всех, не содержит персональных данных, показывается до регистрации и может кешироваться.
|
||||
|
||||
Анкета:
|
||||
|
||||
- Кандидат берется из сессии; аккаунт работодателя получает 403 `forbidden`. Кандидат без сохраненной анкеты получает 200 с `version: 0`, без специализаций и с null в `work_context` и `updated_at`, а не 404, поэтому первое сохранение читает версию так же, как последующие.
|
||||
- У каждой выбранной специализации есть `self_assessed_grade`, `task_languages`, `stack` и `experience` в месяцах или null, если опыт не указан; `work_context` содержит только допустимые форматы работы и не содержит персональных данных. Анкета никогда не содержит подтвержденный грейд или категорию, а неизвестные поля, например `confirmed_grade`, дают 400. Самооценка - это ожидаемый грейд, который шаг онбординга `candidate_assessment` предлагает первым; она влияет на старт оценки, но не добавляет баллов, и ни самооценка, ни тег стека вроде "Senior" не присваивают категорию. Реальный профиль не виден работодателям, пока оценка не подтвердит категорию.
|
||||
- При сохранении схема допускает одну или две специализации и отклоняет неизвестные специализацию, грейд, язык заданий или формат работы. JSON Schema `uniqueItems` не умеет сравнивать элементы массива по одному полю, поэтому повтор специализации отклоняет сервер: 400 с pointer `/specializations/<index>/specialization`. Сервер также отклоняет язык заданий, которого нет в опубликованном банке специализации, с pointer на этот язык. Специализацию с тестом `in_development` выбрать можно; оценка для нее не начинается.
|
||||
- Конкурентные изменения контролирует `expected_version` в теле, а не If-Match, потому что сгенерированный клиент пока не читает заголовок `ETag`. Первое сохранение отправляет 0. Устаревшее значение дает 412 `version_conflict` - тот же статус и код, что при несовпадении If-Match, потому что действие клиента то же: прочитать анкету снова. `version_conflict` сохраняет статус 412, поэтому `state_conflict` (409) здесь не используется.
|
||||
- PUT заменяет анкету целиком, и Idempotency-Key ему не нужен. Тело, равное сохраненному состоянию, ничего не меняет, сохраняет версию и дает 200 даже со старым `expected_version`, поэтому повтор после потерянного ответа не падает с 412.
|
||||
- Порядок проверок при сохранении: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), доменные правила (400), версия (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер.
|
||||
|
||||
### Профиль кандидата
|
||||
|
||||
Тег `candidate` включает реализованные `GetMyProfile` и `SaveMyProfile` для приватного ручного профиля. Подтвержденный кандидат читает и меняет только свой профиль; работодатель получает 403, гость - 401. PUT требует CSRF-токен сессии и точный Origin. Данные, версия, подтверждения пересечений, история и переход шага сохраняются одной транзакцией. Без DATABASE_URL остается ответ 501. `confirmed_categories` только читается: одна категория на специализацию в порядке каталога из результатов оценки, с `basis` (`synthetic_demo` для демонстрационной категории), `confirmed_at` и `attempt_id`; ни один запрос ее не принимает.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/profile` | `GetMyProfile` | сессия | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/profile` | `SaveMyProfile` | сессия и CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 412 `version_conflict` |
|
||||
| `POST /api/v1/me/profile/repository-checks` | `RequestMyRepositoryChecks` | сессия и CSRF | 202 `ProfileRepositoryCheckRequest`, `Cache-Control: no-store` | 401, 403 `csrf_check_failed` или `forbidden`, 429 `rate_limited` с Retry-After |
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed` и `version_conflict`.
|
||||
|
||||
`experience_overlaps` перечисляет пересекающиеся включительные месяцы и состояние решения. Перед измененным сохранением требуется явное `confirmed_parallel_periods` с индексами и точными датами этой версии; прежнее решение переносится только при тех же индексах и датах. Сохраненный неподтвержденный overlap допускает точный no-op, но не изменение других полей без решения. История добавляется только при изменении. Успешный PUT переводит только `candidate_profile` в `candidate_questionnaire`; ранний `candidate_consents` и поздние шаги не меняются. Завершение шага согласий пока не имеет отдельной операции.
|
||||
|
||||
Состав профиля:
|
||||
|
||||
- Полное имя и контакты (`full_name`, `contacts.email`, `contacts.phone`, `contacts.telegram`), стек (`stack`, теги `StackTag`), роли (`roles`: специализация каталога и самооценка грейда), опыт работы (`experience`: записи с периодом по месяцам `YYYY-MM`, специализацией и описанием задач, а не названием должности), софт-скиллы (`soft_skills`, свободный текст) и условия (`terms`: место, готовность к переезду и минимальная зарплата с валютой, периодом и налоговой базой). Это ПДн кандидата; каждое такое поле в описании схемы помечено как персональные данные, а значения не попадают в логи, метрики, URL и события.
|
||||
- Контакты - ровно те четыре вида, которые может раскрыть согласие C4 (`ContactFieldKind`), с теми же форматами (E.164, `@` у Telegram, одна строка до 200 символов для имени), поэтому раскрытие никогда не преобразует и не отбрасывает сохраненное значение. Контактный email профиля - не логин аккаунта: сервер не отправляет на него почту и не проверяет его.
|
||||
- Допустимые форматы работы в профиле не повторяются: они остаются только в `WorkContext` анкеты.
|
||||
- Профиль закрыт: его читает только владелец, а ни одна схема организации, приглашения или потребности его не ссылает (`$ref`). Организация видит кандидата только через анонимную карточку и, после принятого приглашения, через контактное разрешение. Минимальная зарплата не раскрывается организации никогда; приглашение показывает только индикатор совместимости, который считает сервер.
|
||||
|
||||
Самооценка и подтвержденная категория:
|
||||
|
||||
- Грейд роли (`roles[].self_assessed_grade`) - заявление кандидата, то же, что анкета называет `self_assessed_grade`; он ничего не добавляет и никогда не становится подтвержденным грейдом. Подтвержденная категория - отдельный список `confirmed_categories` (специализация, грейд, время и попытка оценки, которая его подтвердила). Он только для чтения, сервер выводит его из результатов оценки, ни один запрос его не несет, а в хранилище профиля для него нет столбца. Запрос с полем `confirmed_grade`, `category` или `confirmed_categories` отклоняется как неизвестное поле.
|
||||
|
||||
Источник и подтверждение:
|
||||
|
||||
- Каждое значение несет `status` и `source`. У одиночного поля `status` равен `confirmed`, `extracted` или `unknown`; при `unknown` значение и источник равны null, а сервер ничего не подставляет по умолчанию. У элемента списка `status` равен `confirmed` или `extracted`. `source` - `origin` (`manual`; запланированы `extracted_from_resume` и `imported`, ни одна операция MVP их не создает), `trust_level`, `quote`, `extraction_version` и `confirmed_at`.
|
||||
- Каждое заявление профиля имеет `trust_level` 0, какой бы ни был источник: ограничение схемы (`minimum` и `maximum` равны 0), CHECK в базе и тип в домене. Подтверждение предложения меняет статус, а не уровень; более высокие уровни относятся к доказательствам (результату оценки, подтверждению третьей стороной), которые хранятся отдельно и не записываются в заявление.
|
||||
- Запрос несет решение по каждому значению (`value` и `status`): `confirmed` задает ручное значение или подтверждает сохраненное предложение с тем же значением (тогда источник и цитата сохраняются), `extracted` оставляет сохраненное предложение неподтвержденным и допустим только с точно тем же значением. Любое другое использование `extracted` дает 400 с pointer на этот статус, например `/stack/1/status`, поэтому форма без изменений ничего не подтверждает случайно, как и в потребностях. Источник, уровень доверия и время подтверждения клиент не отправляет.
|
||||
|
||||
Версия и повторы:
|
||||
|
||||
- Версия начинается с 0 для кандидата без сохраненного профиля; такой кандидат получает 200 со всеми полями `unknown` и пустыми списками, а не 404. `PUT` заменяет профиль целиком, а список заменяет список; поле, посланное как null, становится неизвестным и удаляется.
|
||||
- Конкурентные изменения контролирует `expected_version` в теле, как в анкете: сгенерированный клиент пока не читает `ETag`. Устаревшее значение дает 412 `version_conflict` без изменений, и клиент читает профиль заново; правка из другой вкладки не теряется молча. Тело без изменений сохраняет версию и дает 200 даже со старой версией, поэтому Idempotency-Key не нужен. Каждое сохраненное изменение увеличивает версию на единицу.
|
||||
- Порядок проверок: сессия (401), CSRF и Origin (403 `csrf_check_failed`), валидация запроса (400), сценарий аккаунта (403 `forbidden` для работодателя), версия выше текущей (412), доменные правила, зависящие только от тела (400), затем правила, зависящие от сохраненных заявлений, и версия: решение `extracted` не для сохраненного предложения при устаревшей версии дает 412 (другая вкладка могла подтвердить значение), при текущей - 400; тело без изменений - 200; любое другое изменение по устаревшей версии - 412. Версия выше текущей никогда не существовала и дает 412 даже для тела без изменений. Доменные правила, которые схема не выражает: повтор тега, навыка или специализации роли (без учета регистра для тегов и навыков), период, который кончается раньше начала или лежит в будущем, и решение `extracted` не для сохраненного предложения. Ответ 400 не повторяет присланное значение.
|
||||
|
||||
Без файла, ML и ФСП:
|
||||
|
||||
- Профиль полностью заполняется вручную. Ни одно поле не требует резюме, извлечения ML или аккаунта ФСП, а миграция и запросы не создают обязательной связи с файлом, ML или ФСП. Загрузка резюме и привязка ФСП ID - запланированные аддитивные возможности; они добавят свои поля и источники, не меняя этих.
|
||||
|
||||
Связь с анкетой:
|
||||
|
||||
- Анкета (`/me/questionnaire`) задает не более двух специализаций для оценки; профиль - то, что кандидат показывает о себе. Одноименные понятия не дублируются под разным смыслом: самооценка грейда и стек - одно и то же заявление в двух местах (в анкете для старта оценки и по специализации, в профиле для показа), сохраняются раздельно, и сервер не копирует одно в другое; общий опыт в месяцах в анкете и записи опыта в профиле - разные заявления; форматы работы живут только в анкете, а место, переезд и зарплата - только в профиле. Описания схем обеих сторон ссылаются друг на друга.
|
||||
|
||||
Хранение (миграция 00013): `candidate_profiles` (строка профиля: `user_id`, `version`, времена) и `candidate_profile_claims` (по строке на сохраненное заявление: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). Отсутствие строки значит `unknown`. Для каждого вида значения есть CHECK формата и границ контракта; `trust_level` всегда 0; в таблицах нет ни столбца файла, ни столбца ФСП, ни подтвержденного грейда. Подробности - в [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#профиль-кандидата).
|
||||
|
||||
Открытые вопросы к владельцу продукта и юристу:
|
||||
|
||||
- Виды контактов: допустимы только четыре вида C4. Нужны ли ссылки на GitHub, соцсети или сайт (PRD прячет их до принятия приглашения), и тогда это изменение контракта и в `ContactFieldKind`.
|
||||
- Основание по 152-ФЗ: какое согласие покрывает хранение профиля (C1 при регистрации или отдельное), нужны ли отдельные согласия для имени и контактов, сроки хранения и порядок удаления. Сейчас удаление аккаунта каскадно удаляет профиль, а правил хранения нет.
|
||||
- Порядок версии и доменных правил: выбрано проверять версию раньше правил, зависящих от сохраненных заявлений (устаревшая вкладка получает 412, а не 400); нужно подтверждение владельца продукта.
|
||||
- Полная замена: `PUT` удаляет сохраненные предложения импорта, которых клиент не показал и не вернул со статусом `extracted`; допустимо ли это или сервер должен сохранять непоказанные предложения.
|
||||
- Минимум для шага онбординга `candidate_profile`: текущий контракт не требует ни одного поля, поэтому любой успешный PUT завершает этот шаг, включая пустой no-op. Введение обязательных полей потребует отдельного решения владельца продукта и изменения контракта.
|
||||
- Единый источник между анкетой и профилем: оставить самооценку и стек независимыми или хранить одно заявление и показывать в обоих местах.
|
||||
- Софт-скиллы: таксономии нет, свободный текст до 10 штук по 50 символов; нужен ли справочник.
|
||||
- Опыт: названия работодателей и описания - ПДн; как анонимная карточка их обобщает (PRD: отрасль и размер), решает контракт карточки, а не этот.
|
||||
- Проверка контактов (подтверждение телефона или email профиля) не предусмотрена: контакты - заявления уровня 0.
|
||||
|
||||
`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation` и `TestProfileAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/profile-contract.test.ts` - сгенерированные правила Zod, типы запросов без подтвержденного грейда и отсутствие полей профиля в схемах организации, приглашения и потребности.
|
||||
|
||||
|
||||
Проекты: необязательный в теле `SaveMyProfile` список `projects` (до 10; отсутствие сохраняет проекты, пустой массив удаляет) с названием, описанием, тегами и адресом `https://github.com/<owner>/<repo>`; другие адреса дают 400 с указателем `/projects/<n>/repository_url`. Ответ `CandidateProfile` несет `projects[].repository_check` (`pending`, `verified`, `not_found`, `unavailable`). `RequestMyRepositoryChecks` повторяет проверки на `api.github.com` не чаще интервала стенда. Публикация проектов в карточке - отдельное поле `projects` в `CardField` (см. [архитектуру](../docs/ru/ARCHITECTURE.md#проекты-кандидата-и-репозитории-github)).
|
||||
### Оценка
|
||||
|
||||
Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | сессия | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
|
||||
| `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` или `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | сессия | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 |
|
||||
| `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 |
|
||||
| `POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs` | `CreateMyAssessmentPracticeRun` | сессия и CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 429 `rate_limited`, 503 `service_unavailable` |
|
||||
| `GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}` | `GetMyAssessmentPracticeRun` | сессия | 200 `PracticeRun`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (сеанс занят другой страницей или у попытки нет рабочего сеанса) |
|
||||
| `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 |
|
||||
| `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422 |
|
||||
| `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | сессия | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` |
|
||||
| `GET /api/v1/me/assessment-results` | `ListMyAssessmentResults` | сессия | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
|
||||
| `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | сессия | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | сессия и CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` |
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`.
|
||||
|
||||
Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Уведомление также перечисляет меры, которые страница применяет во время реальной попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения и печати текста задания, правило вставки, правило одного окна и водяной знак экрана и текста задания) и прямо говорит, что снимок экрана или фото телефоном предотвратить нельзя, а сигналы ведут только к ручной проверке; это версия 4 текста, и подтверждение более ранней версии для текущей никогда не засчитывается. Режим `demo_express` сигналы не собирает и подтверждения не требует.
|
||||
|
||||
Доступ:
|
||||
|
||||
- Кандидат берется только из сессии; ни одна операция не принимает идентификатор кандидата. Аккаунт работодателя получает 403 `forbidden`. Попытка другого кандидата дает 404 `not_found`, как и неизвестный идентификатор, поэтому идентификаторы попыток нельзя перебирать.
|
||||
- Ни одна операция не дает работодателю ответы, историю попыток или античит-сигналы. Работодатель видит текущую категорию в анонимной карточке и разрешенные доказательства навыков этой карточки ([Доказательства навыков](#доказательства-навыков)), но не результат.
|
||||
|
||||
Режимы и версии:
|
||||
|
||||
- При создании обязательно передается `kind`: `root`, `corrective` или `demo_express`. Реальная попытка использует `demo_basic` или `adaptive`; сервер выбирает режим по опубликованному банку, клиент его не передает. `demo_basic` оценивает фиксированную форму проверенных демо-заданий по их ключам относительно проходного балла версионированной базовой политики, не вычисляет оценку способности и решает за один шаг: дополнительную практику он не предлагает. `adaptive` - адаптивный тест из FR04. Кандидат может явно запросить `demo_express` - отдельный интерактивный учебный запуск на 3-5 минут без категории, целевого грейда, перцентиля, квоты реальных оценок или квалификационных данных.
|
||||
- Корректирующая реальная попытка содержит `root_attempt_id`. Сервер разрешает только строго меньший целевой грейд, который еще не проверялся в этой цепочке. Создание корневой попытки резервирует один слот квоты из трех корневых попыток за 180 дней; корректировки используют этот же слот и неизменяемый `chain_deadline` корневой попытки (72 часа от ее старта по текущей политике), но имеют собственные лимиты заданий, практики и сессий. Корректировка не списывает еще один слот, не продлевает срок и не сбрасывает таймеры 30/90 дней. Предварительный отказ в запуске корневой попытки не создает попытку и не резервирует слот. Истечение или незавершенная практика не открывают бесплатную новую цепочку, а недостаточный банк не дает дополнительную корневую квоту. `demo_express` не входит в цепочки корректировок и доступность реальных оценок.
|
||||
- Создание фиксирует `versions`: `policy_version` (номер версии политики `product`), `bank_version` и `algorithm_version`. Попытка и ее результат хранят их, поэтому результат воспроизводится по сохраненным ответам и этим версиям, а более поздняя версия его не переписывает.
|
||||
- `version` попытки растет ровно на единицу с каждым зафиксированным изменением: вердикт, явное начало сессии, истечение или автоматическое завершение. GET-операции возвращают только проекцию: они не меняют состояние, не расходуют квоту сессий и не увеличивают версию. Назревшие исходы фиксирует команда или фоновый переход.
|
||||
|
||||
Жизненный цикл попытки и команды, которые принимает каждое состояние:
|
||||
|
||||
| Состояние | Значение | Принимает |
|
||||
| --- | --- | --- |
|
||||
| `in_progress` | Идут ответы на задания; `current_item` - задание, на которое нужно ответить | ответ на `current_item` |
|
||||
| `practice_pending` | Задания пройдены; у основной практики нет готового вердикта (не отправлена, `pending` или `failed`) | решение практики, пока она `not_started` или `failed` |
|
||||
| `additional_practice_pending` | Только adaptive: завершение нашло вероятность в полосе ниже подтверждения и предложило одну дополнительную практику в той же попытке | решение дополнительной практики, пока она `not_started` или `failed`; завершение в тех же статусах отклоняет предложение |
|
||||
| `ready_to_finalize` | Все обязательные части выполнены | завершение |
|
||||
| `completed` | Решение принято; результат доступен | только повтор завершения |
|
||||
| `expired` | Лимит времени или сессий истек раньше, чем кандидат закончил; результат не подтверждает грейд | ничего |
|
||||
| `insufficient_bank` | Банк не смог обеспечить покрытие в пределах лимита; результат не подтверждает грейд | ничего |
|
||||
|
||||
- Дополнительная практика (FR04 в PRD): при 0.50 <= P_G < 0.80 в демо-политике первое завершение adaptive-попытки ничего не решает. Оно добавляет в `practices` практику вида `additional`, переводит попытку в `additional_practice_pending` и возвращает попытку. Практика продолжает ту же попытку, сохраняет ее лимиты времени и сессий и не расходует новую попытку. Следующее завершение после ее вердикта принимает решение; если P_G остается ниже 0.80, итог `not_confirmed`. Завершение без отправки практики отклоняет предложение с тем же итогом. `practices` - список с полем `kind`, а не еще одно nullable-поле, поэтому новые виды практики добавляются без ломающих изменений.
|
||||
- Поэтому завершение всегда отвечает `AssessmentAttempt`, а не результатом и не `oneOf` из двух схем. Когда состояние `completed`, клиент читает `GetMyAssessmentResult`. Один тип ответа делает сгенерированные клиенты однозначными и оставляет место для незавершающих решений без ломающих изменений.
|
||||
- Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. После простоя кандидат явно вызывает `StartMyAssessmentAttemptSession` с последним `expected_version`; следующая сессия начинается только если позволяют квота и срок. Вызов во время активной сессии ничего не меняет. Начало сессии не продлевает `expires_at` или `chain_deadline`.
|
||||
- При достижении лимитов практика, уже имеющая статус `pending`, сначала оценивается. Затем команда или фоновый переход завершает `ready_to_finalize` как `completed`, отклоняет неотправленную дополнительную практику (`completed`, `not_confirmed`) или переводит `in_progress` и `practice_pending` в `expired`. GET не фиксирует эти переходы. `GetMyAssessmentResult` отвечает 409, пока назревший переход не сохранен.
|
||||
- Недостаточный банк - отдельное состояние в двух местах. До старта корневой попытки `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или достаточного числа невиденных семейств, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict`, не создавая попытку и не резервируя корневой слот. Корректировка также отклоняется, если срок цепочки истек или безопасного банка недостаточно; новая цепочка не создается. Во время существующей попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств.
|
||||
- Подтвержденный грейд. `confirmed_grade` и `confirmed_basis` каждой специализации анкеты читаются из текущей категории вместе, в одном снимке. `confirmed_basis` равен `synthetic_demo` для демонстрационного грейда и null ровно тогда, когда грейд не подтвержден. Попытка напрямую их не задает: меняет их только повышение категории.
|
||||
- Новый код проблемы не добавлен, поэтому создание попытки получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может.
|
||||
- Доступность показывает лимиты каждого грейда до старта: `time_limit_seconds`, `max_sessions`, `max_items` и `practice_required`; null, если значение неизвестно.
|
||||
- Корневая квота и таймеры повторов разделены. Только запуск корневой попытки резервирует один из трех слотов на 180 дней; корректировки этой цепочки не резервируют дополнительные слоты. `insufficient_bank` или недоступность песочницы не создают новую попытку и не открывают бесплатную цепочку. После неудачи, включая первый тест, строго меньший грейд можно проверить в той же цепочке; корректировки не сбрасывают 30-дневный таймер повтора того же грейда или 90-дневный таймер повышения.
|
||||
|
||||
Задания и ответы:
|
||||
|
||||
- У задания есть `id` (экземпляр), `sequence`, `prompt` простым текстом и `content` (`ItemContent`) в одном из форматов `choice`, `number`, `string`, `order`, `find_error`, `configuration` и `practice`. Оно никогда не содержит ключ ответа, правильный вариант, балл, идентификатор семейства или варианта, seed или скрытую проверку, а посевные задания выглядят так же, как оцениваемые. `multiple`, `max_selections` и `max_length` - свойства формата или семейства заданий и никогда не выводятся из ключа. Вариант фиксируется при первой выдаче, поэтому перезагрузка, повтор запроса и возобновление сессии возвращают тот же экземпляр.
|
||||
- Водяной знак. Реальная попытка (`root` или `corrective`) несет `watermark.code` - ключевой псевдоним попытки вроде `7K3QD-9XM2T`, который клиент показывает вместе со временем бледной плиткой поверх экрана задания; у попытки `demo_express` поля нет. `prompt` реальной попытки также несет невидимую метку и взаимозаменяемые формулировки, выбранные тем же секретом сервера; они не меняют ни смысл, ни эталонный ответ, а клиент держит невидимые символы (пробел нулевой ширины, не-соединитель, соединитель, соединитель слов) вне дерева доступности. Ни код, ни метка не называют кандидата, и ни одна операция не отдает их работодателю. См. [Водяной знак текста задания](../docs/ru/ARCHITECTURE.md#водяной-знак-текста-задания).
|
||||
- Одно открытое окно. Реальная попытка допускает одну открытую страницу за раз. Страница при загрузке создает случайный идентификатор и отправляет его как `X-Attempt-Client` (от 16 до 64 символов `A-Za-z0-9_-`) в `HoldMyAssessmentWorkSession`, который занимает рабочий сеанс на 120 секунд и просит страницу продлевать его раз в 15 секунд, и в `ReleaseMyAssessmentWorkSession` при закрытии. `StartMyAssessmentAttemptSession` и `SubmitMyAssessmentAnswer` принимают тот же заголовок как необязательный параметр; пока сеанс занят другой страницей, запрос от другой страницы или без заголовка получает 409 `state_conflict` и ничего не меняет, а этот отказ не сохраняется под Idempotency-Key. Попытка, которую никто не держит, освобожденное занятие и переставшее продлеваться пускают любую страницу. Это правило "одна страница за раз", а не граница безопасности, и оно отделено от `sessions` (`used`, `max`, `idle_timeout_seconds`), которые считают последовательные рабочие сеансы. Сервер хранит только ключевые отпечатки идентификатора страницы и User-Agent, привязанные к попытке. Новый код ошибки не добавлялся, поэтому страница читает 409 на этих операциях как "открыто в другом окне".
|
||||
- Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным.
|
||||
- Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается.
|
||||
- Отладочные прогоны (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) исполняют решение на публичных примерах и до десяти тестах кандидата, пока практика - текущий элемент. Они никогда не запускают, не показывают и не оценивают скрытые проверки и не меняют ни состояние практики, ни вердикт, ни версию попытки. Прогон ставится в очередь и читается по своему идентификатору; повтор с тем же Idempotency-Key и телом возвращает сохраненный прогон. Лимит на кандидата и один незавершенный прогон на практику отвечают 429 `rate_limited` с `Retry-After`. Очередь песочницы вмещает один выполняемый и десять ожидающих прогонов и решений вместе; когда она заполнена, прогон получает 503 `service_unavailable` с `Retry-After`, а финальное решение оставляет практику в `failed` с `sandbox_busy`, что ничего не расходует. Без настроенной песочницы операция отвечает 503 `service_unavailable` без `Retry-After`. Отказ ничего не сохраняет.
|
||||
- Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`.
|
||||
- Попытка бывает без практики только в `demo_basic`, пока кодовая практика выключена до проверки изоляции песочницы; результат тогда содержит ограничение `practice_not_included`.
|
||||
|
||||
Команды, повторы и версии:
|
||||
|
||||
- Создание, начало или возобновление сессии, ответ и завершение требуют Idempotency-Key с 24-часовым повтором, описанным выше, поэтому повтор команды возвращает тот же исход. Начало сессии, ответ и завершение также передают `expected_version` - прочитанную клиентом `version` попытки. У создания нет версии для сравнения, оно опирается на ключ; единственную активную реальную попытку по специализации обеспечивает состояние.
|
||||
- Каждое задание принимает один ответ. Повторная отправка сохраненного ответа, даже с новым ключом или старым `expected_version`, ничего не сохраняет, не меняет версию и дает 200 с текущей попыткой. Равенство определено для каждого формата: множества для `option_ids` и `line_numbers`, точная последовательность для `element_ids`, числовое равенство для `number`, совпадение текста без нормализации для `text` и `config`, тот же язык и совпадающий исходный код для практики. Другой ответ на уже отвеченное задание дает 409 `state_conflict` при текущей версии; при устаревшей версии ее проверка идет раньше и дает 412.
|
||||
- Исключение: практика, последний вердикт которой `failed`, не подпадает под правило повтора. Отправка того же или другого решения с текущей версией снова ставит его в очередь и увеличивает версию.
|
||||
- Завершение попытки в `completed` дает 200 с этой попыткой, поэтому результат вычисляется один раз. Повтор завершения, которое предложило дополнительную практику, с новым ключом несет старую версию и получает 412, поэтому он не может случайно отклонить предложение.
|
||||
- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Так сохраняется правило репозитория и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: рабочая сессия закончилась, задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Коды ведут к разным действиям клиента.
|
||||
- Преждевременное завершение дает 409 `state_conflict` без перечня незавершенных заданий, потому что `Problem` не допускает дополнительных полей. Клиент берет их из попытки: `state`, `progress`, `current_item` и `practices`.
|
||||
- Порядок проверок команды: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), принадлежность попытки (404), версия попытки (412, если передана), переходы по сроку или лимиту сессий, затем состояние команды (409 `state_conflict`) и доменные правила (400 с pointer вроде `/answer/option_ids/0`). Команда начала сессии возвращает обновленную попытку, если она зафиксировала наступивший терминальный переход. По соглашению об Idempotency-Key сохраненные 404 и 409 повторяются под ключом; 400, 412, 429 и 5xx не сохраняются. Создание и ответы ограничены по частоте (429 с `Retry-After`), что ограничивает и нагрузку на песочницу. `TestAssessmentSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер.
|
||||
|
||||
Результат:
|
||||
|
||||
- `GetMyAssessmentResult` отвечает для терминальной попытки и дает 409 `state_conflict` для активной, включая `additional_practice_pending`. `outcome` - это `confirmed`, `not_confirmed` или `not_determined` с `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). Результат никогда не понижает подтвержденный грейд: если попытка ничего не подтвердила, действует `previous_confirmed_grade`.
|
||||
- В ответах попытки и результата есть дискриминатор `kind`: `root`, `corrective` или `demo_express`. Реальный результат всегда содержит пару полей цепочки корректировок: у корневой попытки оба поля null, у корректирующей оба заполнены. Для `demo_express` используется отдельная учебная схема с кратким резюме и `demonstration_only`: категория, целевой и подтвержденный грейды, сила, неопределенность и балл равны null, списки практик, пробелов и следующих шагов пусты. Этот режим не создает квалификационных данных и не виден работодателю.
|
||||
- `calibration_status` и `limitations` описывают метод. Поля, которые метод не вычисляет, равны null, а не нулю: у `demo_basic` null в `uncertainty` и `strength`, у `adaptive` - null в `basic_score`. `uncertainty` содержит `theta`, `standard_error`, `interval_95` и `p_grade`. `practices` перечисляет вердикты по видам. `durations` - отдельная метка, которая не входит в решение.
|
||||
- `next_steps` приходят с сервера: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (команда запланирована) и `take_higher_grade`. Первое подтверждение - не повышение, поэтому `take_higher_grade` после него имеет null в `available_at`; после повышения следующее ждет 90-дневный интервал повышения.
|
||||
- Результат никогда не содержит ответы, правильность отдельных заданий, ключи, seed, скрытые проверки или античит-сигналы.
|
||||
- Категория по результату `demo_basic`. Результат реальной попытки содержит `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), грейд, действовавший до попытки и после нее, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`) и `calibration_status`. Порог берется из принятой версии политики, закрепленной за попыткой: достижение порога засчитывается, параметр запроса его не задает. Категория присваивается, только если включен `ASSESSMENT_DEMO_CATEGORIES_ENABLED`, версия политики является полной демонстрационной политикой с `demo_basic` (порог - ее собственный `basic_pass_mark_bp`), а для открытия, манифеста и версии политики есть аттестация оператора; иначе `status` равен `not_eligible`, `confirmed_grade` равен null, хотя `outcome` может быть `confirmed`. `confirmed_grade` заполнен, только когда подтверждение принято проверенным источником (`assigned` или `unchanged`). Неудача, равный или более низкий грейд не понижают и не меняют текущую категорию. `demo_express` никогда не получает `category_decision` и не создает категорию. Результат, сохраненный до появления решений о категориях, не содержит `category_decision`: его текущий грейд не восстанавливается задним числом.
|
||||
- `GET /api/v1/me/assessment-results` возвращает историю только самого кандидата: завершенные `root` и `corrective` результаты от новых к старым по `decided_at` и `attempt_id`. Курсор непрозрачен, привязан к кандидату и содержит только символы `[A-Za-z0-9_-]`; чужой, измененный или некорректный курсор дает 400 `validation_failed` с pointer `/cursor`. Аккаунт работодателя получает 403. Смена текущей политики, банка или категории не меняет ни одну сохраненную запись. Работодатель получает только текущую категорию (специализация, грейд, грубая сила `standard` и основание `basis`) через анонимную карточку, если кандидат опубликовал поле `categories`; ни попытки, ни баллы, ни версии, ни причины неподтверждения в этой проекции нет.
|
||||
|
||||
Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; серверные сигналы античит-слоя (время ответа, параллельные сессии, смена адреса); сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD).
|
||||
|
||||
### Потребности
|
||||
|
||||
Тег `need` описывает потребности организации в найме (FR08 в PRD, с версиями из FR10): требования с состоянием подтверждения и происхождением, неизменяемые версии, готовность и рекомендации категорий. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/organizations/{org_id}/needs` | `ListOrganizationNeeds` | сессия | 200 `NeedList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `POST /api/v1/organizations/{org_id}/needs` | `CreateOrganizationNeed` | сессия и CSRF, Idempotency-Key | 201 `Need`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 404, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `GET /api/v1/organizations/{org_id}/needs/{need_id}` | `GetOrganizationNeed` | сессия | 200 `Need`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `PATCH /api/v1/organizations/{org_id}/needs/{need_id}` | `UpdateOrganizationNeed` | сессия и CSRF | 200 `Need`, `Cache-Control: no-store` | 400, 401, 403, 404, 412 `version_conflict`, 429 |
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`. Некорректные `org_id` или `need_id` дают 400 с pointer на параметр пути.
|
||||
|
||||
Доступ:
|
||||
|
||||
- `org_id` в пути - единственный источник организации, и сервер сверяет его с действующим членством аккаунта сессии; ни один запрос не содержит поля организации, членства или роли. Организации и членства принадлежат контракту организации, который переиспользует тот же параметр пути `parameters.yml#/OrganizationId`.
|
||||
- Аккаунт без действующего членства в `org_id`, неизвестная организация, неизвестная потребность и потребность другой организации одинаково дают 404 `not_found`, поэтому идентификаторы нельзя перебрать. Аккаунт кандидата получает 403 `forbidden`, как и участник, чья роль не разрешает операцию.
|
||||
- В MVP с потребностями работает только владелец организации. Остальные роли матрицы FR07 в PRD (рекрутер, нанимающий менеджер и техэксперт для назначенных потребностей) запланированы и не меняют ни одного поля контракта.
|
||||
|
||||
Поля и происхождение:
|
||||
|
||||
- `requirements` (`NeedRequirementSet`) содержит `specialization`, `grade`, `required_skills`, `desired_skills`, `tasks`, `domain`, `work_formats`, `location` и `salary`. Поле в ответе - это `{status, value, source}`; у элемента списка свои `status` и `source`.
|
||||
- `status` - `confirmed` (участник ввел или подтвердил значение), `extracted` (предложение, ожидающее подтверждения) или `unknown` (значения нет). У неизвестного поля `value` и `source` равны null; сервер никогда не заполняет его значением по умолчанию или догадкой, например Senior, remote или нулевой зарплатой. Только подтвержденные значения влияют на готовность, рекомендации, поиск и приглашения.
|
||||
- `source` содержит `origin` (`manual`, `extracted_from_text` или запланированный `imported`), `quote` (точный фрагмент до 300 знаков или null), `extracted_in_version` и `extraction_version`. Цитата - фрагмент `source_text` версии `extracted_in_version`, а не обязательно текущего текста: подтвержденное значение сохраняет цитату после изменения текста. Подтверждение предложения сохраняет его происхождение; изменение значения делает его `manual`.
|
||||
- У навыка есть `taxonomy_code`. Он равен null для навыка, которого нет в таксономии платформы: название остается как указано, код не угадывается, а рекомендации считают навык непокрытым.
|
||||
- При наличии `source_text` сервер до ответа извлекает предложения детерминированными правилами и словарем, поэтому потребности работают при выключенном ML. ML-предложения с цитатами запланированы как асинхронное дополнение, которое создает новую версию и никогда не перезаписывает подтвержденное значение.
|
||||
- Текст хранится как написан и может содержать дискриминирующие требования по защищенным признакам; извлечение никогда не превращает их в поле потребности. Поле того, чего не должно быть у кандидата, с проверкой по ст. 64 ТК РФ отложено до реализации проверки требований и добавится без ломающих изменений.
|
||||
|
||||
Запросы, подтверждение и изменения:
|
||||
|
||||
- Каждое поле требования в запросе - это решение `{value, status}` (`NeedSpecializationInput`, `NeedGradeInput`, `NeedDomainInput`, `NeedWorkFormatsInput`, `NeedLocationInput`, `NeedSalaryInput`), а каждый элемент списка - `{name или text, status}`. `status` - `confirmed` или `extracted`. Голое значение не проходит валидацию, поэтому подтверждение всегда явное.
|
||||
- `confirmed` с сохраненным предложенным значением подтверждает его и сохраняет происхождение; `confirmed` с другим значением задает подтвержденное ручное значение. `extracted` оставляет сохраненное предложение открытым и допустим только с точно тем же предложенным значением; любое другое значение, а также поле или элемент без предложения дают 400 с pointer на этот статус, например `/grade/status` или `/required_skills/2/status`. Поэтому клиент, отправивший форму без изменений, ничего не подтверждает случайно: каждое предложение он отправляет с `extracted` или не отправляет поле.
|
||||
- Потребности никогда не нужна вакансия: обязателен только `title`, а `vacancy_id` необязателен и допускает null. Пока вакансий нет в контракте, любой идентификатор вакансии дает 400 с pointer `/vacancy_id`.
|
||||
- При создании каждое решение должно быть `confirmed`, потому что у новой потребности нет сохраненных предложений. Отсутствующее поле извлекается из `source_text` или остается неизвестным. Nullable-поле, переданное как null, остается неизвестным, а пустой список навыков или задач остается пустым; ни то ни другое не извлекается. Пустое значение `work_formats` не проходит `minItems`.
|
||||
- `UpdateOrganizationNeed` использует явную замену полей в `application/json`, а не JSON Merge Patch (RFC 7396): переданное поле заменяется целиком, отсутствующее не меняется, решения и списки не сливаются, а сохраненный элемент, которого нет в переданном списке, удаляется. Null удаляет nullable-поле (оно становится `unknown`, а `vacancy_id` отвязывается); пустой список навыков или задач удаляет все элементы; список, переданный как null, дает 400. ogen генерирует одно необязательное или необязательное nullable значение на решение (`OptNilNeedGradeInput`, `OptNilNeedSalaryInput`).
|
||||
- Другой `source_text` запускает повторное извлечение. Новые предложения заменяют только значения и элементы со статусом `extracted` в полях, не названных в теле; подтвержденные значения не перезаписываются, предложенный навык с названием, которое уже есть в одном из списков навыков, пропускается, а удаленное участником предложение для этой потребности больше не предлагается.
|
||||
- Сервер также отклоняет повтор навыка или задачи и навык в обоих списках - 400 с pointer на более поздний элемент, например `/required_skills/1/name`.
|
||||
|
||||
Версии и конкурентность:
|
||||
|
||||
- `version` начинается с 1 и растет ровно на единицу с каждым зафиксированным изменением, включая серверные. Каждая версия - неизменяемый снимок. GET всегда возвращает последнюю версию.
|
||||
- `requirements_version` - версия, в которой подтвержденные требования менялись последний раз. Подтверждение, изменение или удаление требования делает ее равной новой `version`; изменение названия, привязки вакансии, текста или только предложений ее сохраняет и не обесценивает ни рекомендации, ни результаты поиска. Запуски поиска, снимки подборки (FR10) и приглашения ссылаются на `(need_id, requirements_version)`, и новый снимок подборки нужен только при новой `requirements_version`. Чтение и сравнение прежних версий запланированы отдельными операциями, которые возвращают `NeedRequirementSet` для версии; в `Need` они ничего не добавляют.
|
||||
- Изменение передает `expected_version` - прочитанную клиентом версию - в теле по той же причине, что и анкета: сгенерированный клиент пока не читает `ETag`. Устаревшее значение дает 412 `version_conflict` и ничего не меняет; правило репозитория сохраняет 412 и для If-Match, и для версии в теле. Тело, которое ничего не меняет, дает 200 с текущей потребностью даже со старой версией, поэтому PATCH не нужен Idempotency-Key. POST требует его с повтором в течение 24 часов; сохраняется только 201.
|
||||
|
||||
Готовность:
|
||||
|
||||
- `readiness.missing_fields` перечисляет каждое критичное поле без подтвержденного значения: `specialization`, `grade`, `required_skills` (хотя бы один подтвержденный навык), `work_formats`, `salary` и `location`, если подтвержденные форматы включают `office` или `hybrid`. У каждого элемента есть `reason` (`unknown` или `unconfirmed`) и конкретный вопрос `question` на русском.
|
||||
- Неполная потребность сохраняется (201 или 200), а не отклоняется. `Problem` не допускает полей расширения, поэтому недостающие поля находятся в ресурсе, а не в problem. Каждая следующая операция, например поиск или приглашение, сама указывает, какая готовность ей нужна.
|
||||
|
||||
Зарплата:
|
||||
|
||||
- `SalaryRange` `[A; B]` содержит `salary_from` и `salary_to` (`RubAmount`, целые рубли), `currency` (только `RUB`), `period` (только `month`) и `tax_basis` (`net` или `gross`); все поля обязательны. Запрос передает ее как `salary: {value, status}`, поэтому ее pointer начинаются с `/salary/value`.
|
||||
- Схема требует положительных границ, кратных 1000, до 100000000 и отклоняет другую валюту, период или базу, например с `/salary/value/tax_basis`. Отсутствующее поле вложенной вилки дает `required` со своим pointer, например `/salary/value/tax_basis`.
|
||||
- Межполевые правила FR13 в PRD сервер проверяет в целочисленной арифметике: `A < B` и ширина `(B - A) / ((A + B) / 2)` от 10% до 40% включительно, то есть `20 * (B - A) >= A + B` и `5 * (B - A) <= A + B`. Нарушение, включая равные границы, дает 400 с pointer `/salary/value/salary_to`. `[95000; 105000]` (ровно 10%) и `[80000; 120000]` (ровно 40%) принимаются. FR13 применяет одни правила к вилке потребности и приглашения, и `docs/*/ARCHITECTURE.md` теперь указывает их для приглашений вместо `0 < salary_from <= salary_to`.
|
||||
- Ограничение против подбора скрытых минимумов (FR13, применение запланировано): задание подтвержденной вилки при создании или изменении учитывается в счетчике, общем для всей организации, всех участников и всех потребностей, поэтому новая потребность его не обнуляет. Не больше трех заданий вилки в сутки; сверх лимита сервер отвечает 429 с Retry-After и ничего не меняет. После пяти заданий за семь дней денежная компонента получает статус `withheld` на семь дней. Повторные изменения вилки также питают приватные сигналы риска организации.
|
||||
|
||||
Рекомендации:
|
||||
|
||||
- `recommendations` вычисляет сервер по подтвержденным требованиям версии `requirements_version` с версионируемой политикой (`policy_version`, `algorithm_version`, `computed_at`). `status` - `computed`, `pending` или `not_available` без подтвержденного навыка. Сервер может пересчитать их для той же `requirements_version` при новой политике или изменившемся пуле кандидатов без новой версии потребности; тогда меняются `computed_at` и `policy_version`.
|
||||
- У каждой категории (`specialization` и `grade`) есть `score`, `skill_overlap` (взвешенная доля с весом 2 для обязательных и 1 для желательных навыков, покрытые и непокрытые навыки), `money` и `supply` диапазоном: `fewer_than_5`, `from_5_to_29`, `30_or_more`. Порядок списка задает ранжирование.
|
||||
- `money.status` - `computed`, `insufficient_data` (меньше пяти кандидатов с известным сопоставимым минимумом), `no_salary` или `withheld`; последние три используют нейтральное 0,5 и null в доле. `money.share` округляется вниз до четверти (0, 0.25, 0.5, 0.75, 1): каждая проба новой верхней границы говорит не больше того, какая четверть группы ее принимает, а в наименьшей допустимой группе из пяти один минимум часто не сдвигает значение; при этом доля по-прежнему отличает вилку, которую принимает большинство, от той, которую принимают немногие.
|
||||
- `score` равен `0.5 * Overlap + 0.3 * Money + 0.2 * Supply` с округлением половины вверх до двух знаков и вычисляется по опубликованным компонентам: точному покрытию, доле с округлением до четверти или нейтральному 0,5 и `Supply = min(1, active / 30)`. Он равен null, когда `supply` - `fewer_than_5`. Ниже пяти ранжирование использует Supply только с точностью диапазона: каждая группа меньше пяти кандидатов входит в него с Supply 0, поэтому ни балл, ни порядок не раскрывают точный размер группы меньше пяти, что запрещает FR08. Для пяти и более кандидатов используется точный Supply, поэтому фикстура рекомендаций (Overlap 1, Money 0,5, 15 активных кандидатов) дает `score` 0.75.
|
||||
- Отступление от формулы PRD: в балле и ранжировании используется доля денег, округленная до четверти, а не точная, и у категории меньше чем с пятью кандидатами балла нет. Иначе балл с точной долей раскрыл бы долю, которую округляет `money.share`, а балл с точным Supply малой группы - ее размер. Отображаемое разложение, состоит из опубликованных компонент.
|
||||
- Запрос не может задать рекомендацию, ее балл, членство или минимум кандидата: у тел `additionalProperties: false`, и неизвестные поля, например `rec_score`, `members`, `candidate_minimum`, `version`, `requirements_version` или `recommendations`, дают 400 с pointer на все тело. `TestNeedSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер, `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` - декодирование списков, а `frontend/src/shared/api/needs-contract.test.ts` закрепляет ограничения сгенерированного Zod, явный статус каждого решения и отсутствие этих полей в типах запросов.
|
||||
|
||||
Запланировано, добавляется без ломающих изменений: чтение и сравнение версий, исключения, подсказка рыночной вилки (P25-P75) из FR08, план проверки "вакансия -> задания", статус потребности для архивации, фильтры списка и назначения на потребность.
|
||||
|
||||
### Обращения
|
||||
|
||||
Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции реализованы: гость получает 401 `unauthenticated`, а подтвержденная сессия проходит проверку запроса и доменные правила. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/support-cases` | `ListMySupportCases` | сессия | 200 `SupportCaseList` из `SupportCaseSummary`, `Cache-Control: no-store` | 400 `validation_failed`, 401 |
|
||||
| `POST /api/v1/me/support-cases` | `CreateMySupportCase` | сессия и CSRF, Idempotency-Key | 201 `SupportCase`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 404 `not_found`, 409 `state_conflict` или `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `GET /api/v1/me/support-cases/{case_id}` | `GetMySupportCase` | сессия | 200 `SupportCase`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 404 `not_found` |
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`.
|
||||
|
||||
Доступ:
|
||||
|
||||
- Автор - аккаунт сессии; ни один запрос не содержит поля пользователя, аккаунта или организации. FR18 в PRD позволяет обращаться в поддержку и кандидату, и сотруднику компании, поэтому `/me` обслуживает оба сценария: аккаунт работодателя открывает обращения типа `support`, а остальные типы дают ему 403 `forbidden`. Обращение принадлежит создавшему его аккаунту, а не организации: другие участники той же организации его не видят.
|
||||
- Обращение другого аккаунта дает 404 `not_found`, как и неизвестный идентификатор. Контракт отвечает 404, чтобы идентификаторы нельзя было перебрать, и клиент показывает одно и то же состояние "не найдено" для чужого и неизвестного обращения. Автор читает обращение независимо от того, что потом стало с объектом, поэтому отказ в тесте или отозванный доступ его не скрывают.
|
||||
- Очереди модерации - отдельные служебные операции со своими DTO; к этим операциям они ничего не добавляют.
|
||||
|
||||
Типы и ссылки на объекты:
|
||||
|
||||
| Тип | Аккаунты | Ссылка на объект | Другие поля | Срок ответа |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `support` | кандидат, работодатель | необязательна; `assessment_attempt` автора, `organization`, которую автор видит, `invitation`, адресованное автору, или другое `support_case` автора | необязательный `assessment_target` | значение политики |
|
||||
| `complaint` | кандидат | обязательна; `organization`, которую автор видит, или `invitation`, адресованное автору | обязательный `complaint_reason` | значение политики |
|
||||
| `grade_appeal` | кандидат | обязательна; завершенная `assessment_attempt` автора или `support_case` автора типа `manual_assessment` в статусе `resolved` с исходом `assessed` | нет | 10 рабочих дней |
|
||||
| `anticheat_appeal` | кандидат | обязательна; `assessment_attempt` автора с решением античит-проверки | нет | 10 рабочих дней |
|
||||
| `manual_assessment` | кандидат | необязательна; прежняя `assessment_attempt` автора в той же специализации | обязательный `assessment_target`; `rubric_version` фиксирует сервер | 5 рабочих дней |
|
||||
|
||||
- Запрос - `oneOf` из пяти вариантов, выбираемых по `type` (`SupportCaseCreateSupport`, `SupportCaseCreateComplaint`, `SupportCaseCreateGradeAppeal`, `SupportCaseCreateAnticheatAppeal`, `SupportCaseCreateManualAssessment`). Каждый вариант сужает схему своей ссылки, поэтому уже схема отклоняет организацию в апелляции грейда или обращение в жалобе с pointer `/object/type`, а отсутствующее поле типа - с его pointer, например `/object` или `/assessment_target`. ogen выбирает вариант по значению `type`. Неизвестный или отсутствующий тип и поле другого варианта, например `complaint_reason` в обращении в поддержку, дают 400 с pointer на все тело `""`, потому что относятся к варианту верхнего уровня; `object.id`, который не является UUID, дает 400 с `/object/id` (пример `SupportCaseMalformedReference`).
|
||||
- Категорию, присвоенную без попытки, тоже можно оспорить (FR18): апелляция грейда может ссылаться на собственное обращение ручной оценки, когда оно `resolved` с `assessed`. Неизвестное обращение и обращение другого аккаунта дают 404 `not_found`; собственное обращение другого типа, еще не решенное или решенное с другим исходом дает 409 `state_conflict`.
|
||||
- Организацию видит кандидат, которого она пригласила или которому контракт организации показывает ее профиль, и аккаунт работодателя с действующим членством в ней. Сервер сверяет каждую ссылку с аккаунтом сессии: неизвестный и чужой объект одинаково дают 404 `not_found`, поэтому ссылка не раскрывает, существует ли чужой объект. Обращение хранит только `{type, id}`.
|
||||
- Приглашения есть в контракте (см. раздел Приглашения и контактные разрешения ниже), но не реализованы, а решений античит-проверки в контракте пока нет. До их реализации любая ссылка `invitation` дает 404, а любая античит-апелляция - 409 `state_conflict`; форма запроса не меняется.
|
||||
- Жалобы `offer_content` и `salary_terms_violation` требуют приглашения; другой объект дает 400 с pointer `/object/type` (доменное правило после схемы).
|
||||
- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; ручная оценка не зависит от C3. Кандидат, отозвавший C3 (`DELETE /api/v1/me/consents/c3`) или не дававший его, создает такой же запрос, а запрос не читает и не меняет журнал согласий. Повтор с тем же `Idempotency-Key` возвращает исходное обращение; новый ключ (например, после перезагрузки страницы) при открытой ручной оценке той же специализации дает 409 `state_conflict`, и открытое обращение остается единственным. `rubric_version` равна `null`, если для цели нет единственной актуальной проверенной категории; сервер не выбирает рубрику наугад, а обращение все равно ожидает эксперта без автоматического результата.
|
||||
|
||||
Содержание и поля, которые клиент не задает:
|
||||
|
||||
- `description` - простой текст длиной 1-4000 символов, в котором есть хотя бы один непробельный символ (`pattern: \S`); переносы строк разрешены. ogen переводит `\S` в набор пробельных символов ECMAScript, поэтому и Go-сервер, и сгенерированный Zod отклоняют пустой текст или текст из пробелов вроде U+00A0 или U+3000 с pointer `/description`. В пробельные символы ECMAScript не входит U+0085 (NEL), который Go `unicode.IsSpace` считает пробелом, поэтому реализация добавляет доменную проверку: описание, в котором каждый символ - `unicode.IsSpace` или U+FEFF, дает 400 с pointer `/description`; Zod такой текст принимает, решает сервер. Сервер хранит текст как есть и никогда не пишет его в журналы и уведомления.
|
||||
- У каждого варианта `additionalProperties: false`. Клиент не может задать статус, решение или его исход, приоритет, срок ответа, рубрику, исполнителя, модератора или контакт: такие поля, например `status`, `decision`, `moderator_id`, `response_target`, `rubric_version` или `reply_to`, дают 400 с pointer на все тело.
|
||||
|
||||
Обращение:
|
||||
|
||||
- `number` - понятный человеку номер, который присваивается при создании: `SC-<год UTC>-<порядковый номер>` минимум из шести цифр, например `SC-2026-000123`. Последовательность общая и не переиспользуется, поэтому номер уникален и не меняется. API адресует обращение только по UUID `id`; номер нужен для писем и звонков. Общая последовательность раскрывает примерное число созданных обращений, для MVP это допустимо.
|
||||
- `status` - `submitted`, `in_review`, `waiting_for_user`, `waiting_expert`, `resolved` (терминальный, с `decision`) или `closed` (терминальный, без решения по существу, например дубликат). Меняет его только сервер. `waiting_for_user` есть в перечислении, но пока не выставляется: он появится вместе с запланированной операцией ответа автора. Апелляции и ручная оценка переходят в `waiting_expert` событием `system` в той же транзакции, что и создание, поэтому ответ 201 уже показывает этот статус; в нем они остаются, пока решение не примет человек.
|
||||
- `response_target` - срок ответа из FR18: `kind` `operational_goal` (цель команды, а не срок, установленный законом), `business_days`, `due_at` по настроенному производственному календарю, `answered_at`, `late` и `policy_version`. Для `support` и `complaint` его выполняет первый публичный ответ, решение или закрытие; для апелляций и `manual_assessment` - только решение или закрытие. Пропуск срока не закрывает обращение и не меняет грейд.
|
||||
- `decision` равно null до `resolved`, а затем содержит `outcome` (`upheld`, `partially_upheld`, `not_upheld`, `answered` для поддержки, `assessed` для ручной оценки), публичную причину `reason` и `decided_at`. Удовлетворенная апелляция грейда не переписывает исходный результат; исправленный результат - отдельное решение оценки.
|
||||
- `history` перечисляет все публичные события по порядку, начиная с `created`: `kind` (`created`, `status_changed`, `reply`, `decision`), `actor` только по виду (`user`, `support`, `system`), `occurred_at`, итоговый `status` и публичный `message`. История никогда не обрезается. Инвариант сервера: в обращении не больше 200 событий, и сервер отклоняет ответ или смену статуса сотрудником, если после них не останется места для терминального события, поэтому любое обращение помещается в лимит и его всегда можно решить или закрыть; дальнейшая переписка идет в новом обращении со ссылкой `support_case` на это. Флаг обрезки с постраничными событиями отвергнут: полное обращение зависело бы от второго чтения, а сотрудники на практике не создают 200 публичных событий в одном обращении.
|
||||
- Обращение никогда не содержит личность модератора, эксперта или сотрудника поддержки, внутренние заметки, доказательства, ответы теста, античит-сигналы и сигналы риска или контакты другого человека.
|
||||
- Ответы доходят до пользователя через само обращение. Сервер может также уведомить подтвержденный email аккаунта номером и ссылкой, но не описанием, ответом или подробностями оценки; ни одно поле запроса не задает другой адрес, поэтому операция не может отправить письмо на адрес, введенный пользователем.
|
||||
- `ListMySupportCases` возвращает элементы `SupportCaseSummary`, новые первыми, с курсорной пагинацией: номер, тип, статус, ссылку на объект, категорию, срок ответа, `decision_outcome` и отметки времени, без описания и истории. Полное обращение возвращает только `GetMySupportCase`.
|
||||
|
||||
Команды и ограничения:
|
||||
|
||||
- Создание требует Idempotency-Key с повтором в течение 24 часов: повтор возвращает снимок ответа 201, сохраненный при создании, с тем же обращением и номером, по соглашению репозитория; текущее состояние клиент читает через `GetMySupportCase`. 404 и 409 `state_conflict` сохраняются и повторяются; 400, 403 и 429 - нет.
|
||||
- Попытка и решенная ручная оценка принимают не больше одной апелляции грейда каждая, а попытка - не больше одной античит-апелляции, в любом статусе; несогласие с решением оформляется обращением в поддержку со ссылкой `support_case` на апелляцию. Специализация принимает одну открытую ручную оценку, объект - одну открытую жалобу. Повторное обращение и апелляция грейда активной попытки дают 409 `state_conflict`.
|
||||
- Каждое создание, прошедшее аутентификацию, проверку запроса и сценарий аккаунта, учитывается в лимите аккаунта из продуктовой политики, включая повторы, 404 и 409, поэтому лимит ограничивает и перебор ссылок; сверх лимита сервер отвечает 429 с `Retry-After`.
|
||||
- Порядок проверок при создании: сессия (401), CSRF и Origin (403), проверка запроса (400), сценарий аккаунта (403 `forbidden`), лимит обращений аккаунта (429), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), доменные правила (400), ссылка на объект (404), затем состояние и ограничения (409 `state_conflict`). Общий лимит частоты может ответить 429 до любой проверки.
|
||||
- Новый problem-код не добавляется: перечисление `ProblemCode` побайтно копируется в ML-контракт. Недоступная античит-апелляция и повторная апелляция используют 409 `state_conflict`, а причину клиент узнает из обращения или попытки.
|
||||
- `TestSupportCaseSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер, а `frontend/src/shared/api/support-contract.test.ts` закрепляет правила сгенерированного Zod, отсутствие полей статуса, решения, модератора и контактов в типах запроса и отсутствие личности модератора и внутренних полей в обращении и в сводке.
|
||||
|
||||
Открытый продуктовый вопрос для ручной оценки: подчиняются ли повторные ручные оценки той же категории правилам пересдачи из FR04 (тот же грейд через 30 дней, не больше трех попыток за 180 дней) или собственному правилу. Контракт разрешает только одну открытую ручную оценку на специализацию и интервал не придумывает.
|
||||
|
||||
Открытые вопросы ручной оценки после отказа от C3: нужна ли структурная причина запроса (например, пометка "отказ от C3") вместо свободного текста `description`; должен ли запрос со второй задачей языка (две актуальные категории для одной специализации и грейда) получать рубрику с выбором языка, а не `null`; нужно ли возвращать существующее открытое обращение вместо 409 при повторе с новым ключом. Контракт ничего из этого не выдумывает.
|
||||
|
||||
Запланировано, добавляется без ломающих изменений (новая операция или необязательное поле): ответы автора, вложения, отзыв обращения, фильтры списка по статусу и типу, итоговая категория ручной оценки в решении, следующий шаг для автора, служебные очереди и решения и правила паузы срока ответа.
|
||||
|
||||
Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний из анализа профиля. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения - еще одно событие `decision`, а эксперты и модераторы - это `support`.
|
||||
|
||||
### Приглашения и контактные разрешения
|
||||
|
||||
Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Сторона организации в черновике реализована: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` следуют правилам ниже, но `salary_fit` всегда равен `not_available`, а лимит вилки и счетчик `withheld` пока не применяются ([backend](../backend/README.md#черновики-приглашений)). Реализованы также `SendOrganizationInvitation` и `ListMyInvitations`: отправка проверяет владельца, ключ, версию, состояние, текущую видимость кандидата, предел ожидающих приглашений на потребность и 30-дневную паузу после отказа, и только затем списывает недельную квоту организации; пауза после "сделки нет" пока не проверяется, потому что такого состояния никакая операция не создает; успех означает, что приглашение уже есть в `ListMyInvitations`, а уведомление и письмо идут следом через outbox ([архитектура](../docs/ru/ARCHITECTURE.md#отправка-приглашений)). `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` реализованы, как описано ниже, с одним ограничением: отмена участия еще не реализована. Чтение и просмотр в срок или позже сначала переводят ожидающее приглашение в `expired` с причиной `invitation_timeout` (чтение не записывает просмотр), а опоздавший отказ отвечает 409 `state_conflict`; у отказанного приглашения `contact_consent` и `contact_grant` равны null. `AcceptMyInvitation` реализован, как описывают правила ниже, но чтение контактов и отзыв разрешения еще не реализованы ([архитектура](../docs/ru/ARCHITECTURE.md#принятие-кандидатом)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/organizations/{org_id}/invitations` | `ListOrganizationInvitations` | сессия | 200 `OrganizationInvitationList` | 400, 401, 403 `forbidden`, 404 |
|
||||
| `POST /api/v1/organizations/{org_id}/invitations` | `CreateOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 201 `OrganizationInvitation` (`draft`) | 400, 401, 403, 404, 409 `idempotency_in_progress`, 422, 429 |
|
||||
| `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `GetOrganizationInvitation` | сессия | 200 `OrganizationInvitation` | 400, 401, 403, 404 |
|
||||
| `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `UpdateOrganizationInvitation` | сессия и CSRF | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409 `state_conflict`, 412, 429 |
|
||||
| `POST .../invitations/{invitation_id}/send` | `SendOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`delivered`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `POST .../invitations/{invitation_id}/salary-raise` | `RaiseOrganizationInvitationSalary` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `POST .../invitations/{invitation_id}/withdraw` | `WithdrawOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`withdrawn`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `GET .../invitations/{invitation_id}/contacts` | `GetOrganizationInvitationContacts` | сессия | 200 `ContactDisclosure` | 400, 401, 403, 404 |
|
||||
| `GET /api/v1/me/invitations` | `ListMyInvitations` | сессия | 200 `CandidateInvitationList` | 400, 401, 403 |
|
||||
| `GET /api/v1/me/invitations/{invitation_id}` | `GetMyInvitation` | сессия | 200 `CandidateInvitation` | 400, 401, 403, 404 |
|
||||
| `POST /api/v1/me/invitations/{invitation_id}/view` | `ViewMyInvitation` | сессия и CSRF | 200 `CandidateInvitation` (`viewed`) | 400, 401, 403, 404, 429 |
|
||||
| `POST /api/v1/me/invitations/{invitation_id}/accept` | `AcceptMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`accepted`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `POST /api/v1/me/invitations/{invitation_id}/decline` | `DeclineMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`declined`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
| `POST /api/v1/me/invitations/{invitation_id}/cancel` | `CancelMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`cancelled_by_candidate`) | 400, 401, 403, 404, 409, 412, 422, 429 |
|
||||
|
||||
Каждый успешный ответ имеет `Cache-Control: no-store`, и каждая операция также объявляет problem-ответ `default`. Пути `...` начинаются с `/api/v1/organizations/{org_id}`. 403 на изменяющей операции - `csrf_check_failed` или `forbidden`; 409 на команде - `state_conflict` или `idempotency_in_progress`; 412 - `version_conflict`; 422 - `idempotency_key_reused`. 429 на команде - общий лимит частоты с Retry-After, который может ответить до любой проверки; на создании, изменении и отправке это также лимит вилки или недельная квота. Чтение контактов и простые чтения собственного 429 не объявляют, как и другие чтения контракта.
|
||||
|
||||
Доступ:
|
||||
|
||||
- Сторона организации: `org_id` в пути - единственный источник организации, сервер сверяет его с действующим членством аккаунта сессии, как для потребностей. Аккаунт без членства, неизвестная организация, неизвестное приглашение и приглашение другой организации одинаково дают 404 `not_found`; аккаунт кандидата и участник, чья роль не разрешает операцию, получают 403 `forbidden`. В MVP с приглашениями работает только владелец; остальные роли FR07 запланированы.
|
||||
- Сторона кандидата: `/me/invitations` привязаны к аккаунту сессии. Черновик, приглашение другому кандидату и неизвестный идентификатор дают 404 `not_found`; аккаунт работодателя получает 403 `forbidden`. Ни в одном запросе нет поля пользователя, кандидата, организации или роли.
|
||||
- Кандидат указывается только через `candidate_handle` (`CandidateHandle` в `common_schemas.yml`, общий с результатами поиска FR11), никогда через email, телефон или идентификатор аккаунта либо профиля. Неизвестный handle, handle другой организации и профиль, который организация больше не может видеть, одинаково дают 400 с pointer `/candidate_handle`.
|
||||
|
||||
Условия (`InvitationTerms`):
|
||||
|
||||
- Условия полны с первого черновика, и каждое поле обязательно: `role_title`, `specialization`, `grade`, `offer_type` (`full_time`, `part_time`, `contract`, `internship`), `tasks`, `team`, `tech_stack`, `work_formats`, `location` (null только для полностью удаленной роли; для `office` или `hybrid` обязательно по доменному правилу с pointer `/terms/location`), `communication_method` (`channel` и необязательная заметка), `salary` (`SalaryRange`) и `package`. Поэтому черновик без базы net/gross или способа связи существовать не может: такое тело дает 400 `required` с `/terms/salary/tax_basis` или `/terms/communication_method` (примеры `InvitationWithoutTaxBasis` и `InvitationWithoutCommunicationMethod`).
|
||||
- `package` содержит `bonus`, `equipment`, `training` и `health_insurance` (ДМС). Каждое поле - `oneOf`: `{status: provided, description}` или `{status: not_provided}` ("Не предусмотрено" в интерфейсе). "Не предусмотрено" - явный выбор: пропущенное условие дает `required` со своим pointer, например `/terms/package/training`; `provided` без описания дает `required` на его `description`; `not_provided` с описанием дает `invalid` на самом условии. Сгенерированный Zod не строгий и отбрасывает такое описание, поэтому отклоняет его только сервер.
|
||||
- Намеренное отступление от формулировки критериев приемки: пакет в PRD называет формат работы рядом с бонусом, оборудованием, обучением и ДМС, но здесь формат - обязательное условие `work_formats` без варианта "не предусмотрено", потому что у роли всегда есть формат, а индикатор и поиск его сравнивают. Это открытый вопрос к владельцу продукта.
|
||||
- Одна схема служит полем запроса и сохраненным снимком, поэтому ответ можно отправить обратно без изменений. Условия никогда не содержат данных кандидата.
|
||||
|
||||
Версии и конфликты:
|
||||
|
||||
- `version` растет с каждым зафиксированным изменением, включая просмотр и серверное истечение срока. `terms_version` растет только при изменении условий: изменении `terms` в черновике или единственном повышении верхней границы после отправки. Каждая версия условий неизменяема.
|
||||
- Каждая команда, кроме просмотра, передает `expected_version`; `AcceptMyInvitation` передает еще `terms_version`. 412 `version_conflict`: `expected_version` или, при принятии, `terms_version` не текущие (случай устаревших условий, пример `InvitationStaleTerms`); ничего не изменено, под ключом ничего не сохраняется, клиент перечитывает приглашение. 409 `state_conflict`: состояние не допускает команду, например принятие отозванного или истекшего приглашения, команда в момент дедлайна или позже, отправка, заблокированная лимитом ожидающих по потребности или 30-дневной паузой, изменение отправленного приглашения или второе повышение; такой ответ сохраняется под ключом. Правило репозитория оставляет 412 для любой устаревшей версии, как для потребностей и анкеты.
|
||||
- Порядок: после того как приглашение найдено и наступивший срок применен, и после проверки повтора терминальное состояние (`declined`, `expired`, `withdrawn`, `cancelled_by_candidate`) или, для принятия и отказа, прошедший дедлайн дает 409 до сравнения версий. Поэтому клиент получает 409 для отозванного, истекшего или опоздавшего приглашения даже с устаревшими версиями и показывает итоговое состояние, а не перечитывает и повторяет. Затем идут версии (412) и остальные правила состояния (409). Это относится к принятию, отказу, отмене, отзыву и повышению вилки.
|
||||
- Повторы возвращают прежний результат: повтор с тем же Idempotency-Key воспроизводит сохраненный исход, а повтор команды, чей переход уже произошел, отвечает 200 с текущим приглашением даже с новым ключом или старой версией: отправка отправленного, отзыв отозванного, отказ с той же причиной и комментарием, отмена отмененного, то же повышение и принятие, чьи `terms_version` и поля совпадают с `contact_grant` - версией и полями, которые кандидат принял, даже если позднее повышение увеличило текущую `terms_version`. Второе согласие, grant, списание квоты или событие аудита не создаются.
|
||||
- `UpdateOrganizationInvitation` следует соглашению `UpdateOrganizationNeed`: без Idempotency-Key, с явной заменой полей, а тело, которое ничего не меняет, дает 200.
|
||||
|
||||
Состояния и просмотр:
|
||||
|
||||
- `InvitationState` перечисляет все состояния таблицы FR12: `draft`, `delivered`, `viewed`, `counter`, `accepted`, `interview_scheduled`, `interviewed`, `negotiation`, `terms_agreed`, `no_deal`, `declined`, `expired`, `withdrawn`, `cancelled_by_candidate`. Операции MVP производят `draft`, `delivered`, `viewed`, `accepted`, `declined`, `expired`, `withdrawn` и `cancelled_by_candidate`; остальные перечислены заранее, чтобы сгенерированные клиенты принимали их, когда появятся встречное предложение, интервью и закрытый финал. Внутренний этап `SENT` не виден: отправка отвечает `delivered` после создания входящей записи.
|
||||
- `expiry_reason` - `invitation_timeout` или запланированный `negotiation_timeout`, не null ровно в `expired`.
|
||||
- Просмотр - явная команда `ViewMyInvitation`: она переводит `delivered` в `viewed`, сохраняет дедлайн и в любом другом состоянии возвращает текущее приглашение без изменений. Команда идемпотентна по эффекту, поэтому ей не нужны ни Idempotency-Key, ни `expected_version`, и она никогда не падает из-за того, что приглашение изменилось после чтения клиентом. `GetMyInvitation` и `ListMyInvitations` побочных эффектов не имеют; чтение лишь показывает наступивший срок, который сервер применяет в момент дедлайна в любом случае. Команда не дает предзагрузке, повтору или обновлению кеша менять состояние, которое видит организация.
|
||||
- `withdrawn` - команда организации из любого незавершенного состояния, включая `draft` и `accepted`; существующий grant она сохраняет. `cancelled_by_candidate` - команда кандидата из любого незавершенного состояния после доставки; она отзывает grant этого приглашения. Отказ - структурированный ответ до принятия.
|
||||
- Дедлайн равен `delivered_at + response_period_days` (3, 7 или 14 дней, по умолчанию 7). Просмотр, письмо или повышение вилки его не сдвигают; команда, принятая в момент дедлайна или позже, опоздала.
|
||||
|
||||
Вилка и скрытый минимум:
|
||||
|
||||
- Условия переиспользуют `SalaryRange` с правилами раздела Потребности: RUB, месяц, `net` или `gross`, положительные границы, кратные 1000, `A < B` и ширина 10-40%, которую сервер проверяет с pointer `/terms/salary/salary_to`.
|
||||
- Организация получает только `salary_fit`: `within_range`, `up_to_10_percent_above`, `above`, `withheld` или `not_available` (нет минимума для предложенных форматов или он в другой базе). Точный минимум не появляется ни в ответе, ни в примере, ни в логе, ни в problem. Сервер никогда не отклоняет вилку из-за минимума, потому что отказ сам раскрыл бы его. В DTO кандидата индикатора нет; кандидат сравнивает с собственным минимумом из профиля.
|
||||
- Каждое изменение, которое может сдвинуть индикатор, считается установкой: вилка при создании, а в черновике изменение любой границы, базы или `work_formats`, потому что индикатор сравнивает с минимумом для предложенных форматов. Каждая установка учитывается в общем лимите организации - три в день вместе с вилками потребностей (429 с Retry-After) - и в счетчике `withheld`. Изменение, которое сохраняет вилку, базу и форматы, не учитывается.
|
||||
- `withheld`: после пяти установок за семь дней индикатор выключается на семь дней с пятой. Ответ на пятую установку уже показывает `withheld`, как и каждый черновик и каждое приглашение организации, включая существующие, до конца периода.
|
||||
- Переключение базы превращает `not_available` в диапазон или обратно и тем сообщает организации базу минимума; это принято, а переключение учитывается в лимите как любая установка.
|
||||
- После отправки база фиксирована, а нижняя граница не снижается. `RaiseOrganizationInvitationSalary` поднимает `salary_to` один раз за всю историю приглашения, создает следующую версию условий и отвечает 409 на второе повышение. Оно подчиняется своему однократному правилу и не входит в дневной лимит, но учитывается в счетчике `withheld`, потому что сдвигает верхнюю границу, с которой сравнивает индикатор.
|
||||
|
||||
Согласие C4 и контактное разрешение:
|
||||
|
||||
- `GetMyInvitation` показывает в `contact_consent` текст C4 для этой организации и виды контактов, которые есть в профиле. Поле равно null, когда принять приглашение нельзя: этого не допускает состояние или дедлайн либо в профиле нет контактов. В последнем случае клиент просит кандидата сначала добавить контакт, потому что grant должен покрывать хотя бы одно поле.
|
||||
- `AcceptMyInvitation` передает `terms_version`, `expected_version` и `consent_c4` (`ContactConsentAcceptance`): показанную версию текста C4, `accepted: true` и `fields` - хотя бы одно из `full_name`, `email`, `phone`, `telegram`, без значения по умолчанию и без предвыбора. Неопубликованная версия текста дает 400 `/consent_c4/text_version`, а поле, которого нет в профиле, - 400 `/consent_c4/fields/<i>`. Согласие аналогично принятию C1 по `text_version`, а запись совпадает с реестром согласий C4 (цель, версия и хэш текста, организация, набор полей, приглашение-источник). Разрешение передавать данные в ATS организации (C4 и FR19) запланировано как дополнительный необязательный флаг, по умолчанию без передачи.
|
||||
- В одной транзакции принятие переводит приглашение в `accepted`, записывает C4, создает grant ровно на выбранные поля и пишет событие аудита. Оно не публикует профиль (C2) и не снимает скрытие.
|
||||
- У `contact_grant` кандидата есть `status` (`active` или `revoked`), `readable` и `blocked_by`. Grant, созданный, когда профиль не был опубликован или был скрыт от организации, остается `active` с `readable: false` и `blocked_by: visibility`, чтобы кандидат видел, почему организация не может его прочитать (FR12 в PRD); он станет читаемым, когда кандидат опубликует профиль или снимет скрытие. Любое изменение видимости после появления grant отзывает его (`visibility_closed`), и повторная публикация его не открывает.
|
||||
- Значения контактов передаются только в `ContactDisclosure` из `GetOrganizationInvitationContacts`, отдельно от условий и приглашения. Каждое чтение проверяет членство, C4, grant и его поля и текущую видимость без кеша. Без читаемого grant операция отвечает 404 `not_found`, как для неизвестного приглашения. `contact_access` организации - `not_granted` (grant нет), `available` (с видами полей) или `closed`, что покрывает и отозванный grant, и grant, заблокированный с самого начала, не говоря, какой из них. Это наименее раскрывающее правило: отзыв, скрытие и отсутствие публикации выглядят одинаково, а поскольку любое изменение видимости после появления grant его отзывает, организация не наблюдает последующих переключений; стать `available` может только grant, заблокированный с начала, и лишь по собственному выбору кандидата. Поля вне grant равны null.
|
||||
- Отзыв: `CancelMyInvitation` отзывает grant этого приглашения (`participation_cancelled`); отзыв C4 для организации закрывает все ее grants (`consent_revoked`); отзыв C2 или скрытие профиля закрывает их (`visibility_closed`). Отзыв приглашения, `no_deal` и таймаут финала grant не отзывают; новый grant создает только новое явное C4. Отдельная операция отзыва grant относится к контракту согласий.
|
||||
- Реализация: чтение контактов, отзывы C4 и C2, закрытие публикации и скрытие реализованы, только для владельца, и закрывают разрешения так, как описано в пункте выше (архитектура: [Чтение контактов и отзыв](../docs/ru/ARCHITECTURE.md#чтение-контактов-и-отзыв)). `contact_access` организации выводится при каждом чтении приглашения (`GetOrganizationInvitation`, список и ответы создания, изменения и отправки) теми же проверками, что и чтение контактов, поэтому он показывает `available` только там, где чтение бы прошло, и никогда не называет причину. `CancelMyInvitation` пока не реализован.
|
||||
- Форматы значений: ФИО одной строкой до 200 символов, телефон в формате E.164 и имя пользователя Telegram с ведущим @. Контракт профиля (FR02) должен хранить контакты в тех же форматах, чтобы раскрытие не преобразовывало и не отбрасывало сохраненное значение.
|
||||
|
||||
Отказ и приватность:
|
||||
|
||||
- `DeclineMyInvitation` принимает `reason` (`salary`, `tasks`, `stack`, `work_format`, `package`, `company`, `not_looking`, `other_offer`, `other`) и необязательный `comment` до 500 символов; для `other` комментарий не нужен. Организация видит только `declined` и `responded_at`, но не причину и не комментарий: причина вроде `salary` сообщила бы ей, что скрытый минимум выше вилки. Причины идут только в агрегаты с минимальным размером группы (запланировано). Кандидат читает их обратно в `decline`.
|
||||
- Ни один DTO приглашения ни одной стороны не содержит ФИО, email, телефон, Telegram, идентификатор аккаунта или профиля или минимум кандидата; примеры используют только синтетические данные. `TestInvitationSchemaValidationPrecedesImplementation` проверяет отказы схемы и pointer через сгенерированный сервер, `TestInvitationDTOsCarryNoContactOrMinimum` - сгенерированные Go DTO, а `frontend/src/shared/api/invitation-contract.test.ts` закрепляет правила сгенерированного Zod и на уровне типов отсутствие полей контактов, минимума и отказа.
|
||||
|
||||
Открытые продуктовые вопросы: допустимо ли второе незавершенное приглашение той же организации тому же кандидату (PRD об этом молчит, поэтому контракт правила не придумывает), отступление по формату в пакете выше, типы предложения, виды контактов и причины отказа.
|
||||
|
||||
Запланировано, добавляется без ломающих изменений: встречное предложение и ответ компании, чтение прежних версий условий, операции интервью и закрытого финала, фильтры списков, метрики отзывчивости организации для кандидата, ориентировочная сумма в другой базе, агрегаты причин отказа, флаг ATS в C4 и поля ФСП как новые виды контактов (новое значение enum выпускается вместе с перегенерированными клиентами).
|
||||
|
||||
Новый код ошибки не добавлен: enum `ProblemCode` побайтно копируется в ML-контракт, а `version_conflict` и `state_conflict` покрывают устаревшие условия и конфликты состояния.
|
||||
|
||||
### Согласия
|
||||
|
||||
Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Реализованы публичное чтение C1, чтение текущих текстов настроек и собственной истории, выдача C1/C2/C3/C5, отзыв C2/C3/C5 и отзыв C4 в области одной организации. Запрос C1 создает долговечный запрос на удаление аккаунта; сама запись аккаунта не удаляется синхронно. Эти обработчики требуют действующую подтвержденную PostgreSQL-сессию, а изменяющие операции также требуют session-bound CSRF и единственный `Origin`, совпадающий с `APP_PUBLIC_URL`. Гость получает 401; неподходящая роль, неверный Origin или CSRF получают 403.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/identity/consent-texts/c1` | `GetConsentText` | публичная | 200 `ConsentText` | 400 `validation_failed` |
|
||||
| `GET /api/v1/me/consent-texts/{purpose}` | `GetMyConsentText` | сессия | 200 `ConsentText`, `Cache-Control: no-store` | 400, 401 |
|
||||
| `GET /api/v1/me/consents` | `ListMyConsents` | сессия | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 |
|
||||
| `PUT /api/v1/me/consents/{purpose}` | `GrantMyConsent` | сессия и CSRF | 200 `ConsentRecord`, `Cache-Control: no-store` | 400, 401, 403 |
|
||||
| `DELETE /api/v1/me/consents/{purpose}` | `RevokeMyConsent` | сессия и CSRF | 204 | 401, 403 |
|
||||
| `DELETE /api/v1/me/consents/c4/organizations/{org_id}` | `RevokeMyOrganizationContactConsent` | сессия и CSRF | 204 | 400, 401, 403 |
|
||||
| `POST /api/v1/me/account-deletion-requests` | `RequestMyAccountDeletion` | сессия и CSRF | 202 `ConsentDeletionRequest`, `Cache-Control: no-store` | 401, 403 |
|
||||
|
||||
- Цели (`ConsentPurposeCode`): `c1` - обработка персональных данных, `c2` - публикация карточки кандидата, `c3` - автоматическая категоризация, `c4` - передача выбранных контактов одной организации, `c5` - импорт результатов ФСП. Публичный `GetConsentText` остается доступен только для C1; `GetMyConsentText` возвращает текущий текст C1/C2/C3/C5 перед выдачей в настройках. Текст C4 остается частью приглашения с его конкретной областью.
|
||||
- Субъект берется из сессии; ни один параметр не называет аккаунт, поэтому ответ содержит только собственные записи вызывающего. Страница перечисляет записи от новой выдачи к старой с курсорной пагинацией; необязательный фильтр `state` принимает `active`, `superseded` или `revoked`, а неизвестное значение отвечает 400 с указателем `/state`.
|
||||
- `ConsentRecord` содержит цель, принятую `text_version`, `source` (`registration`, `consent_settings` или `invitation_acceptance`), `granted_at`, вычисленное `state`, а также `revoked_at` и `revocation_source` (`consent_settings` или `support_request`). Запись `c4` дополнительно называет `organization` (`ConsentOrganization`, где `name` - снимок названия из текста согласия, поэтому последующее переименование его не меняет), поля контакта `fields` (`ContactFieldKind`), `invitation_id` и `invitation_terms_version`; для остальных целей они равны null. Запись `c2` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации ([Видимость кандидата](#видимость-кандидата)), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации.
|
||||
- Выдача в настройках требует явного `accepted: true` и текущую версию прочитанного текста. C1 можно выдать аккаунту кандидата или работодателя; C2/C3/C5 доступны только кандидату. C4 нельзя выдать общей операцией настроек: он выдается только принятием конкретного приглашения.
|
||||
- Журнал только дополняется. Новая версия текста цели - новая запись, а прежняя становится `superseded` без изменений; отзыв ставит отметку на все неотозванные записи цели, включая прежние версии. Отзыв C4 действует только для одной организации и берет набор полей из сохраненных записей, не из запроса. Повтор отзыва безопасен и не создает второе событие.
|
||||
- Отзыв C2 в одной транзакции закрывает действующую публикацию, очищает ее поля, добавляет запись privacy history и пишет ограниченный по размеру outbox intent. Новая выдача C2 не открывает прежнюю публикацию. Отзыв C3 не блокирует ручной путь оценки. Отзыв C5 немедленно закрывает consent gate для будущего импорта и пишет stop/delete intent; внешнего адаптера ФСП нет, поэтому фактическое удаление данных во ФСП не заявляется.
|
||||
- Запрос удаления C1 отзывает C1 и создает или возвращает активный запрос удаления и outbox intent в одной транзакции. Повтор возвращает тот же запрос; последующая выдача C1 его не отменяет. Обработчик будущего удаления аккаунта не синхронен и пока отсутствует.
|
||||
- Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`.
|
||||
|
||||
Открытый юридический вопрос: является ли `c2` согласием на распространение персональных данных по статье 10.1 152-ФЗ, которое требует отдельного согласия с категориями данных.
|
||||
|
||||
Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden` и `csrf_check_failed`. Контрактные тесты закрепляют security-схемы и порядок валидации, `TestConsentSettingsOverHTTP` проверяет согласия с настоящими PostgreSQL и Redis, а `frontend/src/shared/api/consent-contract.test.ts` закрепляет сгенерированные правила Zod и отсутствие в DTO хэшей, субъекта и контактов.
|
||||
|
||||
### Организации
|
||||
|
||||
Тег `organization` включает реализованные создание, чтение, редактирование и список своих организаций. Подтвержденный работодатель создает организацию с активным владельцем; операции в области организации требуют активного владельца на каждом запросе. Небезопасные операции требуют CSRF-токен сессии и точный Origin. Общий middleware защищает также пока не реализованные потребности и приглашения до ответа 501. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства).
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/organizations` | `ListMyOrganizations` | сессия | 200 `MyOrganizationList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
|
||||
| `POST /api/v1/organizations` | `CreateOrganization` | сессия и CSRF, Idempotency-Key | 201 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
|
||||
| `GET /api/v1/organizations/{org_id}` | `GetOrganization` | сессия | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `forbidden`, 404 `not_found` |
|
||||
| `PATCH /api/v1/organizations/{org_id}` | `UpdateOrganization` | сессия и CSRF | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 404, 412 `version_conflict`, 429 |
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`. Некорректный `org_id` отвечает 400 с указателем пути.
|
||||
|
||||
Активный контекст организации:
|
||||
|
||||
- Контекст не хранится на сервере. Каждая операция в области организации, включая потребности и приглашения этого контракта, называет организацию в пути `org_id`, а сервер на каждом запросе проверяет этот идентификатор по активному членству аккаунта сессии. Сам идентификатор ничего не дает; переключение между организациями - это другой `org_id` в маршрутах клиента.
|
||||
- Причина: атрибут сессии был бы кешем членства, который пришлось бы сбрасывать при удалении, приостановке или выходе (нужно закрыть следующее чтение, а не ждать истечения кеша браузера), две вкладки в двух организациях спорили бы за одно значение, а форма с путем уже является контрактом потребностей и приглашений. Переключение организации очищает клиентские запросы с ее областью, что согласуется с клиентским контекстом.
|
||||
- `ListMyOrganizations` - справочник контекстов: организации, где у вызывающего `active` членство, от нового членства к старому, с ролью и состоянием вызывающего. Клиент выбирает контекст из него, может помнить последний выбор в браузере для удобства и перечитывает список после 404 по пути организации. Человек с несколькими членствами видит все и работает в одной за раз; права и данные организаций остаются раздельными.
|
||||
|
||||
Доступ:
|
||||
|
||||
- Только аккаунт работодателя. Аккаунт кандидата получает 403 `forbidden` на всех четырех операциях, аккаунт без сессии - 401.
|
||||
- `GetOrganization` и `UpdateOrganization` одинаково отвечают 404 `not_found` аккаунту без активного членства в `org_id` и на неизвестную организацию, а также участнику в состоянии `suspended`, `removed` или `left`, поэтому организации нельзя перечислить, а отозванный участник теряет следующее чтение сразу. Участник, чья роль не управляет организацией, получает 403 `forbidden` на `GetOrganization` и `UpdateOrganization`; матрица FR07 отдает управление компанией и сотрудниками только владельцу. В MVP каждый участник - владелец, потому что операции добавления участников запланированы.
|
||||
- `CreateOrganization` создает организацию и членство владельца для вызывающего в одной транзакции (роль `owner`, состояние `active`), поэтому организации без владельца не существует; база отказывается фиксировать такую. В теле нет поля владельца, роли, членства или уровня проверки.
|
||||
|
||||
Членства:
|
||||
|
||||
- Членство - это `(пользователь, организация, роль, состояние)`, уникальное для пары в любом состоянии. `OrganizationRole` содержит `owner`, `recruiter`, `hiring_manager` и `technical_expert` (2.2 и Q3 в PRD). `MembershipState` содержит `active`, `suspended` (доступ остановлен, можно вернуть), `removed` (завершено владельцем или платформой) и `left` (завершено участником). Доступ дает только `active`, и список возвращает только `active` членства; `joined_at` - момент первого создания членства (вернувшийся участник сохраняет его, а время последней активации - запланированное поле `activated_at`); членство `removed` по решению платформы не должно само возвращаться в работу по решению владельца, принятию приглашения или управлению участниками, а кто и почему удалил участника - аддитивные поля управления участниками; остальные состояния есть в enum, чтобы управление участниками могло их показывать без изменения контракта. Добавление роли или состояния - изменение контракта.
|
||||
- Роль живет только в членстве. В `Organization`, `OrganizationCreate`, `OrganizationUpdate` и `CandidateOrganizationCard` нет поля роли, владельца или участника. Свою роль вызывающий читает в `OrganizationMembership` из `ListMyOrganizations`; DTO не называет аккаунт.
|
||||
- Состояния `invited` нет: сотрудник попадает в организацию только по приглашению на email (2.2 в PRD), которое задачи приглашения сотрудников хранят отдельной записью и превращают в `active` членство, когда владелец адреса его принимает. Человек может иметь независимые членства в нескольких организациях.
|
||||
- Применение полной матрицы ролей (рекрутер, нанимающий менеджер, техэксперт) к потребностям, приглашениям и контактам запланировано в ролевом контроле доступа. До этого остальные роли ничего не дают: операции потребностей и приглашений отвечают им 403 `forbidden`, как сказано в их разделах. Список и управление участниками, смена ролей, удаление участников и правило, что последнего владельца удалить нельзя, запланированы в управлении участниками и добавляют в контракт операции, а не поля.
|
||||
|
||||
Профиль:
|
||||
|
||||
- `OrganizationCreate` требует только `name`. Поля профиля: `name` (1-200 символов, без пробелов и переводов строки по краям, потому что запись согласия хранит его копию), `description` (1-2000 символов, nullable, переводы строки разрешены), `sphere` (1-100 символов, nullable, свободный текст: в PRD нет таксономии сферы, а код таксономии был бы аддитивным полем), `contacts` и `representatives`.
|
||||
- `contacts` - один объект с `website`, `email`, `phone` и `telegram`, все обязательные и nullable, поэтому он одновременно поле запроса и сохраненное значение. Это публичные каналы компании: сайт по https без учетных данных, порта и IP-адреса, почта для вакансий, телефон в формате E.164 и имя пользователя Telegram с ведущим `@`. Личных контактов сотрудника в контракте нет, а сервер не отличает личный адрес от адреса компании, поэтому за содержимое отвечает владелец; жалоба на организацию подается через обращение в поддержку. Сервер никогда не обращается по адресу сайта.
|
||||
- `representatives` - список до десяти записей `{name, job_title}` в порядке, заданном владельцем. Представитель существует только для показа: не участник, без связи с аккаунтом, без контакта и без прав, а участник не становится представителем при вступлении. Имя - персональные данные сотрудника, которые публикует владелец, отсюда открытый вопрос ниже.
|
||||
- `UpdateOrganization` использует явную замену полей, как `UpdateOrganizationNeed`: присутствующее поле заменяет поле целиком, отсутствующее остается без изменений, а `contacts` и `representatives` никогда не объединяются. `description` и `sphere` со значением null становятся неустановленными; `name`, `contacts` и `representatives` не могут быть null. ogen генерирует `OptNil` для nullable-полей и обычный slice для `representatives`, где nil означает отсутствие, а `[]` - замену пустым списком; обработчик обязан проверять его через `!= nil`, а не через `len` (`TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`).
|
||||
- Текст простой: клиенты показывают каждое поле как текст, а не как HTML. Доменные правила, которым нужно больше, чем схема, например правила хоста сайта, отвечают 400 с указателем (`/contacts/website`, `/representatives/0/job_title`); формы показывают примеры.
|
||||
|
||||
Уровень проверки:
|
||||
|
||||
- `OrganizationVerificationLevel` - `e0`, `e1`, `e2` или `e3` (FR07 в PRD). Новая организация начинает с `e0` на основании `confirmed_email`, как бы ни выглядел ее профиль. Более высокий уровень сервер сообщает только после того, как его записал процесс проверки; процессов для `e1`, `e2` и `e3` еще нет (запланированный процесс проверки добавляет E0/E1 с доказательствами, областью действия и историей), поэтому клиент считает любой уровень, кроме `e0`, недоступным, а контракт никогда не сообщает `e1`, `e2` или `e3` достигнутыми сами по себе.
|
||||
- Ни один запрос не задает и не повышает уровень или его основание: `OrganizationCreate` и `OrganizationUpdate` - закрытые объекты только с полями профиля, ни одна операция контракта не меняет уровень, а правка описания, контактов или представителей оставляет его как есть. База держит уровень и основание в отдельных столбцах, которые оператор обновления профиля никогда не пишет, а CHECK связывает каждый уровень с его основаниями. `OrganizationVerification` только для чтения: `level`, `basis` и `changed_at`; область проверки и история изменений (FR07 в PRD) придут аддитивными полями с первым процессом.
|
||||
- Уровень выбирает ступень квот (E0 10 приглашений и 50 карточек, E1 40 и 150, E2 100 и 400 в демо-политике); `domain.OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику. Применение квот - отдельная запланированная функция.
|
||||
|
||||
Карточка кандидата и версии:
|
||||
|
||||
- `Organization.candidate_card` - карточка так, как ее видит кандидат; сервер строит ее из профиля и уровня: предпросмотр FR07 в PRD. Ее видит только кандидат, получивший приглашение от организации; это не публичная страница, и ни одна операция не показывает ее другим, пока не решен вопрос об именах представителей ниже. Она повторяет поля профиля и добавляет только уровень; в ней нет членства, роли, аккаунта, версии и основания. Ее `representatives` необязательно и допускает null: отсутствие или null означает, что представители не опубликованы, а не что их нет. Контракт приглашения называет организацию через `InvitationOrganization` и планирует аддитивно отдавать эту карточку кандидату.
|
||||
- `version` начинается с 1 и растет с каждым зафиксированным изменением профиля. Изменение несет `expected_version` в теле по той же причине, что и потребности: сгенерированный клиент пока не читает `ETag`. Устаревшее значение отвечает 412 `version_conflict` и ничего не меняет; правило репозитория сохраняет 412 для устаревшей версии, как и для потребностей. Тело без изменений отвечает 200 с текущей организацией, поэтому PATCH не нужен Idempotency-Key. POST нужен ключ с повтором на 24 часа; сохраняется только 201.
|
||||
- Порядок проверок `UpdateOrganization`: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), членство (404) и роль (403), тело без изменений (200), версия (412), доменные правила (400).
|
||||
|
||||
Внешние ключи на организации: `memberships` и `organization_representatives` ссылаются на `organizations(id)` уже сейчас. Журнал согласий, потребности и приглашения несут `organization_id` и ссылаются на него ограничивающим внешним ключом в миграции, создающей записи приглашений, потому что для области C4 нужны сразу обе ссылки, а тесты журнала согласий используют синтетические идентификаторы организаций. Приложение никогда не удаляет организацию.
|
||||
|
||||
Открытые вопросы к владельцу продукта:
|
||||
|
||||
- Представители: может ли карточка показывать их имена любому кандидату до принятия приглашения и кто отвечает за право публиковать имя сотрудника (152-ФЗ)? Альтернатива - показывать представителей только в приглашении, отправленном их организацией.
|
||||
- Сфера: пока свободный текст; таксономия сферы, согласованная с доменами потребностей, - решение для поисковых фильтров.
|
||||
- Контакты: нужен ли в карточке пятый вид, например страница вакансий, и должна ли почта совпадать с доменом сайта.
|
||||
|
||||
Решение владельца продукта: число организаций на аккаунт не ограничено. Организации одного аккаунта образуют холдинг, а E0-квоты (в демо-политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа) общие для E0-организаций этого холдинга; организация на E1 и выше считает свои квоты отдельно. Контракт не меняется: холдинг внутренний, и ни одна операция его не показывает.
|
||||
|
||||
Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление, полная матрица ролей, процессы проверки и их история, квоты по уровню, карточка в приглашении кандидата, и код сферы.
|
||||
|
||||
Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused` и `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart` и `TestOrganizationContractFollowsThePRD` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/organization-contract.test.ts` - сгенерированные правила Zod и, на уровне типов, отсутствие полей роли, владельца, участников и уровня проверки в запросах.
|
||||
|
||||
### Видимость кандидата
|
||||
|
||||
Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)).
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/privacy` | `GetMyPrivacySettings` | сессия | 200 `PrivacySettings`, `Cache-Control: no-store` | 401, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/privacy/publication` | `SetMyPublication` | сессия и CSRF | 200 `Publication`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict`, 412 `version_conflict` |
|
||||
| `GET /api/v1/me/privacy/preview` | `GetMyCardPreview` | сессия | 200 `CardPreview`, `Cache-Control: no-store` | 401, 403 |
|
||||
| `PUT /api/v1/me/privacy/search-status` | `SetMySearchStatus` | сессия и CSRF | 200 `SearchStatus`, `Cache-Control: no-store` | 400, 401, 403, 412 |
|
||||
| `GET /api/v1/me/privacy/hidden-organizations` | `ListMyHiddenOrganizations` | сессия | 200 `HiddenOrganizationList`, `Cache-Control: no-store` | 400, 401, 403 |
|
||||
| `PUT /api/v1/me/privacy/hidden-organizations/{org_id}` | `HideOrganization` | сессия и CSRF | 200 `HiddenOrganization`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 409 `state_conflict`, 429 |
|
||||
| `DELETE /api/v1/me/privacy/hidden-organizations/{org_id}` | `UnhideOrganization` | сессия и CSRF | 204 | 400, 401, 403 |
|
||||
| `GET /api/v1/me/privacy/history` | `ListMyPrivacyHistory` | сессия | 200 `PrivacyEventList`, `Cache-Control: no-store` | 400, 401, 403 |
|
||||
| `GET /api/v1/me/privacy/access-history` | `ListMyCardAccessHistory` | сессия | 200 `CardAccessList`, `Cache-Control: no-store` | 400, 401, 403 |
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `state_conflict`, `version_conflict` и `rate_limited`. Аккаунт работодателя получает 403 `forbidden` на всех девяти операциях.
|
||||
|
||||
Закрыто по умолчанию и три независимые настройки:
|
||||
|
||||
- Профиль закрыт по умолчанию. Кандидат, который никогда не публиковал, читает `publication.state` `closed`, `closed_reason` `never_published`, пустой набор полей и версию 0; сохранение профиля, заполнение анкеты и оценка его не публикуют. У каждой настройки своя `version` (0 - "никогда не задавалась"), своя операция и свой `expected_version` в теле, поэтому изменение одной никогда не делает устаревшей другую.
|
||||
- Публикация и C2 разделены. Согласие C2 остается в журнале согласий (`ListMyConsents`) и доказывает, что кандидат принял текст публикации. `Publication` хранит, какие поля опубликованы и когда, и ссылается на запись C2 за ними (`consent_id` - `id` записи `ConsentRecord` того же аккаунта). Она не дублирует согласие: `state` равен `published`, только пока эта запись не отозвана, поэтому отзыв C2 закрывает карточку сразу, а `closed_reason` показывает `consent_revoked`. Новая выдача C2 карточку не открывает: кандидат публикует заново, и новая публикация привязывается к новой записи. Тело `SetMyPublication` не называет согласие: сервер привязывает текущую неотозванную запись C2 аккаунта, а без нее отвечает 409 `state_conflict` (кандидат сначала дает C2; операция выдачи запланирована в настройках согласий).
|
||||
- Статус поиска - не согласие. В `SearchStatus` и `SearchStatusUpdate` нет свойств согласия, публикации или организации, схемы одного семейства не достигают другого (тест обходит ссылки), а `SetMySearchStatus` не меняет ничего, кроме статуса. Кандидат с закрытым профилем, который задал `looking`, не становится видимым никому.
|
||||
- Скрытые организации - записи кандидата (`HiddenOrganization`: организация с ее текущим названием и `hidden_at`). Одна запись на кандидата и организацию, не более 1000 на кандидата. Организация их не читает, не узнает, что скрыта, и видит скрывшего кандидата так же, как неопубликованного. Скрытие и его снятие не меняют ни C2, ни публикацию, ни статус поиска.
|
||||
- Скрытие - это PUT состояния, поэтому оно идемпотентно и не требует Idempotency-Key: повторное скрытие отвечает 200 с исходной записью и не пишет историю. Снятие - DELETE, который отвечает 204, была организация скрыта или нет.
|
||||
|
||||
Статус поиска и его 30 дней:
|
||||
|
||||
- `looking` ("Ищу") хранит `confirmed_at` и `lapses_at`. Срок - не константа контракта или кода: это `search_status.searching_confirmation_interval_days` действующей версии политики `product` (в демо-версии 1 - 30), прочитанное при подтверждении статуса. Строка называет версию политики, которой воспользовалась, и фиксирует `lapses_at`, поэтому последующее изменение политики не сдвигает сохраненные времена. Владелец меняет срок публикацией новой версии политики.
|
||||
- После `lapses_at` статус действует как `not_looking` с `lapsed` true. Истечение вычисляется при каждом чтении и нигде не записывается, поэтому не требует задачи и может только сужать: оно никогда не публикует, не снимает скрытие и не меняет C2 или скрытые организации. Кандидат подтверждает снова через `SetMySearchStatus` со значением `looking`, которое заменяет `confirmed_at` и увеличивает версию. Напоминание до истечения - запланированное уведомление.
|
||||
- Истекший статус никогда не становится "более публичным": единственное состояние, до которого доходит истечение, - непубличное `not_looking`. Влияет ли `looking` на появление опубликованной карточки в выдаче поиска - решение контракта поиска, здесь не принято.
|
||||
|
||||
Анонимная карточка и предпросмотр:
|
||||
|
||||
- `CardField` - закрытый набор групп значений карточки, которые кандидат выбирает публиковать: `categories` (категории, подтвержденные результатами оценки), `stack`, `experience` (суммарно в месяцах), `soft_skills`, `location` и `relocation`. У полного имени, любого контакта и минимальной зарплаты значения нет, поэтому ни один запрос не может их опубликовать; контакты доходят до организации только через контактное разрешение принятого приглашения (C4), а минимальная зарплата не доходит никогда. Самооценка грейда не категория и никогда не публикуется. Сервер хранит и отдает набор в порядке возрастания кодов.
|
||||
- `AnonymousCardContent` - карточка так, как ее читает организация: закрытый объект из шести свойств выше, каждое равно null, если не опубликовано или значения нет, поэтому карточка не различает эти случаи. В ней нет имени, email, телефона, имени в Telegram, работодателя, суммы зарплаты, идентификатора аккаунта или профиля, и из нее недостижима ни одна схема приватного профиля, контакта, согласия, приглашения или организации (`TestAnonymousCardReachesNoProfileOrContactSchema` обходит ссылки). `GetMyCardPreview` возвращает ее с опубликованными полями или `card` null, пока профиль закрыт, как приватное чтение, которое не создает просмотра и записи в истории. Карточка результата поиска организации должна использовать это содержимое и не вправе добавлять свойство, идентифицирующее кандидата.
|
||||
|
||||
Версии и проверки:
|
||||
|
||||
- Обе операции `PUT` настроек следуют образцу профиля: полное новое состояние в теле, `expected_version` в теле (сгенерированный клиент пока не читает ETag), 412 `version_conflict` для устаревшей или несуществующей версии, а тело без изменений отвечает 200 с текущим состоянием даже при устаревшей версии, поэтому Idempotency-Key не нужен. Порядок проверок: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), версия выше текущей (412), неизмененное состояние (200), устаревшая версия (412), затем C2 для публикации (409). Состояние `published` без поля и `closed` с полем отвечают 400 с указателем `/fields`; схема отклоняет неизвестное или повторное поле карточки и неизвестные свойства, например идентификатор согласия или время подтверждения. `looking` всегда меняет сохраненное подтверждение, поэтому при устаревшей версии отвечает 412 даже как повтор. Два вида 409 `state_conflict` различаются через `errors`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Закрытие поверх сохраненной публикации с отозванной C2 - настоящее изменение (сохраняет закрытие, пишет `publication_closed` и отзывает разрешения); путь отзыва C2 сам закрывает сохраненную публикацию и отзывает разрешения в своей транзакции. Публикации, скрытию и истории нужен подтвержденный email (требование юзкейса). `Problem.errors` не только для `validation_failed`: `state_conflict` несет одну запись как уточнение (`consent_required`, `limit_reached`), поэтому будущий писатель problem не должен вырезать `errors` из ответов, не связанных с валидацией. В карточку попадают только подтвержденные значения, свободный текст, похожий на контакт (email, телефон, URL, ссылка Telegram, @handle), отбрасывается, а новое поле карточки - это изменение контракта и миграция.
|
||||
- 404 и защита от перебора. `HideOrganization` отвечает одинаковым 404 `not_found`, с тем же телом и без другого времени ответа, и для несуществующей организации, и для той, которую кандидат не видит, поэтому операция не позволяет спросить, принадлежит ли идентификатор организации. Кандидат видит организацию, приславшую ему приглашение, и организации, которые покажет поиск организаций для кандидата (запланирован). Идентификаторы случайные, а общий лимит запросов может ответить 429 с Retry-After до любой проверки. `UnhideOrganization` ничего не раскрывает: 204 на любой корректный идентификатор. Некорректный `org_id` отвечает 400 с указателем `/org_id`.
|
||||
- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (запланировано вместе с операциями; причину задает контракт приглашений). Снятие скрытия и повторная публикация разрешение не возвращают. Статус поиска разрешение никогда не отзывает.
|
||||
|
||||
История:
|
||||
|
||||
- `ListMyPrivacyHistory` возвращает журнал изменений настроек только для добавления, от новых к старым (история хранит только идентификатор организации, а текущее название определяется при чтении): `publication_opened`, `publication_changed` (с опубликованными полями и `consent_id` за ними), `publication_closed`, `search_status_confirmed`, `search_status_cleared`, `organization_hidden` и `organization_unhidden` (с текущим названием организации). Это доказательство набора опубликованных полей и его изменений со временем, которого нет в записи C2. Отзыв C2 и истечение статуса вычисляются и событиями не являются; отзыв показывает история согласий. Значений профиля в истории нет.
|
||||
- `ListMyCardAccessHistory` возвращает обращения организаций к карточке: `card_viewed` и `contact_read`. У просмотра организацией, не связанной с кандидатом приглашением, `organization` равно null; чтение контактов всегда называет организацию. Записи не несут запроса или ранга. Хранение для них придет с задачами поиска и чтения контактов, поэтому операция только в контракте.
|
||||
|
||||
Открытые вопросы к владельцу продукта и юристу:
|
||||
|
||||
- Значения статуса поиска: в контракте `looking` и `not_looking`. Нужен ли по PRD третий статус, например "открыт к предложениям", не решено; значение - аддитивное изменение.
|
||||
- Влияет ли `looking` на появление опубликованной карточки в поиске (организация видит только ищущих) или это только метка. Это определяет смысл истечения для видимости и относится к контракту поиска.
|
||||
- Набор полей карточки. Шесть значений - предложение, согласованное с профилем; карточка в PRD (FR11) может добавить, разделить или убрать часть, например обобщенную отрасль и размер работодателя вместо работодателей, и каждое изменение аддитивно для контракта.
|
||||
- Нужен ли для публикации минимум: хотя бы одна подтвержденная категория или сохраненный профиль. Контракт требует только одно поле карточки и действующую C2.
|
||||
- Должно ли сужение опубликованных полей, а не только закрытие публикации или скрытие организации, отзывать контактные разрешения. Контракт приглашений говорит, что любое изменение видимости после разрешения его отзывает; этот контракт отзывает только при закрытии и скрытии.
|
||||
- Как кандидат находит организацию, чтобы скрыть ее до любого приглашения. Контракт скрывает по идентификатору и отвечает 404 на организацию, которую кандидат не видит, поэтому заранее скрыть текущего работодателя можно только при поиске организаций для кандидата (по названию или домену), который сам должен быть защищен от перебора (минимальная длина запроса, лимит, только публичные данные). Без него скрытие работает только для организаций, которые уже написали кандидату.
|
||||
- Должен ли кандидат узнавать название организации, которая смотрела карточку без приглашения (`CardAccess.organization`), и сколько хранятся обращения.
|
||||
- Предел скрытых организаций (сейчас 1000) и срок хранения настроек и их истории вместе с доказательствами согласий (152-ФЗ, PRD 7.3). История ссылается на аккаунт с `ON DELETE CASCADE` под защитой двух триггеров: UPDATE запрещен всегда, а DELETE (и удаление аккаунта) запрещен, пока аккаунт подтвержден, как у журнала согласий; очистка неподтвержденных аккаунтов удаляет историю удаляемого аккаунта, а процедура удаления аккаунта расширит условие.
|
||||
- Свободный текст в карточке (теги стека, софт-скиллы, место) защищает только `CardTextLooksLikeContact`, который ошибается в сторону отбрасывания (Socket.io отбрасывается, а простая обфускация все же может пройти); для устранения остаточного риска построителю карточки еще нужна закрытая таксономия вместо свободного текста.
|
||||
- Является ли C2 согласием на распространение персональных данных по статье 10.1 152-ФЗ и нужна ли ей собственная область полей (см. Согласия); пока поля и времена хранит история.
|
||||
- Требует ли новая версия текста C2 повторного согласия кандидата для уже существующей публикации. Сейчас публикация действует, пока ее запись C2 не отозвана, поэтому более новая версия текста, которую кандидат не принимал, ее не закрывает.
|
||||
- Квазиидентификаторы и k-анонимность карточки: редкое сочетание места, стека и опыта может идентифицировать кандидата и без имени. Обобщение редких признаков и минимальный размер группы - критерии приемки построителя карточки; здесь контракт фиксирует только закрытый набор полей, правило "только подтвержденные значения" и отбрасывание свободного текста, похожего на контакт.
|
||||
- Хранение и право на удаление истории настроек. Записи о скрытии и снятии скрытия чувствительны (они говорят, каких работодателей кандидат избегает). История хранится как доказательства согласий и не удаляется, пока аккаунт подтвержден; может ли кандидат стереть ее, когда и как это согласуется с трехлетним хранением согласий (PRD 7.3) - открытый юридический вопрос. Процедура удаления аккаунта расширит условие удаления таблицы.
|
||||
|
||||
Новый код problem не добавляется. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation` и `TestPrivacyAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/privacy-contract.test.ts` - сгенерированные правила Zod, отсутствие согласия, времени, контакта и зарплаты в типах запросов и карточки и отсутствие настроек в файлах организации, приглашения, потребности, профиля и согласий.
|
||||
|
||||
### Доказательства навыков
|
||||
|
||||
Тег `evidence` описывает факты, которые подтвержденные оценки оставляют о навыках кандидата (FR06 в PRD). В нем две операции чтения; логика за ними реализована (см. [архитектуру](../docs/ru/ARCHITECTURE.md#доказательства-навыков)).
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Специфичные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/evidence` | `ListMyEvidence` | сессия | 200 `EvidenceFactList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` |
|
||||
| `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence` | `GetOrganizationCandidateEvidence` | сессия | 200 `OrganizationEvidence`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
|
||||
|
||||
Каждая операция также объявляет проблемный ответ `default`. Новых кодов проблем нет.
|
||||
|
||||
- Одно событие - один факт. `EvidenceFact` - это событие-источник; `skills` - теги этого события (непустое множество), поэтому второй тег не создает второй факт. `source` называет событие и неизменяемый результат (`event_id` и `result_id`, для оценки они равны, так как результат ключуется попыткой; кандидат открывает его через `GetMyAssessmentResult`).
|
||||
- Заявление не равно измерению. `kind` равен `claim` (доверие 0) или `measurement` (доверие 1-3). `EvidenceTrustLevel` - целое от 0 до 3; онлайн-оценка без надежного подтверждения личности имеет доверие 1 и повторами не растет. Сейчас создаются только измерения из оценок.
|
||||
- Что говорит факт, лежит в `result`: пройденный грейд, `basis` (`synthetic_demo`) и `calibration_status` (`uncalibrated`), поэтому кандидат не принимает демонстрационную категорию за проверенное измерение. Проекция для организации и предпросмотр тоже несут обе метки. В факте нет балла, ответа, задания, проваленной попытки и античит-данных; проваленная попытка, результат без проверенного источника категории и прогон `demo_express` фактов не создают.
|
||||
- `ListMyEvidence` возвращает только факты вызывающего, новые события первыми, включая скрытые (`visibility` `hidden`), с общим `limit` (1-100, по умолчанию 20) и непрозрачным `cursor`, привязанным к кандидату. Неверный или чужой курсор и `limit` вне диапазона дают 400; аккаунт работодателя получает 403.
|
||||
- `GetOrganizationCandidateEvidence` - раздел анонимной карточки. Он отвечает, только пока на тот же handle ответил бы `GetOrganizationCandidateCard` и карточка показывает хотя бы одну категорию; любой другой случай (неизвестный handle, handle другой организации, закрытая или отозванная публикация, скрытая организация, минимальная когорта, карточка без категорий) дает один и тот же 404, поэтому ответ не раскрывает то, чего не раскрывает карточка. На каждую категорию карточки возвращается один `OrganizationEvidenceFact`: самая ранняя видимая оценка, прошедшая ровно подтвержденный грейд, и только `skill`, `grade`, `trust`, `observed_year` (год, UTC), а также `basis` и `calibration_status` (`synthetic_demo`, `uncalibrated`; одинаковы для всех кандидатов, поэтому отпечатка не добавляют и сообщают, что факт - демонстрация). Более низкий грейд, пересдача, остальные теги, источник, основание, месяц и все идентификаторы остаются у кандидата; не более девяти фактов, по порядку навыков; скрытого факта нет. Ключа, который привязывает ответ к человеку, нет, но он не является несвязываемым: вместе с другими значениями карточки навык, грейд, доверие и год могут сузить малый пул, а минимальная когорта год не покрывает. Чтение расходует квоту просмотров карточек и попадает в историю доступа с полем `categories`.
|
||||
- Предпросмотр. `CardPreview.evidence` - тот же раздел, посчитанный для кандидата (`OrganizationEvidence`, либо null ровно тогда, когда `card` равен null), поэтому кандидат видит, что организация прочтет вместе с полем `categories`. Организация и когорта не применяются, так что организация может получить меньше.
|
||||
- Закрытые схемы и обход приватности. У каждого объекта доказательств `additionalProperties: false`, и все его свойства обязательны. `TestNoOrganizationOperationReachesRawAssessmentData` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и `ListMyEvidence` по всем ссылкам и падают на схеме оценки, сигнала или проверки и на свойстве с сырым ответом, баллом или провалом.
|
||||
|
||||
Открытые вопросы: нужна ли новая версия текста согласия C2, раз публикация `categories` теперь отправляет организации еще один подтверждающий факт оценки (навык, грейд, уровень доверия, год) - решение владельца продукта и юриста, тексты согласий здесь не меняются; нужно ли доказательствам собственное поле карточки вместо поля `categories`; подходит ли работодателю точность в один год; операция скрыть или показать факт для кандидата (сохраненная видимость есть, операции для ее изменения нет); когда в список добавятся заявления профиля и факты из других источников.
|
||||
|
||||
### Подбор
|
||||
|
||||
В теге `organization` одна операция поиска по банку кандидатов, видимому организации (PRD FR09). Она реализована как детерминированный поиск без ML; модель, группы и читаемые данные описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение).
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Специфичные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | сессия, CSRF, `Origin`, действующий владелец | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` |
|
||||
|
||||
Операция ничего не меняет и не требует Idempotency-Key; `POST` нужен для тела. Ответ 200 также не объявляет 429.
|
||||
|
||||
- Доступ. Организация берется из пути и действующего членства владельца аккаунта сессии. Отсутствие сессии дает 401; аккаунт кандидата, участник не владелец, отсутствие CSRF-токена и чужой `Origin` дают 403; неизвестная организация, организация без действующего членства, потребность другой организации, неизвестная потребность и `requirements_version`, которую не создавало изменение подтвержденных требований, дают 404. Скрытые профили, отозванная или отсутствующая публикация C2, скрытие именно этой организации и минимальная когорта карточки применяются до появления любой записи: handle в результате - это handle, который `GetOrganizationCandidateCard` открывает в тот же момент.
|
||||
- Основание. `MatchSearchByNeed` ищет по неизменяемому снимку `requirements_version` (не по общей `version`), необязательные `filters` сужают его; `MatchSearchByBank` ищет по всем записям, видимым организации, с явными фильтрами. `source` в ответе повторяет основание: ссылку на потребность либо фильтры банка, где присутствует каждый ключ, а неотправленный фильтр равен null (стек отсортирован).
|
||||
- Записи. Каждая запись - одна специализация кандидата под организационным `candidate_handle`. В `main` и `near` лежат подтвержденные категории (`near`, если обязательный навык запроса дает меньше 0.25), в `unconfirmed` - заявленные специализации, отсортированные по Fit, затем Coverage, затем по внутреннему идентификатору, который не возвращается. У неподтвержденной записи `category: null`, `strength: null` и только `fit` и `coverage`. Группы - не одна шкала, и один handle может быть подтвержден по одной специализации и не подтвержден по другой.
|
||||
- Основание категории. Каждая подтвержденная категория записи несет `basis` (`synthetic_demo` для демонстрационной категории). Организация видит демонстрацию как таковую, а не как стандартное подтверждение; поле обязательно в `MatchCategory`.
|
||||
- Нейтральные и неизвестные значения. Семантика - калиброванный косинус сохраненных векторов потребности и карточки, а без них 0.5 с `ml_unavailable`; `percentile` равен null с `cohort_below_30`, а T равен 0.5 (сопоставимой реальной когорты нет, демонстрационные результаты ее не образуют); домен, свежесть и своевременность равны 0.5 со своими признаками; соревновательный вклад равен 0 и не является ни штрафом, ни неизвестностью; неопубликованное значение карточки - `null` в `public_context` с `not_in_public_card`.
|
||||
- Поиск оплачивается как чтение карточек, потому что запись несет содержимое карточки. Ранжируется весь видимый банк, а каждая группа возвращает не более `max_results_per_group` записей версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 просмотров в сутки для уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат считается одним уникальным просмотром карточки организации (то же резервирование, что у `GetOrganizationCandidateCard`: кандидат, уже просмотренный в окне, второй раз ничего не стоит, и повтор поиска или последующее открытие карточки не списывает дважды) и получает по одной записи `card_viewed` в истории доступа за поиск с фактически возвращенными полями. Когда лимит заканчивается, возвращаются уже оплаченные записи с `truncated: true`, для остальных ничего не пишется, ошибка и новый код проблемы не возвращаются. `truncated` также истинно, когда группа превысила предел, и никогда не несет число. В ответе `truncated` обязателен.
|
||||
- Ни в одной записи нет контакта, локации кандидата, суммы или минимума зарплаты, сырого ответа, проваленной попытки и причины скрытых данных; объяснение использует только ограниченные значения `MatchEvidenceCode` и `MatchEvidenceState`.
|
||||
- `semantic_evidence` (до 12, по умолчанию 6) объясняет поиск по потребности: требование потребности, ближайший элемент опубликованной карточки (`project`, `stack`, `roles`), полоса `high` или `medium` и `repository_verified`. Проект назван только опубликованным названием (поле карточки `projects`), без адреса и владельца репозитория; текст модели в объяснение не входит ([архитектура](../docs/ru/ARCHITECTURE.md#семантический-слой-и-объяснения)). Развертывание, действующая политика которого не содержит раздела `matching`, отвечает внутренней ошибкой и не ранжирует по умолчаниям.
|
||||
|
||||
Принятые остаточные риски: `truncated` - один бит о размере видимого банка, и время ответа растет вместе с ним; оба ограничены пределом группы и не несут числа. Когда реальная сопоставимая когорта категории достигает минимума политики, перцентиль все равно null с причиной `percentile_not_computed`, и поиск не падает. Изменение видимой когорты во время поиска повторяет его до трех раз; два одновременных поиска одной организации сериализуются ее блокировкой квоты.
|
||||
|
||||
Открытые вопросы: демонстрационное значение 10 для `max_results_per_group` и нужна ли постраничная выдача сверх него; должен ли поиск списывать кандидата за краткую запись по цене полного просмотра карточки; должен ли грейд потребности быть неявным фильтром или только объяснением; должны ли значения PRD оставлять онлайн-результат Backend (доверие 0.6 на широкую связь 0.4 дает 0.24) ниже порога близости 0.25, тогда как заявленный тег (0.25) его достигает, так что кандидат, у которого единственное доказательство нужной технологии - оценка специализации, всегда попадает для нее в `near`; должен ли фильтр `stack` требовать каждый тег (как реализовано) или любой; и является ли демонстрационная связь специализаций с технологиями (Backend над Go, PostgreSQL, Kafka и Docker; DevOps над Docker) таксономией, которую хочет владелец продукта.
|
||||
|
||||
### Уведомления
|
||||
|
||||
Тег `notification` описывает внутренний inbox текущего аккаунта в кабинете кандидата и в кабинете одной организации. В нем четыре операции; логика за ними реализована, но настоящие уведомления пока не создает ни один продуктовый модуль (см. [архитектуру](../docs/ru/ARCHITECTURE.md#внутренние-уведомления)).
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Специфичные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/notifications` | `ListMyNotifications` | сессия | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (аккаунт работодателя) |
|
||||
| `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | сессия и CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
|
||||
| `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | сессия | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (аккаунт кандидата) или `email_not_verified`, 404 `not_found` |
|
||||
| `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | сессия и CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
|
||||
|
||||
Каждая операция также объявляет проблемный ответ `default`. Новый код problem не добавляется.
|
||||
|
||||
- Inbox - состояние доставки внутри платформы. Элемент существует, как только событие дошло до платформы, независимо от того, отправлено ли письмо, и неудачное или отсутствующее письмо его не блокирует. Повторная доставка того же события - тот же элемент (`id` - идентификатор события).
|
||||
- Inbox хранит ссылки, а не текст. `content` вычисляется из текущего источника для получателя при каждом чтении и равен `null`, когда источника нет или получатель сейчас не вправе его видеть (например, кандидат скрыл организацию); элемент остается в списке, его можно отметить, а клиент показывает общую строку и никогда не показывает прежнюю копию. `content.link_path` - абсолютный путь того же origin (`^/[A-Za-z0-9/_-]{0,255}$`) или `null`.
|
||||
- Получатель - аккаунт сессии. Маршрут организации дополнительно требует активное членство любой роли в `org_id` и показывает только элементы вызывающего в этой организации. Кандидат на маршруте организации и работодатель на маршруте кандидата получают 403 `forbidden`, а работодатель с неподтвержденной почтой на маршруте организации - 403 `email_not_verified`. Нет членства, неизвестная организация, элемент другого аккаунта или другой организации и неизвестный идентификатор дают один и тот же 404 `not_found`, поэтому идентификаторы нельзя перебирать.
|
||||
- Пагинация использует общие `limit` (1-100, по умолчанию 20) и `cursor`, новые доставки первыми, идентификатор разрешает равенство. Курсор привязан к аккаунту и кабинету; курсор другого аккаунта или кабинета дает 400.
|
||||
- Отметка идемпотентна по эффекту и не требует Idempotency-Key: первое время прочтения сохраняется, и каждый повтор возвращает его. Она не читает источник и не возвращает содержимое. `kind` равен `invitation_delivered` (пока его не создает ни один модуль) или `synthetic` (уведомление без продуктового смысла, которое проверяет путь).
|
||||
- Закрытые схемы и проверки. У каждого объекта уведомлений `additionalProperties: false`, и все свойства обязательны. `TestNotificationOperationsFollowTheConventions` и `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) проверяют тег, защиту чтений и отметок, статусы, no-store, параметры и то, что у элемента нет текста, названия и контакта вне `content`.
|
||||
|
||||
### Проверки генераторов
|
||||
|
||||
`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core.
|
||||
|
||||
`make -C api check-toolchain` проверяет фикстуру линтером и запускает на ней три генератора; нужны Go toolchain backend, pnpm и uv, поэтому передавайте тот же `UV` override, что и для `make generate`.
|
||||
|
||||
| Target | Генератор | Проверяемые соглашения |
|
||||
| --- | --- | --- |
|
||||
| `make -C backend check-ogen-compat` | ogen | Все: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Тесты проверяют ошибки валидации, сценарий повтора, предусловия и лимит тела 413 вместе с backend-маппингом problem |
|
||||
| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. Результат проходит проверку типов с настройками компилятора frontend |
|
||||
| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. Модели проходят `mypy --strict` и скрипт валидации |
|
||||
|
||||
Каждый target пишет результат во временный каталог и удаляет его.
|
||||
|
||||
Известные ограничения генераторов:
|
||||
|
||||
- Orval 8.40 не создает Zod-схемы для `components/responses`, но импортирует тип `<Name>Response` для каждой ссылки. Поэтому `frontend/codegen/orval.config.ts` встраивает ссылки на ответы перед генерацией.
|
||||
- Orval передает header-параметры типизированным аргументом только с `headers: true`. С `exactOptionalPropertyTypes` необязательный заголовок, например `If-Match`, совместим с `RequestInit` только при точных необязательных свойствах Zod, поэтому конфигурация также задает `override.zod.exactOptional`.
|
||||
- Orval не генерирует типы заголовков ответа, а `apiRequest` возвращает только тело, поэтому сгенерированный клиент пока не может прочитать `ETag`. Первая операция с версионируемым ресурсом должна открыть его, например через тело ответа или mutator.
|
||||
- datamodel-code-generator 0.83.0 создает модели только для схем и query- и path-параметров; header-параметры и заголовки ответа (Idempotency-Key, If-Match, ETag) не дают Python-моделей.
|
||||
- Orval не генерирует методы для `additionalOperations`.
|
||||
- ogen записывает имя заголовка в канонической Go-форме (`Etag`); имена HTTP-заголовков не зависят от регистра.
|
||||
- ogen требует `SecurityHandler`, как только в контракте есть схемы защиты, и проверяет схемы в порядке имен их сгенерированных типов, поэтому переименование схемы может изменить порядок; тогда `TestGeneratedServerSecurityOrder` упадет. Сбои защиты попадают в `NewError` без заголовков ответа, поэтому удаление cookie при 401 от `Logout` требует ручного кода.
|
||||
- Orval не делает значения схем защиты типизированными аргументами, поэтому `X-CSRF-Token` не является сгенерированным параметром; его планируется добавлять к изменяющим запросам в общем API-клиенте. Тип для `Set-Cookie` Orval тоже не генерирует, этот заголовок обрабатывает браузер.
|
||||
- Zod-схемы Orval игнорируют `uniqueItems` и не отклоняют неизвестные поля объектов с `additionalProperties: false`; в обоих случаях решает сервер.
|
||||
- ogen генерирует необязательное nullable-поле как `OptNil<T>`, которое различает отсутствие (`IsSet` false), null (`IsNull`) и значение. Необязательный массив без null, напротив, - обычный slice, где nil и `[]` значат разное: отсутствующее поле декодируется в nil (без изменений), `[]` - в пустой slice, не равный nil (удалить все элементы), а null не декодируется. Поэтому обработчик `UpdateOrganizationNeed` должен проверять списки через `!= nil`, а не через `len`; это закрепляет `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart`.
|
||||
- Orval очищает `src/shared/api/endpoints/` и `src/shared/api/schemas/` перед генерацией (`clean: true`), потому что схема, используемая несколькими тегами, переезжает из каталога тега в корень схем.
|
||||
- Шаг после Orval `frontend/codegen/mock-patterns.ts` ищет границы длины строки с pattern по имени свойства и pattern, поэтому два свойства с одинаковыми именем и pattern должны иметь одинаковые границы. Поэтому технологии в условиях приглашения называются `tech_stack` (`SkillName`, до 100 символов) рядом с `stack` анкеты (`StackTag`, до 50), а условие пакета передает `description`, а не `value`, которое решения потребности используют с другими границами.
|
||||
|
||||
#### Объединения форматов
|
||||
|
||||
- Объединения форматов, например `ItemContent` и `AssessmentAnswer`, - это `oneOf` без объекта `discriminator`. Redocly разрешает значения `discriminator.mapping` как ссылки, а `scripts/merge-schemas.py` переписывает только `$ref`, поэтому mapping из отдельного файла схем не разрешается в объединенном `components/schemas.yml`. Каждый вариант фиксирует `format` перечислением из одного значения; ogen различает варианты по этому значению и по полям, уникальным для варианта, и отклоняет тело, подходящее под несколько вариантов, а Orval генерирует Zod-объединение.
|
||||
- Orval называет константы встроенного свойства `<Schema><Property>`, поэтому имя свойства, повторяющее имя другой схемы, дает конфликт в `index.ts` (TS2308). Поэтому объединение форматов задания называется `ItemContent`, а не `AssessmentItemContent`, рядом со свойством `AssessmentItem.content`, а части `Need` называются `NeedRequirementSet`, `NeedReadinessReport` и `NeedCategoryRecommendations`, а не `NeedRequirements`, `NeedReadiness` и `NeedRecommendations`. Срок ответа обращения называется `SupportResponseTarget`, а не `SupportCaseResponseTarget`, рядом со свойством `SupportCase.response_target`.
|
||||
|
||||
Сгенерированный Zod не строгий. Тело, смешивающее поля двух форматов или содержащее лишние `score` или `seed`, принимается после молчаливого удаления неизвестных ключей, а `uniqueItems` не проверяется; такие тела отклоняет только сервер. `frontend/src/shared/api/assessment-contract.test.ts` закрепляет принимаемые форматы и отсутствие в DTO ответа и задания полей балла, ключа, seed или правильности.
|
||||
|
||||
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
|
||||
Процесс изменения контрактов: [DEVELOPMENT.md](../docs/ru/DEVELOPMENT.md). Проверки: [TESTING.md](../docs/ru/TESTING.md).
|
||||
@@ -1,5 +1,5 @@
|
||||
-- +goose Up
|
||||
-- TASK-089 adds separately chosen opt-in groups to the anonymous card. The
|
||||
-- Add separately chosen opt-in groups to the anonymous card. The
|
||||
-- publication and event constraints call this function, so replacing it
|
||||
-- changes the accepted contract without rewriting any saved field set.
|
||||
-- +goose StatementBegin
|
||||
|
||||
+12
-38
@@ -1,42 +1,16 @@
|
||||
# Assessment demo bundle status
|
||||
# Assessment demo bundle
|
||||
|
||||
`backend_demo_bundle.json` is the input of the assessment bank loader
|
||||
(`internal/usecase/assessment`) for the category `backend`. It holds four
|
||||
families of original practice problems with deterministic seed generators,
|
||||
reference solutions, and rubrics.
|
||||
`backend_demo_bundle.json` contains four draft families for testing the assessment
|
||||
bank loader. Each has a deterministic generator, reference solution, and rubric.
|
||||
|
||||
## Status: AI-generated draft, pending human review
|
||||
The bundle records its author and a pending review. Keep those provenance fields
|
||||
accurate: the content has not received independent human review or difficulty
|
||||
calibration. Importing it creates drafts; publication requires an approved review
|
||||
by someone other than the author. This fixture alone cannot open a category.
|
||||
|
||||
- Author: `ai:claude-draft`. The problems were written by an AI assistant for
|
||||
the loader task; they are not copies or paraphrases of problems from any
|
||||
coding-practice site.
|
||||
- Review: `pending`. The reviewer field is empty on purpose. No human has
|
||||
checked the statements, the reference solutions, the rubrics, or the
|
||||
difficulty. Do not fill the field to make the bundle pass.
|
||||
- Consequences, which the integration tests rely on:
|
||||
- The loader imports every family as a `draft`.
|
||||
- A family without a reviewer cannot be published
|
||||
(`reviewer_missing`).
|
||||
- The category `backend` cannot be opened: it has no published family, and
|
||||
four families are below the coverage that the grading policy requires.
|
||||
- The bundle makes no claim about difficulty, validity, or grade
|
||||
calibration.
|
||||
Category opening also requires a separate versioned grading policy and sufficient
|
||||
published coverage. The fixture's rubrics do not supply grade thresholds.
|
||||
|
||||
## What the bundle does not contain
|
||||
|
||||
- No grading policy. A category opens only under a versioned grading policy
|
||||
that is referenced by `policy_versions.id` when the category is opened. The
|
||||
rubrics list criteria without points or thresholds.
|
||||
- No reviewer. A real review produces a new bundle version in which the
|
||||
family versions carry an approved review by an operator who is not the
|
||||
author; stored versions are never edited.
|
||||
|
||||
## Format
|
||||
|
||||
Documented by the types `assessment.Bundle` and `domain.AssessmentFamily`.
|
||||
Seed algorithms are registered in `internal/domain/assessment_algorithms.go`
|
||||
under versioned names (`rate_limit_window.v1`, `dedup_window.v1`,
|
||||
`lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`); the statement
|
||||
templates use the parameter names and the data names of the chosen algorithm.
|
||||
A family can instead declare a `table` of variants with their answers in its
|
||||
`seed_generator`; this bundle uses only algorithms.
|
||||
The format is defined by `assessment.Bundle` and `domain.AssessmentFamily`.
|
||||
Generator implementations live in `internal/domain/assessment_algorithms.go`.
|
||||
Families may use algorithmic or table variants; this fixture uses algorithms.
|
||||
+21
-14
@@ -2,21 +2,28 @@
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
Configuration for running the application with Docker Compose and Nginx.
|
||||
Docker Compose, Nginx, and startup tools. Dockerfiles live in service directories; the shared `.env.example` is at the repository root.
|
||||
|
||||
- `docker/docker-compose.yml` starts the core stack with PostgreSQL, Redis, SeaweedFS, and Kafka.
|
||||
- `docker/docker-compose.ml.yml` and `docker/docker-compose.monitoring.yml` run ML and monitoring as separate projects.
|
||||
- `nginx/` configures frontend serving and API proxying.
|
||||
- `docker/docker-compose.e2e.yml` is an overlay used only by the browser suite: it removes the frontend host port and adds the Playwright runner.
|
||||
- `docker/docker-compose.release.yml`, `docker/docker-compose.demo.release.yml`, and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/<service>:<tag>` (the demo seed image included) and never pull them from a registry.
|
||||
- `docker/docker-compose.demo.yml` and `demo/` belong to the isolated demo stand with synthetic data: `make -C deploy demo-seed DEMO_MODE=isolated` starts and seeds it, `demo-reset` rebuilds it only when it holds no ordinary account, and `demo-down` stops it; see the [isolated demo stand](../docs/en/DEPLOY.md#isolated-demo-stand).
|
||||
- `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images.
|
||||
- `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel).
|
||||
- `labs/` holds the LXD layout of the app host for the isolated runner and the labs (`lxd-preseed.yaml`, `acls.sh`) and `runner-vm.sh`, which builds, updates, and checks the production runner VM: `make -C deploy runner-vm-up`, `runner-vm-a16`, and `runner-vm-check` on the app host, and `check-runner-vm` anywhere; see [the runner VM](../docs/en/DEPLOY.md#production-the-runner-vm).
|
||||
- `make -C deploy check-perimeter` checks the published ports, denied paths, limits, and the trusted peer of Nginx from the files; `make -C deploy perimeter-test` checks the same over HTTP on throwaway Nginx containers; see [Public perimeter and client address](../docs/en/DEPLOY.md#public-perimeter-and-client-address).
|
||||
| Directory | Purpose |
|
||||
| --- | --- |
|
||||
| `docker/` | Core stack and separate Compose files for ML, monitoring, demo, E2E, and the dev runner |
|
||||
| `nginx/` | SPA serving and API proxy to Go |
|
||||
| `edge/` | Public HTTPS proxy and private tunnel templates |
|
||||
| `labs/` | LXD networks, code runner VM, and labd systemd configuration |
|
||||
| `ml-gpu/` | ML on a GPU host through systemd |
|
||||
| `demo/`, `scripts/` | Synthetic data, checks, and release tooling |
|
||||
| `release/` | Local release manifests, excluded from Git |
|
||||
|
||||
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; `make -C deploy test-e2e-registration` enables a local Resend-compatible inbox only for registration browser tests. See [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite) for details.
|
||||
From the repository root:
|
||||
|
||||
`make -C deploy release-build`, `release-smoke`, `release-e2e`, and `release-manifest` build the release images with pinned base image digests, check them, and publish an immutable manifest to `deploy/release/<release-id>/`, which Git ignores; a new `RELEASE_ID` gives the next stage its own manifest. `make -C deploy release-manifest-check` scans the manifest for secrets and machine data, `release-manifest-verify` compares running containers with it, `release-up` restores the core stack and `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>` the demo stand from its exact images, and `release-clean` removes release images that no manifest retains. See the [release manifest](../docs/en/DEPLOY.md#release-manifest).
|
||||
```sh
|
||||
make -C deploy help
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
```
|
||||
|
||||
See the [deployment guide](../docs/en/DEPLOY.md).
|
||||
`config` validates examples; `up` requires a prepared `.env` and starts core only. ML and monitoring start separately; monitoring and local ML need the existing core network. `down` preserves volumes.
|
||||
|
||||
For a demonstration: `make -C deploy demo-seed DEMO_MODE=isolated`. For checks: `make -C deploy check`, `smoke`, or `test-e2e`. The latter two create and remove their own stands.
|
||||
|
||||
Secrets, HTTPS, runner, and release instructions: [DEPLOYMENT.md](../docs/en/DEPLOYMENT.md). Test scenarios: [TESTING.md](../docs/en/TESTING.md).
|
||||
+21
-14
@@ -2,21 +2,28 @@
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
Конфигурация запуска через Docker Compose и Nginx.
|
||||
Docker Compose, Nginx и инструменты запуска. Dockerfile лежат в каталогах сервисов, общий пример настроек - в `.env.example` в корне.
|
||||
|
||||
- `docker/docker-compose.yml` поднимает основной стек с PostgreSQL, Redis, SeaweedFS и Kafka.
|
||||
- `docker/docker-compose.ml.yml` и `docker/docker-compose.monitoring.yml` запускают ML и мониторинг отдельными проектами.
|
||||
- `nginx/` содержит конфигурацию раздачи frontend и проксирования API.
|
||||
- `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright.
|
||||
- `docker/docker-compose.release.yml`, `docker/docker-compose.demo.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/<service>:<tag>` (включая образ demo seed) без скачивания из registry.
|
||||
- `docker/docker-compose.demo.yml` и `demo/` относятся к изолированному демонстрационному стенду с синтетическими данными: `make -C deploy demo-seed DEMO_MODE=isolated` запускает и заполняет его, `demo-reset` пересоздает его, только если в нем нет обычных аккаунтов, а `demo-down` останавливает; см. [изолированный демонстрационный стенд](../docs/ru/DEPLOY.md#изолированный-демонстрационный-стенд).
|
||||
- `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска.
|
||||
- `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель).
|
||||
- `labs/` содержит раскладку LXD хоста приложения для изолированного исполнителя и лабораторий (`lxd-preseed.yaml`, `acls.sh`) и `runner-vm.sh`, который собирает, обновляет и проверяет production VM исполнителя: `make -C deploy runner-vm-up`, `runner-vm-a16` и `runner-vm-check` на хосте приложения и `check-runner-vm` где угодно; см. [VM исполнителя](../docs/ru/DEPLOY.md#production-vm-исполнителя).
|
||||
- `make -C deploy check-perimeter` проверяет по файлам опубликованные порты, запрещенные пути, лимиты и доверенного пира Nginx; `make -C deploy perimeter-test` проверяет то же по HTTP на одноразовых контейнерах Nginx; см. [Публичный периметр и адрес клиента](../docs/ru/DEPLOY.md#публичный-периметр-и-адрес-клиента).
|
||||
| Каталог | Назначение |
|
||||
| --- | --- |
|
||||
| `docker/` | Основной стек и отдельные Compose для ML, мониторинга, demo, E2E и dev-runner |
|
||||
| `nginx/` | Раздача SPA и проксирование API в Go |
|
||||
| `edge/` | Шаблоны публичного HTTPS-прокси и приватного туннеля |
|
||||
| `labs/` | LXD-сети, VM исполнителя кода и systemd-конфигурация labd |
|
||||
| `ml-gpu/` | Запуск ML на GPU-хосте через systemd |
|
||||
| `demo/`, `scripts/` | Синтетические данные, проверки и сборка выпуска |
|
||||
| `release/` | Локальные манифесты выпуска, вне Git |
|
||||
|
||||
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; `make -C deploy test-e2e-registration` включает локальный Resend-compatible inbox только для браузерных тестов регистрации. Подробности см. в [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
|
||||
Из корня репозитория:
|
||||
|
||||
`make -C deploy release-build`, `release-smoke`, `release-e2e` и `release-manifest` собирают образы выпуска с закрепленными digest базовых образов, проверяют их и публикуют неизменяемый манифест в `deploy/release/<release-id>/` (игнорируется Git); новый `RELEASE_ID` дает следующему этапу собственный манифест. `make -C deploy release-manifest-check` ищет в манифесте секреты и данные машины, `release-manifest-verify` сверяет с ним запущенные контейнеры, `release-up` восстанавливает основной стек, а `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>` - демонстрационный стенд из точных образов, и `release-clean` удаляет образы выпуска, которые не удерживает ни один манифест. См. [манифест выпуска](../docs/ru/DEPLOY.md#манифест-выпуска).
|
||||
```sh
|
||||
make -C deploy help
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
```
|
||||
|
||||
Подробнее: [развертывание](../docs/ru/DEPLOY.md).
|
||||
`config` проверяет примеры, `up` требует подготовленный `.env` и запускает только core. ML и мониторинг включаются отдельно; мониторинг и локальный ML требуют уже созданной сети core. `down` сохраняет тома.
|
||||
|
||||
Для демонстрации: `make -C deploy demo-seed DEMO_MODE=isolated`. Для проверок: `make -C deploy check`, `smoke` или `test-e2e`. Последние две цели создают и удаляют свои стенды.
|
||||
|
||||
Инструкции по секретам, HTTPS, runner и выпуску: [DEPLOYMENT.md](../docs/ru/DEPLOYMENT.md). Сценарии проверок: [TESTING.md](../docs/ru/TESTING.md).
|
||||
@@ -5,7 +5,7 @@
|
||||
# writable cgroup v2 tree inside the Docker Desktop VM, and it serves plain
|
||||
# HTTP on loopback. A privileged container on the core application host is
|
||||
# forbidden; production runs the runner image only inside its dedicated VM
|
||||
# with TLS and without these switches (see docs/en/DEPLOY.md).
|
||||
# with TLS and without these switches (see docs/en/DEPLOYMENT.md).
|
||||
#
|
||||
# Use it through make -C deploy runner-dev-up, which creates the local token
|
||||
# file named by RUNNER_DEV_TOKEN_FILE.
|
||||
|
||||
@@ -242,7 +242,7 @@ services:
|
||||
IDENTITY_SESSION_IDLE_TIMEOUT: ${IDENTITY_SESSION_IDLE_TIMEOUT:-24h}
|
||||
IDENTITY_SESSION_ABSOLUTE_LIFETIME: ${IDENTITY_SESSION_ABSOLUTE_LIFETIME:-168h}
|
||||
ASSESSMENT_DEMO_CATEGORIES_ENABLED: ${ASSESSMENT_DEMO_CATEGORIES_ENABLED:-false}
|
||||
# Semantic matching (see docs/en/DEPLOY.md#semantic-matching). Off by
|
||||
# Semantic matching (see docs/en/DEPLOYMENT.md#semantic-matching). Off by
|
||||
# default: searches then use the neutral Sem. When on, vector jobs call
|
||||
# the separate ML project, which joins this network as "ml".
|
||||
SEMANTIC_MATCHING_ENABLED: ${SEMANTIC_MATCHING_ENABLED:-false}
|
||||
@@ -259,7 +259,7 @@ services:
|
||||
GITHUB_TOKEN: ${GITHUB_TOKEN:-}
|
||||
GITHUB_TIMEOUT: ${GITHUB_TIMEOUT:-10s}
|
||||
REPOSITORY_CHECK_INTERVAL: ${REPOSITORY_CHECK_INTERVAL:-10m}
|
||||
# Own code runner (see docs/en/DEPLOY.md#code-runner-client). Off while
|
||||
# Own code runner (see docs/en/DEPLOYMENT.md#code-runner-client). Off while
|
||||
# CODE_RUNNER_URL is empty: practice then reports the runner as
|
||||
# unavailable and runs nothing. The token and the run key are secrets;
|
||||
# pass the CA inline (CODE_RUNNER_CA_PEM) or mount a file and set its
|
||||
@@ -294,7 +294,7 @@ services:
|
||||
expose:
|
||||
- "8080"
|
||||
- "9090"
|
||||
# Shutdown budget with the defaults (see docs/en/DEPLOY.md):
|
||||
# Shutdown budget with the defaults (see docs/en/DEPLOYMENT.md):
|
||||
# - in parallel: the HTTP shutdown (SHUTDOWN_TIMEOUT, 10s), the relay
|
||||
# pass (10s plus a 5s rollback), and each event consumer
|
||||
# (CONSUMER_SHUTDOWN_GRACE 5s, a 5s rollback, CONSUMER_COMMIT_TIMEOUT
|
||||
@@ -328,7 +328,7 @@ services:
|
||||
ipv4_address: ${APP_FRONTEND_IP:-172.29.79.10}
|
||||
ports:
|
||||
# Loopback by default. On the app host behind the edge proxy,
|
||||
# APP_HTTP_BIND is the tunnel address (see docs/en/DEPLOY.md); never
|
||||
# APP_HTTP_BIND is the tunnel address (see docs/en/DEPLOYMENT.md); never
|
||||
# set it to 0.0.0.0, because Docker publishing bypasses ufw.
|
||||
- "${APP_HTTP_BIND:-127.0.0.1}:${APP_HTTP_PORT:-8080}:8080"
|
||||
healthcheck:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# /etc/systemd/system/awg-quick@awg-lincodex.service.d/userspace.conf.
|
||||
#
|
||||
# The kernel module is not used: awg-quick falls back to the userspace
|
||||
# daemon, which is installed from a pinned build (see docs/en/DEPLOY.md).
|
||||
# daemon, which is installed from a pinned build (see docs/en/DEPLOYMENT.md).
|
||||
# The daemon is one process per interface and is not restarted by systemd
|
||||
# on its own; check the handshake with `awg show` after incidents.
|
||||
[Service]
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Creates the network ACLs referenced by lxd-preseed.yaml (TASK-592).
|
||||
# Creates the network ACLs referenced by lxd-preseed.yaml.
|
||||
# Run before the preseed. Rules are stateful: replies to allowed traffic pass.
|
||||
set -euo pipefail
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# LXD host layout for the isolated runner and the practical labs (TASK-592).
|
||||
# LXD host layout for the isolated runner and the practical labs.
|
||||
# Applied once on the app host with: lxd init --preseed < lxd-preseed.yaml
|
||||
# It only adds objects; it does not touch Docker, wg0 or the awg-lincodex tunnel.
|
||||
storage_pools:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# systemd user unit of the ML service on a GPU host without Docker. Install it
|
||||
# as ~/.config/systemd/user/lincodex-ml.service of the service user (with
|
||||
# lingering enabled) and keep the settings and the token in the environment
|
||||
# file, mode 600; see docs/en/DEPLOY.md#ml-service-on-a-gpu-host.
|
||||
# file, mode 600; see docs/en/DEPLOYMENT.md#ml-service-on-a-gpu-host.
|
||||
#
|
||||
# %h is the home directory of the user: the layout below is
|
||||
# %h/lincodex-ml/app/ml the ml/ directory of the release
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
ML_EMBEDDER=giga,qwen3
|
||||
ML_DEVICE=cuda
|
||||
# float16 fits both models in about 2.4 GiB of VRAM; see the precision note in
|
||||
# docs/en/DEPLOY.md#ml-service-on-a-gpu-host before changing it.
|
||||
# docs/en/DEPLOYMENT.md#ml-service-on-a-gpu-host before changing it.
|
||||
ML_DTYPE=float16
|
||||
# Allocator cap of the process; the CUDA context adds about 130 MiB.
|
||||
ML_CUDA_MEMORY_LIMIT_MB=2300
|
||||
|
||||
+2
-3
@@ -4,11 +4,10 @@
|
||||
|
||||
Guides to the project's structure and development workflow. Russian documents live in `ru/`, with English translations in `en/`.
|
||||
|
||||
- [ARCHITECTURE](en/ARCHITECTURE.md) covers service boundaries, layers, and planned product workflows.
|
||||
- [ARCHITECTURE](en/ARCHITECTURE.md) covers components, data flows, and implementation boundaries.
|
||||
- [DEVELOPMENT](en/DEVELOPMENT.md) covers project structure, code generation, and development rules.
|
||||
- [DEPLOY](en/DEPLOY.md) covers the MVP quick start and the demo stand, startup, environment settings, and monitoring.
|
||||
- [DEPLOYMENT](en/DEPLOYMENT.md) covers the MVP quick start and the demo stand, startup, environment settings, and monitoring.
|
||||
- [TESTING](en/TESTING.md) describes test types, commands, and check boundaries.
|
||||
- [SECURITY](en/SECURITY.md) describes scanners, reports, and security exceptions.
|
||||
- [MVP](en/MVP.md) is the submission package of the minimal release: what is implemented, how to run it, limits, what is not implemented, and checks.
|
||||
|
||||
Update both language versions together. From the repository root, `make docs-check` checks documentation structure and local links. Source requirements and brand assets live in [requirements/](../requirements/README.en.md).
|
||||
+2
-3
@@ -4,11 +4,10 @@
|
||||
|
||||
Руководства по устройству проекта и работе с ним. Русские документы находятся в `ru/`, английские переводы - в `en/`.
|
||||
|
||||
- [ARCHITECTURE](ru/ARCHITECTURE.md) - границы сервисов, слои и запланированные продуктовые сценарии.
|
||||
- [ARCHITECTURE](ru/ARCHITECTURE.md) - компоненты, потоки данных и границы реализации.
|
||||
- [DEVELOPMENT](ru/DEVELOPMENT.md) - структура проекта, кодогенерация и правила разработки.
|
||||
- [DEPLOY](ru/DEPLOY.md) - быстрый старт MVP и демонстрационный стенд, запуск, настройки окружения и мониторинг.
|
||||
- [DEPLOYMENT](ru/DEPLOYMENT.md) - быстрый старт MVP и демонстрационный стенд, запуск, настройки окружения и мониторинг.
|
||||
- [TESTING](ru/TESTING.md) - виды тестов, команды и границы проверок.
|
||||
- [SECURITY](ru/SECURITY.md) - сканеры, отчеты и исключения безопасности.
|
||||
- [MVP](ru/MVP.md) - пакет сдачи минимального выпуска: что реализовано, запуск, ограничения, нереализованное и проверки.
|
||||
|
||||
Обе языковые версии обновляются вместе. Из корня репозитория: `make docs-check` проверяет структуру документации и локальные ссылки. Исходные ТЗ и брендбук находятся в [requirements/](../requirements/README.md).
|
||||
+103
-1283
File diff suppressed because it is too large.
Load diff
@@ -1,47 +0,0 @@
|
||||
# Company quotas
|
||||
|
||||
Company quota reservations are implemented in the domain, `companyquota` usecase, and PostgreSQL adapter. They provide a transaction-bound storage port for invitation and candidate-card usage. An invitation spends one place of the weekly quota when it is sent (`SendOrganizationInvitation`): a draft spends nothing, and a repeat of the send of the same invitation does not spend a second place. An invitation that leaves the waiting state (a decline, an expiry, an acceptance) frees its place in the per-need pending limit, but never returns the weekly quota; see [Pending limit, cooldown, and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry).
|
||||
|
||||
## Policy and trusted organization level
|
||||
|
||||
Each operation takes one UTC application-clock snapshot and reads the effective version of `ProductPolicyKey`. Limits come from that versioned policy. The bundled demo policy currently enables E0 at 10 invitations per rolling 7 days and 50 distinct candidate-card views per rolling 24 hours. E1 is 40 invitations per 7 days and 150 distinct views per 24 hours.
|
||||
|
||||
E2 has configured limits of 100 invitations and 400 distinct views, but its tier is inactive in the bundled demo policy. E2 can be used only when an effective policy activates it and the organization loaded from storage has the corresponding verified level and basis. E3 has no quota tier and is denied. The caller cannot choose or raise a tier.
|
||||
|
||||
The quota snapshot captures the policy version and the stored organization verification level, basis, and change time. Before writing, the PostgreSQL adapter locks the organization and checks those values and the effective policy version again. If either changed, it returns `outbound.ErrCompanyQuotaSnapshotChanged` without writing usage. The caller must reload policy and organization state, then retry the whole transaction.
|
||||
|
||||
## Reservation and transaction order
|
||||
|
||||
Call `companyquota.Service.ReserveInvitation` or `ReserveCardView` with repositories from the current `outbound.UnitOfWork`. The repository returned by `UnitOfWork.CompanyQuotas()` is transaction-scoped and must not be retained. Make the quota reservation and its eventual business change in the same transaction so rollback removes both. The service is constructed with the application clock and reads the effective policy once per operation.
|
||||
|
||||
Tenant authorization remains the caller's responsibility. Recheck active membership and owner permission inside the same transaction. Writers follow this order: organization, then for an E0 organization its holding (see [Holding pool](#holding-pool)), active membership, invitation or visibility record, then quota usage. The quota adapter locks the organization row first and, for an E0 organization, the holding row right after it; a caller that already holds those rows may lock them again in the same transaction. Do not reverse this order.
|
||||
|
||||
The organization lock serializes concurrent reservations of one organization, and the holding lock serializes the shared E0 pool. The adapter checks existing usage, counts the active window, and inserts or refreshes usage while those locks are held. A decision is either allowed or denied; reuse implies allowed. A denied reservation writes no usage and includes `RetryAt`, the earliest active usage expiry that can free capacity.
|
||||
|
||||
## Windows and retries
|
||||
|
||||
An invitation is keyed by `(organization_id, invitation_id)`. Repeating the same invitation ID is allowed as reused, even with a different request idempotency key and after the rolling window. Its usage evidence remains for the organization's lifetime, so removing an invitation in a future workflow will not refund quota.
|
||||
|
||||
A card view is keyed by `(organization_id, candidate_id)`, so viewing the same candidate again during the active window does not consume another distinct-view slot. The repeat refreshes `last_seen_at` monotonically: a backdated application clock cannot move the stored time backward.
|
||||
|
||||
The active-window query uses a strict comparison with the cutoff. A row exactly at `now - window` has expired. Invitation usage is counted over seven rolling days; card views are counted over 24 rolling hours. The limits apply across requests and users of the organization, except that an E0 organization shares its limits with the other E0 organizations of its holding (see [Holding pool](#holding-pool)).
|
||||
|
||||
Expired card-view rows are deleted in batches of at most 100 after a successful allowed reservation. Window expiry is logical; this cleanup does not promise deletion at an exact time. Deleting a candidate account cascades its card-view usage row. Deleting an organization cascades both quota tables. Invitation usage has no invitation foreign key, so future invitation withdrawal cannot erase its idempotency evidence.
|
||||
|
||||
## Holding pool
|
||||
|
||||
A holding groups the organizations that one founder account created; the `holdings` table and the migration `00041_create_holdings.sql` store it. `CreateWithOwner` stores each new organization in the holding of its owner account in the same transaction. The holding of an account is created with its first organization, and concurrent creations of one account end in one holding, because the insert ignores an existing founder key and the transaction then reads the stored holding. A holding carries no profile and no right; its only effect is the shared E0 pool.
|
||||
|
||||
The E0 limits (10 invitations per 7 days and 50 distinct card views per 24 hours in the bundled demo policy) are shared by the E0 organizations of a holding. An E0 reservation counts the usage rows of every organization of its holding whose trust level is E0 when the count runs. Each usage row stays attributed to the organization that consumed it, and usage of an organization that is no longer E0 leaves the shared pool. An organization at E1 or above counts only its own usage and keeps its own pool, so its usage does not count toward the E0 pool.
|
||||
|
||||
Idempotency stays per organization. The same invitation ID, or a repeated view of one candidate by the same organization inside the window, is not charged twice. The same candidate viewed by two organizations of one holding is two charges of the shared pool.
|
||||
|
||||
Locks: for an E0 organization, `CompanyQuotaRepository.LockOrganization` and each reservation take the holding row with `FOR NO KEY UPDATE` right after the organization row. Reservations of one pool therefore run one after another, and the second one counts the usage that the first one committed, because it counts only after the holding lock. Every writer takes the organization lock before the holding lock, and no code takes an organization lock while it holds a holding lock, so the holding lock adds no cycle to the documented order. The cost is that E0 searches, card reads, and invitation drafts or sends of one holding wait for one another while their transactions are open; a search holds the lock for its whole ranking transaction.
|
||||
|
||||
The migration gives each founder one holding: the founder of an organization is the account of its earliest membership, which is the creator's owner membership, and the holding is dated by its first organization. The rollback refuses while a holding groups several organizations, because the schema without holdings could not keep their E0 pool together. Merging holdings of different owners is out of scope.
|
||||
|
||||
## Verification
|
||||
|
||||
`TestHoldings` in `backend/integration_test/holding_test.go` covers the shared E0 pool of two organizations of one account with a verified organization apart, a second account's own holding, usage leaving the pool when its organization is raised, concurrent reservations from two organizations that never exceed the shared limits, concurrent creations ending in one holding, and a refused creation of an unknown founder. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` in `backend/integration_test/holding_migration_test.go` covers the backfill and the guarded rollback.
|
||||
|
||||
`TestCompanyQuota` in `backend/integration_test/company_quota_test.go` exercises the real PostgreSQL adapter in an isolated database. It checks concurrent E0 reservations, E0/E1 boundaries, exact window cutoffs and `RetryAt`, same-ID invitation reuse, cross-request card-view reuse, monotonic refresh, rollback, policy or organization snapshot changes, an allowed reservation with an active E2 policy and stored E2 verification, rejection of a forged E2 snapshot for a stored E0 company, inactive E2 and E3 denial, and candidate-deletion cleanup. It does not test a delivered invitation because that workflow is not implemented.
|
||||
-1047
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,276 @@
|
||||
# Running and deploying
|
||||
|
||||
Run commands from the repository root. Install Docker with Compose, GNU make, Python 3, and OpenSSL. Go operator commands need the toolchain from `backend/go.mod`; they read exported environment variables rather than loading `.env` automatically. Settings are described in [.env.example](../../.env.example); defaults and container environment bindings are in [deploy/Makefile](../../deploy/Makefile) and [Compose](../../deploy/docker/).
|
||||
|
||||
## Running the MVP: quick start
|
||||
|
||||
If `.env` does not exist, copy `.env.example`, replace `replace-this-*`, and set `IDENTITY_KEY_SECRET` to a random secret (`openssl rand -base64 48`). The PostgreSQL password is part of the connection URL, so use URL-safe characters such as hex. This file contains secrets and must stay out of Git.
|
||||
|
||||
```sh
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl --fail http://localhost:8080/api/v1/healthz
|
||||
```
|
||||
|
||||
`config` validates example settings; `up` reads the real `.env`. The `app` project starts frontend Nginx, the Go backend, PostgreSQL, Redis, SeaweedFS, and Kafka. The backend applies migrations on startup. An empty database has no question bank or prepared accounts; use the [demo stand](#isolated-demo-stand) to demonstrate the product.
|
||||
|
||||
| Component | Start | Default address |
|
||||
| --- | --- | --- |
|
||||
| Core | `make -C deploy up` | `http://localhost:8080` |
|
||||
| Synthetic demonstration | `make -C deploy demo-seed DEMO_MODE=isolated` | `http://localhost:8090` |
|
||||
| ML, after core | `make -C deploy ml-up` | `127.0.0.1:8000` |
|
||||
| Monitoring, after core | `make -C deploy monitoring-up` | Grafana: `127.0.0.1:3000` |
|
||||
| Development code runner | `make -C deploy runner-dev-up` | `127.0.0.1:8070` |
|
||||
|
||||
ML, monitoring, the runner, and labd do not start with core. Pass the same project name to every command, for example `APP_PROJECT=my-app` for `up`, `logs`, and `down`. Make does not read the project name from `.env`.
|
||||
|
||||
## Core service
|
||||
|
||||
`make -C deploy logs` follows logs. `make -C deploy down` preserves named volumes; stop monitoring before core. PostgreSQL, SeaweedFS, and Kafka persist data in volumes; Redis is a bounded cache without persistence. Removing volumes destroys their data. A single Compose host provides neither HA nor off-host backups.
|
||||
|
||||
### Public perimeter and client address
|
||||
|
||||
Frontend Nginx is the HTTP entry point, serving the SPA and `/api/v1/` on one origin. Open exactly `APP_PUBLIC_URL`; unsafe requests check Origin and, for sessions, a CSRF token. Use `localhost` for local HTTP and HTTPS for a public hostname: the session cookie has the `Secure` flag.
|
||||
|
||||
Keep `APP_HTTP_BIND=127.0.0.1` locally or use a private tunnel address. Do not publish the backend, `/metrics`, databases, broker, or storage. Docker port publishing can bypass ufw rules. `TRUSTED_PROXY_CIDRS` must trust only frontend Nginx; coordinate proxy addresses and ACLs when changing `APP_SUBNET` or `APP_FRONTEND_IP`.
|
||||
|
||||
### Outbox relay
|
||||
|
||||
The backend publishes outbox records to Kafka and runs event consumers and scheduled jobs in the same process. `RELAY_*`, `CONSUMER_*`, and `JOBS_*` settings live in [backend/config](../../backend/config/). Adding a variable to `.env` affects a container only if Compose explicitly passes it. Keep a margin in `stop_grace_period` when increasing shutdown timeouts.
|
||||
|
||||
### Event consumers
|
||||
|
||||
Watch outbox age, consumer errors, and due jobs in Grafana. Inspect dead letters in the database and Kafka lag through the broker CLI. Delivery permits retries; handlers deduplicate events. Changing `CONSUMER_GROUP_PREFIX` creates new groups that read retained events from the beginning.
|
||||
|
||||
#### Dead letters and replay
|
||||
|
||||
After fixing the cause, inspect the record in `consumer_dead_letters`. For a known `event_id`, republish its retained outbox row by clearing only that row's `published_at`; successful handlers recognize the duplicate. This does not repair an `invalid_record`. Stop all members of the affected group before manually resetting Kafka offsets. `consumer_processed_events` records successful processing; do not copy payloads or personal data into incident logs.
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
`scheduled_jobs` stores state and errors. After fixing the cause, retry only the affected job according to its handler; do not reset the entire queue. Synchronize backend clocks through NTP because deadlines and leases use application time. Practice uses a separate queue described below.
|
||||
|
||||
## Mail
|
||||
|
||||
| Mode | Requirements |
|
||||
| --- | --- |
|
||||
| `EMAIL_PROVIDER=disabled` | Sends nothing; a newly registered account remains unverified |
|
||||
| `EMAIL_PROVIDER=resend` | `RESEND_API_KEY`, `EMAIL_FROM` on a verified domain, and the correct `APP_PUBLIC_URL` |
|
||||
| `EMAIL_PROVIDER=smtp` | Configuration exists, but the transport is not implemented; backend startup fails |
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
Resend sends email confirmation and supported product notifications through the outbox. A transport failure is not a successful delivery. `make -C deploy test-e2e-registration` uses a local Resend-compatible inbox, not a real provider account.
|
||||
|
||||
### Mail quotas
|
||||
|
||||
`EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit recipients by UTC periods, defaulting to 100 and 3000. `EMAIL_SERVICE_RESERVE_*` reserve part of those limits for service mail. `EMAIL_ACCOUNT` identifies the actual provider account; do not rename it to bypass local accounting. Application defaults do not guarantee a provider plan or quota.
|
||||
|
||||
### Mail templates
|
||||
|
||||
Templates and rendering live in `backend/internal/usecase/notification/mailtemplate/`. Send only data the recipient needs; the one-time link and code belong in verification mail. Service keys and data the recipient may no longer access must not be included.
|
||||
|
||||
## Isolated demo stand
|
||||
|
||||
```sh
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
make -C deploy monitoring-up DEMO_MODE=isolated
|
||||
make -C deploy demo-down DEMO_MODE=isolated
|
||||
```
|
||||
|
||||
The seed creates a separate `lincodex-demo` project, bank, and synthetic accounts; repeated runs are idempotent. The local frontend is available at `http://localhost:8090`; you do not need to pass `APP_HTTP_BIND` on the command line. The target uses the root `.env` and `deploy/demo/demo.env`, falling back to the public example if the latter is absent. The command prints logins; `DEMO_ACCOUNT_PASSWORD` sets their password. For external access, choose your own password and share it separately with participants.
|
||||
|
||||
The guide is at `/demo`. Main accounts: `candidate@demo.lincodex.test`, `prepared-1@demo.lincodex.test` through `prepared-6@demo.lincodex.test`, `employer-alpha@demo.lincodex.test`, and `employer-beta@demo.lincodex.test`. Follow the candidate from assessment to result, then send an invitation as the employer and accept it as the candidate with selected contacts.
|
||||
|
||||
`demo-reset DEMO_MODE=isolated` deletes and reseeds only its project; it refuses to run when ordinary accounts exist. Do not use this stand for real people. Demo categories are uncalibrated, and the express run awards no grade. The official FSP integration is not connected.
|
||||
|
||||
### Demonstration scenario
|
||||
|
||||
1. Complete the candidate profile and questionnaire, take a test or open a prepared result. The Backend Junior bank with Go is synthetic; `demo_express` assigns neither a grade nor evidence.
|
||||
2. Grant C2 and publish the card after previewing it. Anonymous results need a sufficiently large group: one published candidate may not appear in search.
|
||||
3. As the company owner, create a hiring need with a salary range, find a candidate, open the explanation and send an invitation.
|
||||
4. Accept it as the candidate with C4 and selected contacts. Check that the company can read only those fields, then revoke access or hide the company and verify refusal.
|
||||
|
||||
The `synthetic_demo` category demonstrates mechanics, not established assessment quality. Built-in consent texts are marked `demo`. Practice requires a separate runner and a suitable bank, so do not present it as part of the ordinary demonstration test. See [ARCHITECTURE.md](ARCHITECTURE.md) for other implementation limits and [TESTING.md](TESTING.md) for acceptance.
|
||||
|
||||
The presentation slot is 10 minutes; video is allowed instead of a live demonstration. Rehearse with a timer and state limitations. Keep the stand available throughout evaluation where possible; exact dates and whether jury questions count within the ten minutes need confirmation.
|
||||
|
||||
### Demonstration categories on a stand
|
||||
|
||||
The seed prepares categories itself. Manual setup requires an open category with a published bank, a demo policy, `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, and operator attestation:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:maintainer'
|
||||
```
|
||||
|
||||
The command requires `DATABASE_URL`. Attestation binds the category opening, bank, and policy version; reopen and attest after changing them. Synthetic categories remain disabled in environments with real candidates.
|
||||
|
||||
### Match search policy on a stand
|
||||
|
||||
The initial policy on an empty stand has no `matching` section. Publish it before demonstrating search:
|
||||
|
||||
```sh
|
||||
make -C backend policy-publish ARGS='matching --actor operator:maintainer'
|
||||
```
|
||||
|
||||
The command requires `DATABASE_URL` and publishes the next demo version. The seed handles this preparation itself. A policy change requires reopening and attesting demo categories; attempts already started keep their previous version.
|
||||
|
||||
### Assessment review band
|
||||
|
||||
```sh
|
||||
make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operator:maintainer'
|
||||
```
|
||||
|
||||
The command requires `DATABASE_URL` and shows signals for manual review. They do not prove misconduct or automatically lower a score. The `operator:*` label is for auditing; database access remains the operator's access boundary.
|
||||
|
||||
### Leak trace
|
||||
|
||||
```sh
|
||||
make -C backend assessment-leak-trace ARGS='search --actor operator:maintainer --file leaked.txt'
|
||||
```
|
||||
|
||||
Set `DATABASE_URL` and the same `IDENTITY_KEY_SECRET` used when issuing attempts. Pass text in a file or through `--stdin` to keep it out of shell history. Results and audit records omit the original text; a match supports manual review rather than an automatic decision.
|
||||
|
||||
## Separate ML Compose project
|
||||
|
||||
ML serves Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B embeddings. Its image downloads pinned weights at build time, verifies SHA-256, and runs offline. Compose uses CPU with a limit of 4 CPUs and 8 GiB. The separate project joins the external core network as `ml`.
|
||||
|
||||
1. Set the same `ML_SERVICE_TOKEN` for ML and backend in `.env`: at least 32 printable characters without spaces.
|
||||
2. Start core, then run `make -C deploy ml-build` and `make -C deploy ml-up`.
|
||||
3. Wait for `/readyz` 200. `/healthz` checks the process, not model loading.
|
||||
|
||||
`ML_EMBEDDER=giga,qwen3` loads both models; `none` keeps the service unready, and `fake` is for fixtures. All routes except health/readiness require the configured bearer token. Without a token, the service permits only loopback clients and refuses to start the container listener on `0.0.0.0`. `ml-logs` and `ml-down` manage this project separately.
|
||||
|
||||
For development, run `make -C ml install`, `make -C ml model-fetch`, then `make -C ml run` with `ML_EMBEDDER` and model directories in the environment. `model-fetch` downloads about 2.2 GB of weights. `make -C ml test-model` tests real models separately from ordinary tests.
|
||||
|
||||
### ML service on a GPU host
|
||||
|
||||
Use the [systemd template](../../deploy/ml-gpu/lincodex-ml.service) and [example settings](../../deploy/ml-gpu/ml.env.example). The service expects code at `~/lincodex-ml/app/ml`, a virtualenv at `~/lincodex-ml/venv`, and settings in `~/.config/lincodex-ml/ml.env` with mode 0600. Use the Python version from `ml/.python-version`; `make -C ml cuda-requirements` prepares pinned dependencies with a CUDA torch build, which must be installed from the matching PyTorch index.
|
||||
|
||||
Prepare weights from the lock files; select a private address, `ML_DEVICE=cuda`, dtype, and `ML_CUDA_MEMORY_LIMIT_MB` for the host's resources. After installing the unit and configuring lingering, run `systemctl --user daemon-reload`, then `systemctl --user enable --now lincodex-ml.service`. Check `/readyz`, logs, and real model tests on the target device. Memory and latency measurements from another host are not guarantees for yours.
|
||||
|
||||
Restrict access to the backend address. The service does not terminate TLS; use a protected channel across an untrusted network. CUDA memory exhaustion returns 503 and retries loading; other persistent loading failures exit with `ML_EXIT_ON_LOAD_FAILURE=true` so the supervisor can restart the process.
|
||||
|
||||
### Semantic matching
|
||||
|
||||
Search reads precomputed vectors and does not invoke a model within the HTTP request.
|
||||
|
||||
1. Wait for ML readiness, set `SEMANTIC_MATCHING_ENABLED=true`, the shared token, and `ML_SERVICE_URL` (default `http://ml:8000`), then rerun `make -C deploy up`.
|
||||
2. With the stand's `DATABASE_URL`, run `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:maintainer'`. This policy needs both models; `semantic` uses Giga alone.
|
||||
3. Queue existing data: `make -C backend semantic-backfill ARGS='all --run initial'`. Repeating the same run label is idempotent; use a new label for another pass.
|
||||
|
||||
Reopen and attest demo categories after publishing a policy. Missing or incompatible vectors use neutral `Sem=0.5` with `ml_unavailable`. GitHub repository checks are enabled separately through `GITHUB_REPOSITORY_CHECKS_ENABLED`; they are not a requirement for ML startup.
|
||||
|
||||
## Separate monitoring Compose project
|
||||
|
||||
```sh
|
||||
make -C observability check
|
||||
make -C deploy monitoring-up
|
||||
make -C deploy monitoring-logs
|
||||
make -C deploy monitoring-down
|
||||
```
|
||||
|
||||
By default, the project joins the core network. After starting the demo, run `make -C deploy monitoring-up DEMO_MODE=isolated` to connect it to the `lincodex-demo` network. Grafana is bound to loopback; Prometheus, Loki, Alloy, and exporters remain internal. Dashboards cover Go, PostgreSQL, Redis, SeaweedFS, the host, and product metrics. Kafka has no dedicated scrape yet. The React telemetry SDK is not connected. Alert rules exist; notification delivery needs separate configuration.
|
||||
|
||||
Prometheus retains metrics for 14 days with a 4 GB cap; Loki retains logs for 7 days. Keep contacts, resumes, raw URLs, and user identifiers out of labels. Alloy accesses the Docker API through a restricted socket proxy; even read-only Docker API access can expose sensitive container configuration. Treat this component as privileged.
|
||||
|
||||
The PostgreSQL exporter role is created only on first initialization of an empty volume: set `POSTGRES_EXPORTER_USER` and `POSTGRES_EXPORTER_PASSWORD` beforehand. Provision the role separately for an existing database. `ML_METRICS_TARGET` adds a private target, but the current scrape template sends no bearer token; protected ML also requires Prometheus authorization configuration.
|
||||
|
||||
`make -C observability verify-product-metrics` starts disposable core and monitoring stacks, checks metrics and the absence of fixture personal data in telemetry, then removes them. This integration check is separate from `check`.
|
||||
|
||||
## Edge proxy, HTTPS and tunnel
|
||||
|
||||
Public requests follow browser -> edge HTTPS Nginx -> private AmneziaWG tunnel -> frontend Nginx -> Go. Templates and scripts live in [deploy/edge](../../deploy/edge/); core Compose does not terminate TLS.
|
||||
|
||||
1. Prepare `deploy/edge/edge.env` from the example: domain, dedicated `EDGE_LISTEN_IP`, tunnel addresses, and port. Check DNS, free listeners, and subnet overlap. Preserve existing sites and routes on a shared edge host.
|
||||
2. `make -C deploy edge-config` checks templates and runs containerized `nginx -t`; `edge-render` writes Nginx configuration into `deploy/edge/rendered/`. These targets install nothing on the host.
|
||||
3. On edge, install the HTTP configuration for ACME, obtain a certificate with certbot, then install the HTTPS configuration and [reload-nginx.sh](../../deploy/edge/certbot/reload-nginx.sh) hook. Run `nginx -t` before reload and test renewal with `certbot renew --dry-run`.
|
||||
4. Create tunnel keys through `deploy/edge/scripts/awg-keys.sh` and render each side through `render.sh --params`. Keep key files outside the repository, accessible only to root. Prepare AmneziaWG and the required systemd drop-ins on both hosts.
|
||||
5. On app, set `APP_HTTP_BIND` to its tunnel address and `APP_PUBLIC_URL=https://<domain>`. The firewall permits the core port only from edge; frontend trusts forwarded headers only from the edge address. Check both sides; Docker publishing does not replace a firewall.
|
||||
|
||||
Before opening access, check HTTPS and the certificate chain, HTTP redirects, SPA deep links, sign-in and CSRF, and denial of `/metrics` and administrative paths. Edge replaces forwarded headers instead of trusting client values. Run `make -C deploy check-perimeter` and `make -C deploy perimeter-test`; the latter starts disposable Nginx containers.
|
||||
|
||||
Keep previous configuration and certificates for rollback and validate them before reload. Do not remove unrelated interfaces, firewall rules, or sites. A successful template check does not prove public domain availability.
|
||||
|
||||
## Isolated runner and lab host (LXD)
|
||||
|
||||
LXD needs Linux with KVM, space for the btrfs pool, and operator privileges. Review [acls.sh](../../deploy/labs/acls.sh) and [lxd-preseed.yaml](../../deploy/labs/lxd-preseed.yaml) against the host's network, then apply ACLs before the preseed. The scripts create separate runner and lab-management bridges; guests use static addresses without NAT, DHCP, or DNS. Do not apply the layout over unrelated objects with the same names.
|
||||
|
||||
The backend never receives the LXD socket. The `lxd` group grants root-equivalent access; only the operator and labd receive it. Test guest isolation from core, the host, LAN, and the internet on the actual host; configuration alone does not prove it.
|
||||
|
||||
## Code runner
|
||||
|
||||
The `runner/` service executes Python and Go in nsjail with cgroup v2, seccomp, and limits. The supervisor needs isolation privileges; candidate code runs as an unprivileged user. Run history is in runner memory and is lost on restart.
|
||||
|
||||
### Local development only
|
||||
|
||||
`make -C deploy runner-dev-up` creates a token at `runner/.dev/api-token` and starts a separate privileged container with loopback HTTP. Stop it with `runner-dev-down`. This mode is forbidden on the core host and is excluded from release. The backend requires TLS and cannot connect directly to this HTTP mode.
|
||||
|
||||
### Production: the runner VM
|
||||
|
||||
Use a dedicated LXD VM with its own kernel and no core directory, Docker socket, application secrets, or default route. The network permits API connections only from the app network and host side, while denying guest-initiated connections. TLS 1.3 and a bearer token are required. nsjail needs delegated cgroup v2 and a work tmpfs with `exec,nosuid,nodev`.
|
||||
|
||||
### Steps of the VM script
|
||||
|
||||
On a prepared app host, as a member of the `docker` and `lxd` groups:
|
||||
|
||||
```sh
|
||||
make -C deploy runner-vm-up
|
||||
make -C runner a16-bundle
|
||||
make -C deploy runner-vm-a16 A16_BUNDLE=/path/to/a16-bundle.tar.gz
|
||||
make -C deploy runner-vm-check
|
||||
```
|
||||
|
||||
The A16 bundle can be built on a machine with Go and transferred to app. `runner-vm-up` prepares secrets, rootfs, VM, and service in sequence. Separate targets are `runner-vm-secrets`, `runner-vm-rootfs`, `runner-vm-create`, and `runner-vm-install`. Secrets and reports stay in `RUNNER_VM_STATE_DIR`, defaulting to `~/lincodex-runner`, outside the repository.
|
||||
|
||||
### Verification on the app host
|
||||
|
||||
Before enabling practice, pass A16 on the target VM and `runner-vm-check`: TLS, token, harmless programs, limits, cleanup, and network denial. A failure blocks practice activation. Repeat checks after changes to the kernel, runtime, or isolation settings. A passing run on an older release does not replace them.
|
||||
|
||||
### Code runner client
|
||||
|
||||
Set backend `CODE_RUNNER_URL` to HTTPS, `CODE_RUNNER_TOKEN`, a distinct `CODE_RUNNER_RUN_KEY`, and exactly one of `CODE_RUNNER_CA_FILE`/`CODE_RUNNER_CA_PEM`. Mount the CA file into the container yourself. Set `CODE_RUNNER_SERVER_NAME` if required; certificate verification stays enabled. `CODE_RUNNER_REQUEST_TIMEOUT` bounds each request.
|
||||
|
||||
Without a URL, all other `CODE_RUNNER_*` settings must be empty; practice reports unavailable. Invalid configuration prevents startup. `make -C backend test-code-runner-live` tests the client against a prepared TLS runner with `CODE_RUNNER_URL`, `CODE_RUNNER_TOKEN`, and `CODE_RUNNER_CA_FILE` from the environment; it does not replace A16.
|
||||
|
||||
### Practice queue and debug run limits
|
||||
|
||||
The backend already connects the practice handler and PostgreSQL queue when `DATABASE_URL` and a runner are configured. The queue allows one running and ten waiting jobs; Redis limits candidate debug requests. `PRACTICE_*` settings live in `backend/config/` but are not passed by ordinary Compose. Infrastructure failure ends without grading, not as a wrong answer; inspect the queue through `assessment_practice_jobs`.
|
||||
|
||||
## Labs and labd
|
||||
|
||||
labd runs as a systemd service on the app host and exclusively manages LXD. Use its [unit](../../deploy/labs/lincodex-labd.service) and [settings](../../deploy/labs/labd.env.example): TLS, token, allowed networks, state file, and memory budget. Preserve its state file with the LXD objects; it is needed to recover and delete labs.
|
||||
|
||||
The built-in template registry is currently empty, backend does not connect the labd adapter, and the WebSocket console returns 501. A usable workflow requires prepared images, templates, and integration. Before enabling it, verify L2 isolation, MAC/port filtering, cloud-init, and node authentication during checks. `make -C labd test-live` creates and deletes a lab on a separate test LXD with `LABD_LIVE_SOCKET` and `LABD_LIVE_SOURCE`; never run it against production.
|
||||
|
||||
## Release manifest
|
||||
|
||||
A reproducible release needs a clean working tree and passing checks of those exact images:
|
||||
|
||||
```sh
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-manifest-check RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-up RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-manifest-verify RELEASE_ID=demo-stage-1
|
||||
```
|
||||
|
||||
The manifest in `deploy/release/<id>/` records source, dependencies, Compose, image IDs/digests, and inputs. Each ID is immutable; a new delivery needs a new ID. These are local artifacts and stay out of Git. `RELEASE_DATA_MANIFEST` adds bank, policy, and seed versions; the absence of an accepted bank remains an explicit limitation rather than proof of product readiness.
|
||||
|
||||
`release-up` requires local images and matching files; it neither builds nor pulls them. For another project, use matching `APP_PROJECT` and `RELEASE_VERIFY_PROJECT`. Restore the demo with `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>`; stop core with `release-down` using the same ID. `release-clean` removes only image references not retained by manifests.
|
||||
|
||||
The manifest does not back up data or deploy edge, the GPU host, runner, or labd. Back up data and configuration before upgrades; rolling back an image does not undo migrations. Test recovery of PostgreSQL and SeaweedFS objects separately.
|
||||
|
||||
## Checks
|
||||
|
||||
| Command | Coverage |
|
||||
| --- | --- |
|
||||
| `make -C deploy check` | Compose and tooling checks without starting the stack |
|
||||
| `make -C deploy smoke` | Dependency health and network boundaries of a disposable stack |
|
||||
| `make -C frontend install`, then `make -C deploy test-e2e` | Browser scenarios on a disposable stack |
|
||||
| `make -C deploy test-e2e-registration` | Scenarios with a local mail fixture |
|
||||
| `make -C observability check` | Monitoring configuration and alert rules |
|
||||
|
||||
Test coverage and environment requirements are in [TESTING.md](TESTING.md). A passing health check does not confirm the complete business flow.
|
||||
+89
-229
@@ -1,251 +1,111 @@
|
||||
# Development
|
||||
|
||||
This guide describes implemented components and repository commands. Current business workflows are listed below; see [ARCHITECTURE.md](ARCHITECTURE.md) for the target design.
|
||||
[Русский](../ru/DEVELOPMENT.md)
|
||||
|
||||
## Stack and version sources
|
||||
Run commands below from the repository root. [ARCHITECTURE.md](ARCHITECTURE.md) explains the services, [DEPLOYMENT.md](DEPLOYMENT.md) covers the environment, and [TESTING.md](TESTING.md) covers checks.
|
||||
|
||||
| Component | Version source |
|
||||
## Tools
|
||||
|
||||
Use the versions declared by the build inputs:
|
||||
|
||||
| Tool | Source |
|
||||
| --- | --- |
|
||||
| Go | exact 1.26.9 in backend/go.mod, toolchain, and Go build image |
|
||||
| Node.js | frontend/.node-version |
|
||||
| Frontend dependencies | current stable releases in package manifests and pnpm-lock.yaml |
|
||||
| Python and uv | ML toolchain declarations and uv.lock |
|
||||
| Go | `backend/go.mod`, `runner/go.mod`, `labd/go.mod`, and their Dockerfiles |
|
||||
| Node.js | `frontend/.node-version` |
|
||||
| pnpm and frontend | `frontend/package.json`, `frontend/pnpm-lock.yaml` |
|
||||
| Python and uv | `ml/.python-version`, `ml/pyproject.toml`, `ml/uv.lock` |
|
||||
| Go generators | `tool` directives and dependencies in Go modules |
|
||||
| Containers | `deploy/docker/` and service Dockerfiles |
|
||||
|
||||
Select current stable frontend dependency releases and keep pnpm-lock.yaml committed for repeatable installs. ML dependencies are locked in uv.lock; Go dependencies are in backend/go.mod. An update must change its lock/configuration and pass checks for that service. Container images use the requested moving `latest` or `alpine` tags; inspect their current Compose/Dockerfile references instead of treating the tag as a fixed version.
|
||||
Container checks require Docker with the Compose plugin. The race detector needs a supported C toolchain. Keep lockfiles and test consumers when updating dependencies. Moving `latest` and `alpine` tags can change image content; a reproducible release pins digests.
|
||||
|
||||
## Implementation status
|
||||
```sh
|
||||
make install
|
||||
make help
|
||||
```
|
||||
|
||||
MVP implementation is ongoing. Values below are read from the named files; when updating a dependency, change its source and lockfile and update this table in both languages.
|
||||
`install` installs API, frontend, and ML dependencies and downloads backend, runner, and labd Go modules. It does not start services or install Docker or system compilers.
|
||||
|
||||
| Component | Pinned version | Source |
|
||||
| --- | --- | --- |
|
||||
| Go | 1.26.9 (`go` directive; no separate `toolchain` line) | backend/go.mod; build image `golang:1.26.9-alpine` in backend/Dockerfile |
|
||||
| Node.js | 26.11.1 | frontend/.node-version |
|
||||
| pnpm | 12.9.1 | `packageManager` in frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| React, React DOM | 19.3.0 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| React Router (`react-router-dom`) | 7.18.4 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| TanStack Query (`@tanstack/react-query`) | 5.104.1 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Zod | 4.6.5 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Vite | 8.3.2 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| TypeScript | 7.0.2 (`@typescript/native`, `tsc`); 6.0.2 API (`typescript` alias of `@typescript/typescript6`) for ESLint | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Vitest | 5.0.3 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Orval | 8.40.0 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Python | 3.14.8 (`requires-python >=3.14,<3.15`) | ml/.python-version, ml/pyproject.toml |
|
||||
| uv | 0.12.22 | `[tool.uv] required-version` in ml/pyproject.toml; `setup-uv` in .github/workflows/ci.yml |
|
||||
| FastAPI | 0.142.2 | ml/pyproject.toml, ml/uv.lock |
|
||||
| Pydantic | 2.13.5 | ml/pyproject.toml, ml/uv.lock |
|
||||
| uvicorn | 0.54.0 | ml/pyproject.toml, ml/uv.lock |
|
||||
| ogen | v1.24.0 | backend/go.mod (`require` and `tool`) |
|
||||
| sqlc | v1.31.1 | backend/go.mod (`tool`) |
|
||||
| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` and `tool`) |
|
||||
| mockery | v3.8.0 | backend/go.mod (`tool`) |
|
||||
| golangci-lint | v2.14.0 | backend/go.mod (`tool`) |
|
||||
| goose | v3.28.0 | backend/go.mod (`require` and `tool`) |
|
||||
| chi | v5.3.2 | backend/go.mod |
|
||||
| pgx | v5.11.0 | backend/go.mod |
|
||||
| testcontainers-go | v0.44.0, including modules/postgres | backend/go.mod |
|
||||
| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; outbox relay producer, event consumer group members, and integration tests | backend/go.mod |
|
||||
## Normal workflow
|
||||
|
||||
What exists now:
|
||||
1. Locate the source of the change: contract, usecase, SQL, UI, or configuration.
|
||||
2. Change source files and add a check for observable behavior.
|
||||
3. Run `make generate` if generator inputs changed.
|
||||
4. Check the affected area; use `make check` for the combined checks.
|
||||
5. Review the diff, update both documentation languages, and run `make docs-check`.
|
||||
|
||||
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
|
||||
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and `identity.Credentials` are wired for registration and email confirmation. A generated Go client for the ML contract exists but is not wired into bootstrap.
|
||||
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
|
||||
- OpenAPI contracts api/core/, api/ml/, and api/runner/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders.
|
||||
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs two product handlers, the mail delivery consumer and the inbox consumer, and no product flow emits their events yet; see [Event consumers](#event-consumers).
|
||||
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
|
||||
|
||||
The API and SPA implement registration, email confirmation, sign-in, consents, the private candidate profile and questionnaire, company profiles, needs, and account-owned support cases. The API also creates and resumes assessment attempts; answer submission and result calculation are not connected yet. Matching, invitations, contact disclosure, and product notification delivery remain in development. The worker sends identity service mail through Resend; SMTP is not implemented. Each workflow's boundaries are described in the [backend README](../../backend/README.en.md) and [frontend README](../../frontend/README.en.md).
|
||||
|
||||
`make -C deploy test-e2e` checks the technical shell on a disposable stack. `make -C deploy test-e2e-registration` also exercises business workflows with an isolated local mail receiver and synthetic data; it does not prove real Resend delivery. See [TESTING.md](TESTING.md#browser-e2e-suite).
|
||||
|
||||
## Install and work loop
|
||||
|
||||
The frontend uses TypeScript 7.0.2 (`tsc`) for type checking. The `@typescript/native` npm alias points to that compiler, while `typescript` points to the compatible `@typescript/typescript6` API for ESLint. This follows [Microsoft's side-by-side setup](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): current typescript-eslint does not support the TS7 API yet. Type checking covers source files, Vite configuration, and the TypeScript files in `codegen/`.
|
||||
|
||||
Orval writes directly to `frontend/src/shared/api/endpoints/` and `schemas/`, without an extra `generated/` directory. The adjacent `client.ts` and root `shared/api/index.ts` are handwritten. A Node test exercises the generated MSW handler together with the generated client. After Orval, the `frontend/codegen/mock-patterns.ts` step replaces `faker.helpers.fromRegExp` in the MSW mocks with `fakeFromPattern` and the length bounds from the contract, and `mock-validity.test.ts` checks every response mock with its Zod schema; see [frontend/README.en.md](../../frontend/README.en.md#api-client-generation). Vitest still reports a peer warning expecting MSW 2; the current Node path is tested with MSW 3, and browser mode is not used.
|
||||
|
||||
Ignore rules belong to each component's `.gitignore`; root rules cover only root files. CI installs pnpm from frontend/package.json's `packageManager` declaration and does not require bundled Corepack. To check ML locally with a different global uv version, pass `UV='uv tool run --from uv==0.12.22 uv'` to Make.
|
||||
|
||||
Run make help at the repository root for the current target list. Main targets:
|
||||
|
||||
- make install installs dependencies for api, frontend, ML, and backend.
|
||||
- make generate bundles both OpenAPI contracts and updates generated Go/TypeScript/Python output.
|
||||
- make fmt and make fmt-check format or check formatting.
|
||||
- make lint runs configured linters.
|
||||
- make test runs backend, frontend, and ML unit/component/service tests.
|
||||
- make check checks api, backend, frontend, ML, deploy, observability, and documentation.
|
||||
- make verify runs generation, drift checks, root check, API/backend validation, and a technical Compose smoke.
|
||||
- make docs-check validates RU/EN docs, local links, routes, and imports.
|
||||
|
||||
Use each area's Makefile for its focused loop, for example make -C backend help, make -C frontend help, make -C ml help, make -C api help, make -C deploy help, and make -C observability help.
|
||||
|
||||
make check is not a business end-to-end suite. make verify runs a deployment smoke with Docker and a backend integration target. See [TESTING.md](TESTING.md) for validation scope and [DEPLOY.md](DEPLOY.md) for the local stack.
|
||||
|
||||
Security tools have a separate install and work loop: `make -C security install`, then `make -C security check`. Use `make -C security test` after changing local rules or scanner integration and `make -C security images` to build and scan service images. These checks are separate from the ordinary root `make check`; see [SECURITY.md](SECURITY.md) for prerequisites, policies, and reports.
|
||||
|
||||
### Sessions on local HTTP
|
||||
|
||||
The session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production.
|
||||
|
||||
`ConfirmEmail` requires Origin to match `APP_PUBLIC_URL` exactly; a missing Origin, the literal value `null`, or any other value answers 403 `csrf_check_failed`. The same check applies to other unsafe identity operations and protected session requests; the latter also require the session-bound CSRF token. The server does not use Host to derive an allowed Origin.
|
||||
|
||||
## Layout
|
||||
|
||||
Each top-level directory except `.github/` has a short Russian `README.md` and an English `README.en.md`. A README and its translation are optional in `.github/`. Detailed guides live in `docs/ru/` and `docs/en/`; READMEs are not added below the first directory level. `make docs-check` validates language pairs and links and runs the checker's own tests.
|
||||
|
||||
| Directory | Purpose |
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| api/core/ | Public browser-to-Go OpenAPI contract |
|
||||
| api/ml/ | Internal Go-to-ML OpenAPI contract |
|
||||
| api/runner/ | Internal OpenAPI contract between Go and the code runner |
|
||||
| scripts/ | Shared schema merge, generated drift, and docs-check |
|
||||
| backend/ | Go HTTP service, adapters, bootstrap, SQL, and consumer codegen |
|
||||
| backend/config/ | Shared Go configuration outside internal |
|
||||
| frontend/ | Vite SPA, Orval configuration, generated TypeScript |
|
||||
| ml/ | Python service, lockfile, and Pydantic model generator |
|
||||
| runner/ | Go code runner service: nsjail, cgroup v2, judge, ogen server, and isolation tests |
|
||||
| deploy/ | Compose, Nginx, and smoke script |
|
||||
| observability/ | Prometheus, Loki, Alloy, provisioning, and dashboard JSON |
|
||||
| security/ | Scanner configuration, installation, Make targets, and local reports |
|
||||
| .agents/ | Canonical project instructions and working standards |
|
||||
| docs/ru/, docs/en/ | User documentation in Russian and English |
|
||||
| `make fmt` | Reformat source files |
|
||||
| `make fmt-check` | Check formatting without edits |
|
||||
| `make test` | Service unit and component tests |
|
||||
| `make check` | Code, documentation, and configuration checks |
|
||||
| `make verify` | Generation, drift, checks, race, integration tests, and smoke |
|
||||
|
||||
Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The Go client for the code runner is generated from backend/codegen/ogen-code-runner.yml into backend/internal/adapter/secondary/code_runner/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go.
|
||||
`verify` requires Docker. It does not include Playwright, security scanners, or real-model checks; select those separately for the change.
|
||||
|
||||
## Local environment
|
||||
|
||||
Use Compose for the complete application. `.env.example` describes its variables; keep secrets in the local `.env`, outside Git and command examples.
|
||||
|
||||
`make -C backend run` reads process environment variables, not `.env`. PostgreSQL, Redis, SeaweedFS, and Kafka addresses inside Compose may not be reachable by a host process. Do not disable required dependencies just to make startup succeed.
|
||||
|
||||
`make -C frontend dev` starts Vite and proxies `/api` to `127.0.0.1:8080`. Authentication validates the public Origin, so `APP_PUBLIC_URL` must match the browser address. Use the application behind Nginx for the complete cookie flow.
|
||||
|
||||
Mail is disabled by default. Develop registration against the isolated mail E2E stand or configure Resend; the SMTP transport is not implemented. A separate demo stand provides prepared synthetic accounts.
|
||||
|
||||
## Contracts and generation
|
||||
|
||||
Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/, api/ml/, and api/runner/ and then bundle each input. The public and internal APIs remain separate contracts.
|
||||
Edit `routes/` and `components/` grouped by subject in `api/core/`, `api/ml/`, `api/runner/`, or `api/labd/`. [api/README.en.md](../../api/README.en.md) summarizes HTTP conventions.
|
||||
|
||||
Root make generate prepares both bundles once, then runs Go, TypeScript, and Python consumers. Merged schemas, bundles, and generated clients are tracked derived files; change their sources and regenerate them. After changing a contract, regenerate every consumer and check drift. A service-local Make target can generate one consumer when its inputs are ready and the shared contract owner has agreed.
|
||||
|
||||
The target is OpenAPI 3.2.0, with ogen for Go, Orval for TypeScript, and datamodel-code-generator for Python/Pydantic v2. Verify the actual feature subset used by the project through pinned tools and the runtime path. A version string does not prove full specification support.
|
||||
|
||||
datamodel-code-generator 0.83.0 reads api/ml/openapi.bundle.yml and writes ml/src/lincodex_ml/api/models.py. Settings live in ml/codegen/pyproject.toml; this file configures the tool, while dependencies remain in ml/pyproject.toml and uv.lock. Health/readiness handlers import the generated models instead of maintaining handwritten schema copies. make -C ml generate bundles the API first; when called by root make generate, API_PREPARED=1 reuses the prepared bundle. make -C ml check-generated compares output with --check without rewriting the file. CI uses the shared make generate target, which includes the Python models.
|
||||
|
||||
Errors, retries, versions, pagination, and time follow the [contract conventions](../../api/README.en.md#contract-conventions). Implemented: every error of the public Go API and of the ML service is an RFC 9457 problem (`application/problem+json`) with a stable `code`. The Go mapping of ogen errors lives in backend/internal/adapter/primary/http/problem/: request validation gives 400, unknown routes under /api 404, unimplemented operations 501, and other errors and panics 500 without internal text; errors are logged at that boundary, panics only by type and stack. The frontend API client throws `ApiRequestError` for problems, network failures (`network_error`), and invalid 2xx bodies (`invalid_response`); a caller's abort propagates unchanged. The ML service maps FastAPI errors in ml/src/lincodex_ml/api/problems.py and routes uvicorn logs through its JSON format without exception text. Idempotency-Key storage, If-Match checks, and pagination are planned: the contract defines their components, and the first business operation that needs them implements them.
|
||||
|
||||
## Code boundaries
|
||||
|
||||
SQL linter dependencies are listed in `backend/requirements-quality.txt` beside `.sqlfluff`. The `make -C backend lint-sql` command installs them in the local `.venv-quality` environment and checks migrations and queries. Running the Go service does not require this environment.
|
||||
|
||||
Go follows domain, usecase, port, adapter, and bootstrap boundaries. The HTTP adapter mounts the generated ogen handler in chi. SQL belongs in backend/db/queries/; schema changes belong in backend/db/migrations/. sqlc output and wire_gen.go are generated.
|
||||
|
||||
Shared backend settings live in backend/config/. The service uses go-logkit 0.6.0 through its slog bridge and go-httpkit 0.7.0 for request IDs and panic recovery. Request logging is the service's own `middleware.RequestLog`: the go-httpkit logger writes the raw path and every query value not on its fixed redaction list, so an address in a path or query would reach the logs. It retains custom Prometheus middleware because it bounds method labels and uses chi route patterns; go-httpkit/metrics accepts the raw method name as a label.
|
||||
|
||||
PostgreSQL uses pgxpool.NewWithConfig, and a generated SELECT 1 readiness query checks connectivity. Pool construction must not wait for the database during startup. go-pgkit 1.4.0 is not used because its constructor probes and retries before returning a pool, coupling service startup to database availability. Health handlers remain explicit: go-httpkit's helper returns ok/degraded with check details, while the shared contract uses ok/ready/not_ready. Do not add pgkit, httpkit/metrics, JWT or WebSocket without a concrete need and a check of the pinned version's behavior.
|
||||
|
||||
Redis connects through the outbound cache port and `backend/internal/adapter/secondary/redis/`. The adapter uses `go-cachekit` 0.7.0 for key/value operations over go-redis; library details stay behind this boundary. Bootstrap constructs the client without waiting for connectivity and closes it on shutdown; shared /readyz checks PostgreSQL, Redis, and SeaweedFS. Use Get/Set/Del with a positive TTL and distinguish a missing key from a Redis error. This is a technical adapter; product cache consumers have not been added. Connection settings are described in [DEPLOY.md](DEPLOY.md).
|
||||
|
||||
S3 storage connects through the outbound `ObjectStorage` port and `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS is a separate server; AWS SDK for Go v2 is the Go client inside the adapter. Put/Get stream content; Put requires a known byte length, and callers must close the body returned by Get. The Get timeout covers reading the response body. The adapter bounds operation time and distinguishes a missing object from a service error. The container initializes its bucket; Go checks it with HeadBucket instead of creating infrastructure while handling requests. Do not add direct Nginx delivery of private files or product upload/download endpoints without access rules.
|
||||
|
||||
The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added.
|
||||
|
||||
Implemented frontend scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, a TanStack Query client over the shared same-origin `apiRequest`, dark graphite theme tokens in CSS variables, and shared primitives for loading, empty, error, forbidden, and saving states. JetBrains Mono, Inter, and Unbounded (for the Lincodex wordmark) are self-hosted with their OFL licenses. Sign-in, registration, email confirmation, support, and cabinet screens are placeholders; business screens are later tasks. /status is a technical API liveness page, not product readiness. Vitest runs in the Node environment without a DOM. The Playwright suite in `frontend/e2e/` loads pages in Chromium but does not yet test interactions, so clicks and keyboard focus are verified manually in a browser until it covers them. See [frontend/README.en.md](../../frontend/README.en.md). Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented.
|
||||
|
||||
ML runs as a separate FastAPI process. It currently provides operational health/readiness only. Readiness stays at 503 without a model. Do not add placeholder inference that looks like a real result.
|
||||
|
||||
Write all source comments and docstrings in English. Keep canonical agent instructions in one English version; maintain user documentation in Russian and English.
|
||||
|
||||
### Database migrations
|
||||
|
||||
Migrations are goose SQL files in `backend/db/migrations/` named `NNNNN_description.sql` with sequential five-digit versions. Each file has a `-- +goose Up` section and a working `-- +goose Down` section. sqlc reads the same directory as its schema, and `make -C backend lint-sql` lints it. `backend/db/migrations.go` embeds the files, so the binary applies exactly the schema it was built with. `make -C backend check` loads the embedded set without a database and fails on a malformed name, a missing Down section, or a duplicate version. A deployed migration is immutable; change the schema with a new file. Two branches that add the same version must renumber before merging. To create a file with the next sequential number, run `go tool goose -dir db/migrations -s create <name> sql` in `backend/`.
|
||||
|
||||
goose runs each migration in its own transaction. A statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`, needs a file of its own with the `-- +goose NO TRANSACTION` annotation. Every migration connection sets `lock_timeout` to 10 seconds, so DDL fails instead of queueing behind long transactions and blocking later queries on the table, and `statement_timeout` to 4 minutes.
|
||||
|
||||
At startup bootstrap applies pending migrations after configuration validation and before the HTTP and metrics listeners open. The runner in `backend/internal/adapter/secondary/postgres/migrator.go` uses the goose v3 Provider API with the pgx database/sql driver and a PostgreSQL session advisory lock, so instances that start together apply migrations one at a time. Lock waiting and migration work are limited to five minutes. A migration error stops startup; the error omits the connection string and the password. Without `DATABASE_URL` the step is skipped with a warning, and readiness stays `not_ready` as before.
|
||||
|
||||
`DATABASE_MIGRATE_ON_START` accepts only `true` or `false` (case-insensitive, surrounding spaces ignored); the default is `true`. It is a local and development option, for example to start the service against a database that a developer migrates by hand. The Compose stack does not pass it, and the backend image contains no separate migration command, so a deployed backend always migrates at startup and its database role needs DDL rights on the application schema. A separate migration role and job with a least-privilege runtime role is future work.
|
||||
|
||||
For a local database, export `DATABASE_URL` in your shell and use these targets:
|
||||
|
||||
- `make -C backend migrate-status` lists each embedded migration as applied, with its time, or pending.
|
||||
- `make -C backend migrate-up` applies pending migrations.
|
||||
- `make -C backend migrate-down-one` rolls back the latest applied migration.
|
||||
|
||||
The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts as startup. The Makefile contains no connection strings; keep credentials out of committed files. Integration tests apply all migrations to the PostgreSQL container from the shared bootstrap; see [TESTING.md](TESTING.md).
|
||||
|
||||
### Identity storage
|
||||
|
||||
Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, and `sessions`; the queries are in `backend/db/queries/identity.sql`. Migration 00014 adds the password hash, scenario, and onboarding step for each registration to its token. Migration 00016 binds registration C1 to the account registration version and backfills existing records without using live tokens. The identity ports are used by registration, verification resend, and email confirmation; login and the session principal are not implemented.
|
||||
|
||||
The database never receives a password, a raw email token, or a raw session token. Repositories take a `domain.PasswordHash` (an Argon2id v19 PHC string) and a `domain.SecretTokenHash` (the SHA-256 of a `domain.SecretToken`). Email addresses are ASCII only for now; IDN and SMTPUTF8 support is future work that needs IDNA ToASCII for the domain. `SecretToken`, `PasswordHash`, and `EmailAddress` redact themselves in `fmt` and `slog` output; `SecretToken.Reveal` and `EmailAddress.Address` return the real values where they are needed. Every stored time comes from the application clock that the caller passes, and PostgreSQL keeps microseconds. A deadlock or serialization failure is reported as `outbound.ErrTransactionConflict`, and the caller may retry the whole operation. The schema and its decisions are described in [ARCHITECTURE.md](ARCHITECTURE.md#identity-storage).
|
||||
|
||||
Passwords enter the backend only as `domain.Password`: `domain.NewPassword` for a new password (15 to 128 code points after NFKC) and `domain.ParseLoginPassword` at login (1 to 128). Raw input over 512 bytes or with invalid UTF-8 is rejected before normalization, and every length check runs before hashing. The `argon2id` adapter implements `outbound.PasswordHasher` with m=65536 KiB, t=3, p=4, a memory budget of `PASSWORD_HASH_CONCURRENCY` derivations (1 to 4; unset means the smaller of 2 and GOMAXPROCS), `ErrPasswordMismatch` for a wrong password, `ErrPasswordHashCorrupt` for a malformed or out-of-bounds stored hash, a `needsRehash` result for older parameters, and `VerifyDummy` for unknown accounts. A stored hash that fails parsing or bounds wraps both `ErrPasswordHashCorrupt` and `domain.ErrInvalidPasswordHash`. Unit tests use cheap parameters; the 64 MiB reference vector is skipped with `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` in `backend/` measures one hash with the production parameters. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing).
|
||||
|
||||
### Product policy store
|
||||
|
||||
Migration `00003_create_policy_versions.sql` creates `policy_versions`, the trigger that stamps `created_at` from the database clock, and the triggers that refuse UPDATE, DELETE, and TRUNCATE; the queries are in `backend/db/queries/policy.sql`. `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and through `postgres.PolicyStore` outside a transaction; `policy.Publisher` publishes a version under the next free number and seeds the demo policy. To change a value, publish a new version; a stored version is never edited. `product` is the only policy family.
|
||||
|
||||
At startup the backend publishes `domain.DemoProductPolicyV1()` as version 1 of `product` when that family has no version. The seed runs right after the startup migrations and only when they run (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set). With startup migrations disabled, nothing seeds the policy. The seed checks presence only, never changes or decodes an existing version, and logs only the key, number, kind, and ID. The demo values are the accepted initial policy, not calibrated values.
|
||||
|
||||
A record that depends on policy values adds `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, stores the version it used, and reads it back by ID; do not recompute an existing record through `GetEffective`. Tests use their own values and do not stand in for the demo policy. Since `product` is the only family and the table refuses TRUNCATE, the integration tests give every case its own database. A new document layout needs a new `schema_version` and decoder; do not edit the golden document in `backend/internal/domain/policy_test.go` to accept a changed canonical form. See [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions).
|
||||
|
||||
### Assessment bank
|
||||
|
||||
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. An algorithm with the answer format `choice` sets `generateChoice` instead of `generate` and returns the correct value with the wrong values of named error models (`lru_hits_choice.v1` is the example); its tests recompute the error models from the statement. A family whose variants are fixed data uses a table generator instead of an algorithm: `seed_generator.table.rows` with `values`, `answer`, and for `choice` the `distractors`, validated at import with the row index in the error and stored with hash scheme 2; use a Go algorithm when the answer must be computed. Migration `00047_allow_table_hash_scheme.sql` allows scheme 2. Statement templates are plain text with `{{.name}}` placeholders only. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
|
||||
|
||||
### Outbox relay
|
||||
|
||||
The relay moves committed `outbox_events` rows to Kafka. The loop lives in `backend/internal/worker/outboxrelay/` and its backoff in `backend/internal/worker/retry/`; it depends on the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports in `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` runs the claim transaction with the `LockPendingOutboxEvents` and `MarkOutboxEventsPublished` queries from `backend/db/queries/outbox.sql`, and `kafka.Publisher` in `backend/internal/adapter/secondary/kafka/` builds the record envelope, provisions the topic, and produces with franz-go. `bootstrap.newOutboxRelay` creates the relay with its own PostgreSQL pool of at most two connections and its own Kafka client, and the application runs it while the HTTP servers run. Product code never calls the relay: a usecase only appends events with `UnitOfWork.Outbox()` in its business transaction.
|
||||
|
||||
A directly launched backend with `DATABASE_URL` set runs the relay against `KAFKA_BROKERS` (`localhost:9092` by default). Without a reachable broker it keeps logging retry warnings and the events stay pending; set `RELAY_ENABLED=false` when you do not need publication. Selection, ordering, envelope, and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay); settings are in [DEPLOY.md](DEPLOY.md#outbox-relay); tests are in [TESTING.md](TESTING.md#outbox-relay-tests).
|
||||
|
||||
### Event consumers
|
||||
|
||||
The consumer runtime applies events from Kafka to this service's own state, once per consumer. The loop lives in `backend/internal/worker/eventconsumer/`; it depends on the `inbound.EventHandler` port (`backend/internal/port/inbound/event_handler.go`) and on the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` is the franz-go group member that decodes the envelope and commits offsets, and `postgres.EventConsumerStore` runs the dedup transaction with the queries in `backend/db/queries/event_consumer.sql`. The backoff is shared with the relay in `backend/internal/worker/retry/`.
|
||||
|
||||
Two product handlers are registered: `notification.DeliveryHandler` stores mail deliveries (see [Mail deliveries](#mail-deliveries)) and `notification.InboxHandler` stores inbox references (see [Internal notifications](#internal-notifications)). To add another, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does.
|
||||
|
||||
A directly launched backend with a registered handler and `DATABASE_URL` set consumes from `KAFKA_BROKERS`; set `CONSUMER_ENABLED=false` when you do not need it. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers); settings, metrics, and the dead letter procedure are in [DEPLOY.md](DEPLOY.md#event-consumers); tests are in [TESTING.md](TESTING.md#event-consumer-tests).
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
To send a notification from a usecase, call `notification.MailRequester.RequestNotification(ctx, unit, request)` with the usecase's `UnitOfWork`, the recipient account ID, and `mailtemplate.NotificationData`; it returns the delivery ID. It stores the text in `mail_requests` and appends an event that carries only the request ID and kind, both in the usecase's transaction. The consumer `notification_delivery` then stores the delivery with the address read from the account and the rendered content, and deletes the request; it skips accounts whose address is not verified. Never put an email address, a token, notification text, or another person's contact into any event payload, and never put a token or another person's contact into a request. Verification and password reset mail carry a token and cannot use the event: the identity flows create those deliveries with `domain.NewDelivery` and `UnitOfWork.Deliveries().Create` in the transaction that issues the token. A new template version changes new deliveries only; never update a stored delivery's content. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries), operations in [DEPLOY.md](DEPLOY.md#mail-deliveries), and tests in [TESTING.md](TESTING.md#mail-delivery-tests).
|
||||
|
||||
Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
|
||||
|
||||
### Internal notifications
|
||||
|
||||
To put a notification into a recipient's inbox, append an event with `unit.Outbox().Append` in the usecase's own transaction. The type must be allowlisted (`domain.NotificationInboxSourceFor`), the payload must be exactly `recipient_user_id` and `organization_id`, and the aggregate must be the one the type names (`invitation` for `invitation.delivered`). Never put text or contacts in the payload. The `notification_inbox` consumer stores a reference. The text is produced when the recipient reads the list, by a resolver that you register for your source type in `notification.DefaultInboxSourceResolvers()`: an `InboxSourceResolver` that reads the current state through the `UnitOfWork`, applies the recipient's current visibility, and returns `ErrInboxContentUnavailable` when the content must not be shown. For a new event type add the pair to `domain.NotificationInboxSourceFor`, the entry to `inboxProjections` in `usecase/notification/inbox_handler.go`, a migration that widens the CHECK constraint of `notification_inbox_events` (never edit a deployed migration), a `NotificationKind` value to the contract, and the mapping in `adapter/primary/http/v1/notifications.go`. A producer needs no email: mail is requested separately with `MailRequester`, and the inbox state does not depend on it. The path can be tried end to end with the synthetic event `notification.synthetic_delivered` (`notification.SyntheticNoticeEventPayload` builds its payload); it has no product meaning and is handled only when `NOTIFICATION_SYNTHETIC_ENABLED=true`. See [Internal notifications](ARCHITECTURE.md#internal-notifications).
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
To run something when it falls due, such as an expiry or a reminder, schedule a job in the usecase's own transaction: build it with `domain.NewScheduledJob` (a kind such as `invitation.response_deadline`, a key that identifies the logical job, for example the aggregate ID, the due time from the injected clock, and a payload of identifiers only) and call `unit.ScheduledJobs().Schedule(ctx, job)`. The first schedule of a kind and key wins and a repeat is ignored, so use a new key, for example `<id>:<version>`, for a new occurrence. Cancel with `unit.ScheduledJobs().Cancel(ctx, kind, key)` before locking the product rows that the handler touches.
|
||||
|
||||
Then implement `inbound.JobHandler` in the module's usecase package: return the kind from `JobKind()` and write the effect in `Handle` only through the `UnitOfWork` it receives, deciding by `job.DueAt` and the current product state, so the handler is a no-op when the state already moved on. A handler may cancel its own job through the unit, for example from a shared helper that cancels the deadline; the job then counts as finished. It must not change its own job in any other way. Return an error that wraps `inbound.ErrJobRejected` for a job that can never run; any other error is retried. Add the handler to `jobHandlers()` in `backend/internal/bootstrap/jobs.go`. Take the clock as a `func() time.Time` and test deadlines with `testutil.FakeClock` from `backend/pkg/testutil/` and `Worker.RunDue`, which runs the due jobs once without polling, as `TestScheduledJobs` does. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs); settings, metrics, and the dead job procedure are in [DEPLOY.md](DEPLOY.md#scheduled-jobs); tests are in [TESTING.md](TESTING.md#scheduled-job-tests).
|
||||
|
||||
## Go readability
|
||||
|
||||
- Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call.
|
||||
- Name non-obvious limits, timeouts, retry settings, protocol bounds, and shared fixture values with constants in the owning package. Derive counts with `len` when they depend on data. Equal numbers with different meanings need separate names. Obvious zero values, indexes, and clear test inputs can stay inline.
|
||||
- Environment settings belong in config with named defaults and validation. Parse each value once; distinguish an unset variable from an explicitly invalid value.
|
||||
- Give each function one clear purpose. Prefer early returns, shallow nesting, and named complex conditions. Do not add generic helpers, interfaces, or layers without consumers.
|
||||
- Pass `context.Context` first. Keep resource ownership and dependencies explicit; register cleanup immediately after acquisition, including partial startup. Helpers must not hide goroutines or global mutable state.
|
||||
- Check errors and explain non-obvious discarded results. Do not use error-string comparisons for control flow or expose internal errors in HTTP responses.
|
||||
- Write English comments explaining constraints and decisions. Use gofmt/goimports. Refactors preserve behavior; tests cover meaningful boundaries and edge cases rather than constant names or helper internals.
|
||||
|
||||
## Error format
|
||||
|
||||
Handwritten Go errors use `Component.Method - operation: %w` when wrapping a cause and `Component.Method - reason` without a cause. For a free function, use `package.Function`. For example:
|
||||
|
||||
```go
|
||||
if err != nil {
|
||||
return fmt.Errorf("EmailUseCase.Send - read ctf_name: %w", err)
|
||||
}
|
||||
```sh
|
||||
make -C api check
|
||||
make generate
|
||||
make check-generated
|
||||
```
|
||||
|
||||
Create a static error without a cause using `errors.New("EmailUseCase.Send - ctf_name is empty")`. The prefix identifies the actual method; descriptions are in English without trailing punctuation. Preserve `errors.Is/As` and sentinel identities, adding context at the error's origin. Avoid redundant wrappers for pass-through returns. Sanitize external SDK errors before wrapping to exclude secrets, URLs, and private object keys. Do not edit generated code. Log errors at the handling boundary rather than at every layer.
|
||||
Generation order is API bundles, Go backend, runner, labd, frontend, and Python ML. `make check-generated` compares output with Git without running generators. Intentional contract changes should include updated output in the same commit; investigate unexpected differences.
|
||||
|
||||
## Change rules
|
||||
- ogen writes Go HTTP code into the relevant adapter's `api/` directory.
|
||||
- sqlc writes PostgreSQL queries into `backend/internal/adapter/secondary/postgres/sqlc/`.
|
||||
- wire assembles dependencies in `backend/internal/bootstrap/`.
|
||||
- mockery generates only interfaces selected in `backend/codegen/mockery.yml`.
|
||||
- Orval writes the client, query hooks, Zod schemas, and MSW into `frontend/src/shared/api/endpoints/` and `schemas/`.
|
||||
- datamodel-code-generator creates Pydantic models from the ML contract.
|
||||
|
||||
- Inspect current code and ownership before editing a shared file.
|
||||
- Preserve other contributors' current changes.
|
||||
- Coordinate changes to OpenAPI, migrations, shared Makefiles, lockfiles, and generated output with one owner of that shared surface.
|
||||
- Regenerate derived files through Make targets.
|
||||
- Label current behavior and intended behavior separately.
|
||||
- Do not commit local paths, secrets, or personal developer settings.
|
||||
Do not edit output by hand. Generator configuration belongs to its consumer's `codegen/` directory: the Go ML client belongs to backend and the Python models belong to ML.
|
||||
|
||||
For backend, frontend, ML, API, database, and infrastructure tasks, use the routes in the root [AGENTS_ROUTING.md](../../AGENTS_ROUTING.md).
|
||||
## Backend and data
|
||||
|
||||
Domain types live directly in `internal/domain/`. Usecases depend on ports; adapters provide HTTP, database, and external-service access. `internal/bootstrap/` assembles dependencies and manages their lifecycle; `cmd/app/main.go` calls it.
|
||||
|
||||
- Put business rules in domain/usecase and HTTP conversion in `adapter/primary/http/v1/`.
|
||||
- Define the required port and adapter for new infrastructure. Services do not access another service's tables directly.
|
||||
- Edit SQL in `db/queries/`, then run `make -C backend gen-sqlc`.
|
||||
- Add schema changes as new migrations in `db/migrations/` and test on an isolated database. Do not rewrite applied migrations.
|
||||
- Save business changes and their outbox event in one transaction. Handlers must tolerate repeated delivery.
|
||||
- Extract repeated code into small helpers; use named constants or configuration for values with domain meaning.
|
||||
|
||||
Errors identify the location and reason: `fmt.Errorf("ProfileUseCase.Update - save profile: %w", err)`. Use the same format without `%w` when there is no underlying error. HTTP responses expose safe problem codes, not internal errors or personal data.
|
||||
|
||||
`make -C backend help` lists maintenance commands. Migrations, mail retries, policy publication, and backfills change state: select the intended environment explicitly.
|
||||
|
||||
## Frontend
|
||||
|
||||
FSD layers are `app`, `pages`, `widgets`, `features`, `entities`, and `shared`. Import lower layers through slice public APIs; do not couple neighboring slices through internal imports. Common components and styles belong in `shared/`; use generated API types.
|
||||
|
||||
Keep server state in TanStack Query and drafts in form state. Preserve entered data on version conflicts and offer to reload the server state. Asynchronous screens need loading, empty, error, and retry states.
|
||||
|
||||
Check keyboard access, focus, field labels, and narrow screens. Vitest checks logic; Playwright checks the interface in a browser.
|
||||
|
||||
## ML and additional services
|
||||
|
||||
ML commands: `make -C ml help`. Ordinary checks use Ruff, mypy, and pytest; model quality and real inference are separate checks. Pin model weights and evaluation data versions.
|
||||
|
||||
Runner and labd are separate Go modules. Unit tests do not replace runner isolation checks or testing labd on a separate LXD test host. Their environments are described in [runner/](../../runner/README.en.md) and [labd/](../../labd/README.en.md).
|
||||
|
||||
## Documentation and Git
|
||||
|
||||
A directory README explains its purpose, startup, and main commands. Details belong in contracts, source files, and the relevant guide. Keep execution history and inventories of individual tests out of documentation.
|
||||
|
||||
Write code comments in English. Maintain documentation in RU/EN pairs. Plans and their identifiers stay in local `PRD/`, which must not be committed. Use a short, single-line commit message describing the change, without assistant authorship or coauthor trailers.
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
# Lincodex MVP: submission package
|
||||
|
||||
Verified commit: `c9f029471ed78ce5ec4583009abdc5a4c8c3bd97` (branch dev, 2026-10-10).
|
||||
|
||||
Release: `mvp-2026-10-10`, built from `392d117` (the same code plus this document). The manifest `deploy/release/mvp-2026-10-10/manifest.json` is a local artifact of the machine that built the images (it is not kept in Git, see [release manifest](DEPLOY.md#release-manifest)); the core is `verified`, the smoke and the browser suite passed on the release images, and restore is available.
|
||||
|
||||
This document describes what the minimal release contains, how to run it, what limits the demonstration category, what is not implemented, and how the release was checked. Details live in the guides: [ARCHITECTURE](ARCHITECTURE.md), [DEPLOY](DEPLOY.md), [TESTING](TESTING.md), [SECURITY](SECURITY.md), [COMPANY_QUOTAS](COMPANY_QUOTAS.md), and the [frontend guide](../../frontend/README.en.md). The HTTP API contract is in [api/](../../api/README.en.md). The statements below are derived from the code, the contract, and these guides; planned behavior is kept apart from working behavior.
|
||||
|
||||
## 1. What is implemented
|
||||
|
||||
### Registration and sign-in
|
||||
|
||||
- Registration of a candidate and an employer with the C1 consent. The address is confirmed with a link from the email or with a six-digit code from the same email; after confirmation, sign-in returns the user to the saved step. See [registration and confirmation](ARCHITECTURE.md#registration-email-verification-and-resend).
|
||||
- Email is sent only with `EMAIL_PROVIDER=resend`. With `disabled`, registration is accepted but there is no way to confirm the address, and sign-in answers 403 `email_not_verified`. The prepared accounts of the demo stand are confirmed in advance. See [mail](DEPLOY.md#2-mail-resend-or-disabled).
|
||||
|
||||
### Candidate
|
||||
|
||||
- Consents C1-C5 in settings. C3 allows automatic categorization; without it, a manual assessment can be requested through a support case.
|
||||
- The profile is filled in manually, step by step, without a resume and without an FSP ID. The questionnaire holds specializations and self-assessment. The home page shows the next step. See [candidate profile](ARCHITECTURE.md#candidate-profile).
|
||||
- Skill assessment in two modes (see [assessment](ARCHITECTURE.md#assessment-and-grade-verification)):
|
||||
- the full `demo_basic` Backend Junior with Go test: 25 tasks from a synthetic bank, a 72-hour window, two work sessions, no practice. The result is compared with the pass mark of the policy version; on the demo stand a passed test gets a category with the basis `synthetic_demo`, otherwise the result is `not_confirmed`;
|
||||
- the `demo_express` test: three tasks; it never assigns a grade, a category, a percentile, or evidence and does not appear in the result history.
|
||||
- Results, history, and skill evidence are available to the candidate; the declared grade is always kept apart from the confirmed one. See [evidence](ARCHITECTURE.md#skill-evidence).
|
||||
|
||||
### Publication and visibility
|
||||
|
||||
- The anonymous card is published only after an explicit C2 and carries no name, contact, or salary amount. The candidate sees a preview built from the same response that the card for organizations uses.
|
||||
- Search status, hiding of individual organizations, change history, and the history of card views and contact reads. A card is shown to organizations only in a group of at least five. See [visibility](ARCHITECTURE.md#candidate-visibility).
|
||||
|
||||
### Employer
|
||||
|
||||
- Organizations (one account can own several), a company profile, and a step-by-step need with a salary range. A need stores requirement versions; a search by a version does not change after an edit. See [organizations](ARCHITECTURE.md#organizations-and-memberships).
|
||||
- Candidate search by a need or by the bank with filters: specialization, confirmed and declared grade, confirmation status, stack, work format, and salary compatibility. The result is split into the groups `main`, `near`, and `unconfirmed`, and the server builds the explanation (score components and unknown flags).
|
||||
- The baseline match works without ML: semantic similarity is a neutral 0.5 marked with the flag `ml_unavailable`; for a cohort below 30 the flag `cohort_below_30` is added. See [matching and explanations](ARCHITECTURE.md#matching-and-explanations).
|
||||
|
||||
### Invitations and contacts
|
||||
|
||||
- The organization creates a draft from a search result, changes the terms with versions, and sends the invitation with a salary range in rubles. Sending spends one place of the weekly quota; a pending limit applies per need, a pair pause applies after a decline, and an unanswered invitation expires at its deadline. See [drafts](ARCHITECTURE.md#invitation-drafts), [sending](ARCHITECTURE.md#sending-invitations), and [limit and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry).
|
||||
- A delivered invitation reaches the candidate inbox. The candidate marks it viewed, declines it, or accepts it with the C4 consent and a choice of contact fields. See [view and decline](ARCHITECTURE.md#candidate-view-and-decline) and [acceptance](ARCHITECTURE.md#candidate-acceptance).
|
||||
- Acceptance creates a contact grant for exactly this pair. The organization reads the chosen fields on the invitation page, and every read checks the grant and the visibility again. Revoking C4, revoking C2, closing the publication, and hiding the organization close the read at once; republishing does not reopen a closed grant. See [contact reads and revocation](ARCHITECTURE.md#contact-reads-and-revocation).
|
||||
|
||||
### Company isolation and holdings
|
||||
|
||||
- Organization operations answer a foreign identifier with the same refusal as for a random identifier. Search, invitations, and contact reads are available only to the owner of the organization.
|
||||
- Organizations of one account form a holding: E0 companies share common quotas (in the demonstration policy, 10 invitations per 7 days and 50 unique card views per 24 hours). The number of organizations per account is not limited. See [COMPANY_QUOTAS](COMPANY_QUOTAS.md#holding-pool).
|
||||
|
||||
### Notifications and mail
|
||||
|
||||
- An inbox in both cabinets; the only product source is a delivered invitation. The entry appears through the outbox, the relay, and Kafka after the commit, not inside the sending transaction. See [internal notifications](ARCHITECTURE.md#internal-notifications).
|
||||
- The invitation email goes through the outbox and the delivery consumer, and a separate notification loop (a worker in the backend process) sends it; before each send it checks the recipient rights again and leaves a quota reserve for service mail. The body is neutral and holds no contacts. See [sending product notifications](ARCHITECTURE.md#sending-product-notifications).
|
||||
- Support cases in both cabinets.
|
||||
|
||||
### Privacy guarantees
|
||||
|
||||
- Before the C4 record and the grant, the organization receives no contacts; cards, search results, invitation lists, and notifications contain no email, phone, or name.
|
||||
- The server log, outbox payloads, inbox rows, and mail requests carry no contact or profile values (checked by the isolation integration test, see section 5).
|
||||
- Organization responses contain no PDFs and no stored search snapshots: there are no such operations.
|
||||
|
||||
## 2. How to run
|
||||
|
||||
Run all commands from the repository root. You need Docker with Compose, GNU make, python3, and openssl; no GPU or external keys are required. Full instructions: [quick start](DEPLOY.md#running-the-mvp-quick-start).
|
||||
|
||||
### Working stand
|
||||
|
||||
cp .env.example .env # replace every replace-this-... value and set IDENTITY_KEY_SECRET
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl http://localhost:8080/api/v1/healthz
|
||||
|
||||
Open http://localhost:8080 (the value of `APP_PUBLIC_URL`). For email, set `EMAIL_PROVIDER=resend`, `RESEND_API_KEY`, and `EMAIL_FROM` in the server environment. A clean stand holds migrations and the starting policy; operator steps (`DATABASE_URL` is required):
|
||||
|
||||
1. Publish the matching section; without it the search answers 500: `make -C backend policy-publish ARGS='matching --actor operator:<handle>'`. See [match search policy](DEPLOY.md#match-search-policy-on-a-stand).
|
||||
2. For a passed full test to receive the demonstration category, set `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, restart the backend, and attest the category opening with `make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'`. Publishing a new policy version requires a new opening and a new attestation, so do step 1 before candidates start attempts. See [demonstration categories](DEPLOY.md#demonstration-categories-on-a-stand).
|
||||
|
||||
The task bank is not loaded on the core stand, and the DEPLOY guide describes loading it only as part of the demo stand seed, so a test cannot be started on the core stand. Use the demo stand to show the full path.
|
||||
|
||||
### Demo stand and the jury route
|
||||
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
|
||||
The command starts a separate project at http://localhost:8090, publishes the policy with the matching section, loads the synthetic bank, attests the category, and creates the accounts `candidate@`, `prepared-1@` to `prepared-6@`, `employer-alpha@`, and `employer-beta@` in the domain `demo.lincodex.test`; the password comes from `deploy/demo/demo.env` or `demo.env.example`. The jury guide is at http://localhost:8090/demo; it takes eight minutes and exists only in the build of this stand. The route: the express and full tests of the candidate, prepared candidates with published cards, a need and a search by the owner of "Alpha", an invitation, acceptance with C4, and a contact read. See [demo stand](DEPLOY.md#3-demo-stand), [route](DEPLOY.md#4-demonstration-route), and [isolated stand](DEPLOY.md#isolated-demo-stand). Reset: `make -C deploy demo-reset DEMO_MODE=isolated` (it refuses when the stand holds ordinary accounts).
|
||||
|
||||
### Restoring from a release manifest
|
||||
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=<id>
|
||||
make -C deploy release-up RELEASE_ID=<id>
|
||||
make -C deploy release-manifest-verify RELEASE_ID=<id> RELEASE_VERIFY_PROJECT=<project>
|
||||
make -C deploy demo-seed DEMO_MODE=isolated RELEASE_ID=<id>
|
||||
|
||||
The manifest is immutable: it pins the sources, lockfiles, Compose files, and image IDs, and `release-up` starts those images without building or pulling and checks the hashes. A manifest is published only for a clean tree and after successful smoke and E2E runs on those images. `release-manifest-verify` compares the running containers with the manifest. A demo stand restored from a manifest has no `/demo` guide because it uses the frontend of the main release. The assessment bank is not snapshotted in the manifest (`product_data_status` is `partial`). See [release manifest](DEPLOY.md#release-manifest).
|
||||
|
||||
## 3. Limits of the demonstration category
|
||||
|
||||
- The task bank is small and synthetic: 25 families for the full test and three for the express test. The families go through the regular publication pipeline with author and reviewer labels, but their content did not receive a subject-matter review.
|
||||
- Thresholds are not calibrated, no percentile is computed, and there is no adaptive test. The result shows the mechanics, not a measured qualification.
|
||||
- In the API the category basis is `synthetic_demo`, described in the contract as a demonstration category that is not a validated measurement. By the product owner's decision the interface shows it as an ordinary confirmation (the label "Test result"). The API and this documentation keep the basis.
|
||||
- The express test assigns no grade under any settings.
|
||||
- The consent texts C1-C5 are published by migrations as `demo`, without legal review. Do not register real people on the demo stand.
|
||||
|
||||
## 4. What is not implemented
|
||||
|
||||
The following belongs to the full product and does not work in this release:
|
||||
|
||||
- coding practice (a sandbox) and an adaptive test;
|
||||
- the final bargaining round and counter-offers: no operation creates the `counter` state, and a salary raise answers 501 `not_implemented`;
|
||||
- interview scheduling and reminders;
|
||||
- withdrawal of an invitation by the organization and cancellation by the candidate: both operations answer 501;
|
||||
- roles other than the owner and need assignments: only the owner of an organization can search, invite, and read contacts;
|
||||
- PDF documents and stored search snapshots;
|
||||
- category recommendations for a need: the need response reports the state `pending` or `not_available` with an empty list;
|
||||
- enabled ML inference: the ML service starts separately without a model, and the backend does not call it;
|
||||
- FSP integration: there is no mode, fixture provider, or call to an external API;
|
||||
- the SMTP transport: selecting `EMAIL_PROVIDER=smtp` stops the backend at startup;
|
||||
- ATS integration;
|
||||
- password reset, resume upload and parsing, and emails for events other than confirmation and a new invitation.
|
||||
|
||||
## 5. How it was verified
|
||||
|
||||
Acceptance result on the verified commit (2026-10-10): `make verify` passed, including 110 integration tests and the technical smoke; `make -C deploy test-e2e-registration` - 95 passed, 1 skipped; `make -C deploy test-e2e` - 64 passed, 32 skipped; `make -C security install test check` and `make security-images` passed with no blocking findings (the scanners ran in a Linux container, as in CI, because their installer supports only Linux; the exception for CVE-2026-93687 is valid until 2026-10-19). The boundaries of every check are described in [TESTING](TESTING.md#commands).
|
||||
|
||||
| Check | What it proves |
|
||||
| --- | --- |
|
||||
| `make verify` | Contract generation without drift, formatting, linters, types, build, Compose, documentation, backend with the race detector, integration tests on PostgreSQL, Redis, SeaweedFS, and Kafka, and a technical smoke |
|
||||
| `make -C deploy smoke` | Stack startup, dependency readiness, and dependency failures; it does not check a business flow |
|
||||
| `make -C deploy test-e2e` | The Playwright suite on a throwaway stack with mail disabled, including `mail-unavailable.spec.ts`: the user sees that the email may arrive later and cannot sign in before confirmation |
|
||||
| `make -C deploy test-e2e-registration` | Registration, confirmation by link and by code, and sign-in through the local Resend-compatible inbox, and within it `acceptance-path.spec.ts` |
|
||||
| `acceptance-path.spec.ts` | The minimal path on the real backend: five candidates, the full test with a `synthetic_demo` category, publication, a need, a search with an explanation and a filter, invitations, acceptance with C4, a contact read, a decline, C2 revocation, and no duplicates after a refresh and a double acceptance. See [the path to contacts](TESTING.md#minimal-path-from-registration-to-disclosed-contacts) |
|
||||
| `TestCompanyIsolationAndRevocationOverHTTP` | Isolation of companies and candidates, immediate closure after hiding and after revoking C4 and C2, and no contacts in the log, outbox, inbox, and mail requests. See [organization tests](TESTING.md#organization-tests) |
|
||||
| `TestInvitationNoticesSurviveRelayAndConsumerRestarts` | Exactly one notice and one email per recipient after relay and consumer restarts and a lost offset |
|
||||
| `TestHoldings`, `TestCompanyQuota` | The shared E0 quota pool inside a holding and no overrun under concurrent reservations |
|
||||
| `make -C security check`, `make -C security images` | Dependency vulnerabilities, secrets, dangerous constructs, and images; see [SECURITY](SECURITY.md) |
|
||||
| `make -C deploy check-demo`, `make docs-check` | Guards of the demo stand targets and the documentation structure |
|
||||
| `make -C deploy release-smoke`, `release-e2e` | The same smoke and browser suite on the release images; a passing run produces evidence for the manifest |
|
||||
|
||||
The checks do not prove: assessment calibration, match accuracy, email delivery through the real Resend, operation behind HTTPS, and production load.
|
||||
+27
-35
@@ -1,62 +1,54 @@
|
||||
# Security checks
|
||||
# Security
|
||||
|
||||
The repository provides local and CI checks for known dependency vulnerabilities, selected configuration risks, secrets, and selected unsafe source patterns. These checks cover the technical scaffold. They do not establish complete security or verify future authorization and personal-data workflows.
|
||||
Server-side authorization and service boundaries protect data. Scanners check known vulnerabilities and selected risky patterns; they do not replace business-flow checks or an audit.
|
||||
|
||||
## Commands
|
||||
## Checks
|
||||
|
||||
Run from the repository root:
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
make -C security install
|
||||
make -C security check
|
||||
make -C security test
|
||||
make -C security test check
|
||||
make -C security images
|
||||
```
|
||||
|
||||
Installation requires Python, uv, Go, and network access. The Trivy/Gitleaks binary installer supports Linux amd64 and arm64. Tools stay in `security/.bin/`, `.tools/`, and `.cache/`; installation does not change global tools. The installer selects current stable Trivy and Gitleaks releases and verifies their downloaded archives against upstream SHA256 checksums. govulncheck is installed with `go install ...@latest`. Semgrep uses an isolated uv tool environment with Python 3.13; uv stores its managed Python under `security/.tools/python/`. Tool versions may change on a later installation; inspect installation output when reproducing a finding.
|
||||
|
||||
| Target | Scope |
|
||||
| Tool | Current scope |
|
||||
| --- | --- |
|
||||
| `filesystem` | Trivy scans repository dependencies and configuration with `trivy/filesystem.yml` |
|
||||
| `secrets` | Gitleaks scans tracked and non-ignored untracked files, plus all available Git history with `gitleaks/gitleaks.toml` |
|
||||
| `go` | govulncheck analyzes the backend's use of known vulnerable Go code |
|
||||
| `semgrep` | Local rules in `semgrep/frontend.yml` and `semgrep/python.yml` inspect frontend and ML source |
|
||||
| `rule-test` | Semgrep fixtures check expected matches and non-matches for the local rules |
|
||||
| `test` | Runs Semgrep rule fixtures and tests for installer integrity, Gitleaks input and report handling, govulncheck failure status, and stale reports |
|
||||
| `check` | Runs filesystem, secrets, Go, and Semgrep checks; attempts every check and returns failure if any fails |
|
||||
| `images` | Builds backend, frontend, and ML images, then scans each exact local image ID with Trivy |
|
||||
| Trivy filesystem | Repository dependencies, lockfiles and configuration |
|
||||
| Gitleaks | Tracked and non-ignored files, complete available Git history |
|
||||
| govulncheck | Use of vulnerable code in `backend/` |
|
||||
| Semgrep | Local rules for `frontend/src/` and `ml/src/` |
|
||||
| Trivy images | Exact local backend, frontend and ML image IDs |
|
||||
|
||||
Gitleaks requires a full Git checkout. A missing repository or shallow history fails the check rather than silently omitting history. Its current-file scan uses tracked files and untracked files that Git does not ignore. Tracked ignored files remain in the scan, while ignored local files such as `.env` stay out of it. Deleted tracked paths and symlinks are omitted from the current scan; symlink targets are never followed or read. The history scan still covers every ref, including values committed before a file was ignored or removed. Gitleaks copies the current input set to an owner-only temporary directory and fails if either scanner fails or its JSON report is missing or invalid. Reports redact detected secret values. Developer tool caches and build output are excluded where configured; application lockfiles remain scan inputs. Trivy also recognizes `requirements-*.txt`, including `backend/requirements-quality.txt` and `scripts/requirements-codegen.txt`.
|
||||
These checks do not include separate runner/labd Go modules or images. The backend Go linter also runs gosec. Image checks need Docker; installation needs network access, Python, uv and Go. Tools are installed locally, and current versions are recorded with reports.
|
||||
|
||||
Image checks require Docker. The backend build context is `backend/`; frontend and ML use the repository root. Images are tagged `lincodex-security-<service>:local` and resolved to image IDs before scanning. This command does not start containers or publish images. Scanning frontend source dependencies remains necessary because the final Nginx image contains compiled assets rather than the development dependency tree.
|
||||
Trivy `HIGH`/`CRITICAL` findings, including unfixed vulnerabilities, block the check. Other scanner findings and tool errors fail too. Incomplete Git history and missing or corrupt reports are not success. Reports in `security/reports/` are local and redact secret values; review before sharing.
|
||||
|
||||
## Findings and exceptions
|
||||
CI calls the same Make targets. A workflow file does not prove a successful run on the current code; releases need evidence from the actual run. Images must be checked alongside source lockfiles: a static frontend image does not contain every development dependency.
|
||||
|
||||
Trivy findings of severity `HIGH` or `CRITICAL` fail the check, including findings without a published fix, unless an active, narrowly scoped exception applies. Gitleaks findings, configured Semgrep findings, govulncheck findings, and scanner errors also fail their targets. The existing Go lint configuration retains gosec; this complements the added checks.
|
||||
## Exceptions
|
||||
|
||||
Review the reported package, installed version, affected path, and available remediation before changing dependencies or configuration. Keep reports local: `security/reports/` is ignored. govulncheck uses text output so its native failure status is preserved. Trivy saves JSON reports and prints their tables in the check log. A scan error, missing report, or report conversion error keeps the check failing.
|
||||
[Trivy ignore](../../security/trivy/ignore.yml) contains a specific exception for `CVE-2026-93687`, `braces@3.0.3` in the frontend lockfile, until 2026-10-19. It was accepted when no fix was available; maintainers must remove it after updating or review it before expiry. It does not exclude all package versions or images.
|
||||
|
||||
One temporary exception in [security/trivy/ignore.yml](../../security/trivy/ignore.yml) was approved by the project owner on 2026-10-05: `CVE-2026-93687` for `pkg:npm/braces@3.0.3` in `frontend/pnpm-lock.yaml`. At approval, no fixed release was available; the exception unblocks dependency CI until its expiry on 2026-10-19. Project maintainers own the exception and must remove it when a fix becomes available or review it before expiry. Trivy enforces the expiry date. Only filesystem scanning uses this exception file; suppressed findings remain visible in its JSON report. Image scanning is unaffected.
|
||||
The [Gitleaks allowlist](../../security/gitleaks/gitleaks.toml) limits exceptions to exact test examples, paths and rules. Manual review is due on 2026-11-07; Gitleaks does not enforce that date. New exceptions require a specific finding, reason, owner and expiry. Do not disable scanners or hide every unfixed vulnerability to make CI pass.
|
||||
|
||||
Eight Gitleaks exceptions cover exact public API examples, test fixtures, a release-manifest fixture, and a fixed Redis rate-limit key prefix. Each requires the matching rule ID, repository path, and complete finding text. Project maintainers own them. Manually review or remove them by 2026-11-07; Gitleaks does not enforce that review date. See the official [Gitleaks configuration reference](https://github.com/gitleaks/gitleaks#configuration) for allowlist behavior.
|
||||
## Data and network boundaries
|
||||
|
||||
For any further exception, scope it to the specific finding and affected input, record the reason, owner, and expiry, and have the change reviewed. The current integration does not enforce expiry uniformly across every tool, so review expiry explicitly where needed. Do not disable an entire scanner or globally suppress unfixed vulnerabilities to obtain a passing result.
|
||||
- Authorization, company membership, consent, publication and contact grants are checked on the server at each access. A cache, snapshot or hidden button is not authorization.
|
||||
- Passwords, session tokens, one-time codes, contacts, resume text and request bodies must not enter logs or metric labels. Verification mail sends the code only to its recipient; API errors do not disclose internal error text.
|
||||
- SeaweedFS stays on a separate internal network; browsers receive neither S3 keys nor direct bucket access. Some internal interfaces do not enforce S3 authentication, so network membership is tightly limited.
|
||||
- Secrets belong in the local environment or secret files, not Git. Nginx does not publish readiness, metrics or administration interfaces.
|
||||
|
||||
## Outbound requests and ML
|
||||
|
||||
- GitHub. Project repository checks call only `https://api.github.com`: the profile accepts an address only as `https://github.com/<owner>/<repo>`, the owner and name are checked against the GitHub patterns and escaped into the path, the base origin is fixed in code (tests replace it only inside the package), no proxy from the environment is used, TLS 1.2+, connect and response timeouts, a redirect is followed only to the same origin (at most three), responses are capped at 1 MiB and the README at 64 KiB. User input therefore cannot point the server at another host (SSRF). The checks are off by default (`GITHUB_REPOSITORY_CHECKS_ENABLED`), a repeated check is limited per candidate (`REPOSITORY_CHECK_INTERVAL`), and the GitHub limit is respected from its headers.
|
||||
- Token. `GITHUB_TOKEN` is optional, needs read access to public data only, and is sent only to `api.github.com`; it never reaches logs, errors, jobs, or the database. The check log carries the job id, attempt, state, and error class, never the repository; the job key and payload carry only a digest of the repository.
|
||||
- GitHub data. The description, topics, languages, and README text are untrusted data: the README becomes plain text, is stored only for a public repository, is used only for ranking, and is never shown, let alone as HTML. The repository address and owner never reach an organization, neither in the card, nor in the explanation, nor after C4.
|
||||
- ML. Every route of the service except `/healthz` and `/readyz` requires `Authorization: Bearer <token>`: a shared random token of at least 32 printable characters (`ML_SERVICE_TOKEN` in the backend, `ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE` in the service) is compared in constant time and never reaches a log, a response, or an error message; a missing or wrong token answers 401 `unauthenticated`, and the request is refused before its body is read. Without a token the service answers loopback callers only, and the entry point `python -m lincodex_ml.serve` refuses to listen on a non-loopback address; the backend does not enable semantic matching without a token. In Compose the backend reaches the service over the network (`http://ml:8000`) and the host port is loopback; on a GPU host it listens on a private LAN address without TLS, so restrict the port to the app host address with host or network rules. `/metrics` requires the token too. The backend sends ML only the texts of the published card and of the organization's need, with no contact and no private profile. The weights are pinned by lock files with SHA-256, no remote model code is executed, no pickle is loaded, and the service runs offline.
|
||||
GitHub checking is disabled by default. It accepts only public `https://github.com/<owner>/<repo>` links, calls the fixed `api.github.com` origin, and bounds redirects, time and response size. An arbitrary URL cannot become a network destination. README and metadata remain untrusted data; they are not executed or rendered as user HTML. Tokens stay out of jobs and logs.
|
||||
|
||||
## CI and limits
|
||||
Backend sends ML only the allowed card and hiring-need projections, without contacts or private profiles. Every ML route except `/healthz` and `/readyz` requires a bearer token; without one, the service accepts loopback clients only. `/metrics` uses the same token, but the current Prometheus ML scrape does not yet send it. Restrict ML port access across hosts: a token does not encrypt HTTP traffic.
|
||||
|
||||
CI runs `make -C security test check` for source checks and `make -C security images` for images, and includes both jobs in its required aggregate result. Reports are uploaded as artifacts with a 14-day retention period, including when checks fail. Gitleaks redacts secret values, but reports can still reveal repository paths and dependency details; restrict artifact access accordingly.
|
||||
|
||||
The local Semgrep rules are a bounded frontend/ML rule set, not a complete application audit. Scanner results depend on the actual checkout, rule versions, vulnerability databases, build inputs, and time of execution. Checked-in workflows do not prove that a GitHub run occurred or that the current tree is free of findings. Record actual results when preparing a release; see [TESTING.md](TESTING.md) for other validation boundaries.
|
||||
Model files are pinned by SHA-256 and loaded locally; remote model code and pickle are not executed. Model output is data, not an instruction to run a command, use a tool or change permissions.
|
||||
|
||||
## Code runner VM
|
||||
|
||||
The code runner executes untrusted candidate code, so production runs it only in the LXD VM `lincodex-runner` (see [DEPLOY.md](DEPLOY.md#production-the-runner-vm)). The boundary has three layers: nsjail with seccomp, namespaces, cgroup v2 limits, and no network for the program; a separate guest kernel; and the bridge ACL, which lets only the app network and the host side open TCP 8443 and drops every connection the guest starts. The VM holds only its own TLS pair and API token. The CA key and the database, mail, storage, and identity secrets never enter it, and it has no shared folder, no Docker socket, and no guest API (`security.devlxd=false`).
|
||||
Production runs the runner in a dedicated VM. Inside it, nsjail restricts programs through namespaces, seccomp, cgroup v2 and no network. The VM receives no database, mail, storage or identity secrets, shared directories or Docker socket. TLS and a token protect the API; network ACLs restrict access and guest-initiated connections.
|
||||
|
||||
`make -C deploy check-runner-vm` checks the VM script without LXD. On the app host, `make -C deploy runner-vm-check` checks the running VM and `make -C deploy runner-vm-a16` runs the hostile-program suite in it. These checks do not cover vulnerabilities of the kernel, QEMU, KVM, nsjail, or LXD, side channels, or the host itself: the `lxd` group is equivalent to root on the host, and its members can open a root shell in the guest through the LXD agent. The token is a shared secret without automatic rotation: to replace it, remove `api-token` from the secrets directory, run `runner-vm-secrets` and `runner-vm-install`, and give the backend the new value. The VM has no monitoring yet.
|
||||
`make -C deploy check-runner-vm` checks configuration without starting a VM. Live VM and isolation checks run separately as described in [DEPLOYMENT.md](DEPLOYMENT.md) and [TESTING.md](TESTING.md). They do not establish that the kernel, hypervisor or nsjail has no vulnerabilities. A privileged development container is not the production boundary; automatic token rotation and VM monitoring are not connected yet.
|
||||
+99
-670
@@ -1,715 +1,144 @@
|
||||
# Checks and quality evaluation
|
||||
# Testing
|
||||
|
||||
Routine checks prove individual code properties. They do not establish ranking accuracy, grade validity, production latency, or complete product readiness.
|
||||
[Русский](../ru/TESTING.md)
|
||||
|
||||
Choose checks for the change. Unit tests cover rules, integration tests exercise real dependencies, and browser E2E tests exercise user actions. Run commands from the repository root.
|
||||
|
||||
## Commands
|
||||
|
||||
Use the root Make targets:
|
||||
| Area | Command | Requirements |
|
||||
| --- | --- | --- |
|
||||
| Backend, fast tests | `make -C backend test-fast` | Go |
|
||||
| Backend, race | `make -C backend test` | Go and a C toolchain |
|
||||
| Backend, integration | `make -C backend test-int` | Go, Python 3, Docker |
|
||||
| Frontend | `make -C frontend check` | Node.js, pnpm, installed dependencies |
|
||||
| ML API | `make -C ml verify` | Python, uv, installed dependencies |
|
||||
| Contracts | `make -C api check` | Installed API tools |
|
||||
| OpenAPI 3.2 generators | `make -C api check-toolchain` | Go, frontend, and ML toolchains |
|
||||
| Technical smoke | `make -C deploy smoke` | Docker Compose |
|
||||
| Browser E2E | `make -C deploy test-e2e` | Docker Compose, frontend dependencies |
|
||||
| E2E with mail | `make -C deploy test-e2e-registration` | The same dependencies |
|
||||
| Documentation | `make docs-check` | Python 3 |
|
||||
|
||||
make test
|
||||
make check
|
||||
make verify
|
||||
make docs-check
|
||||
`make test` runs service tests. `make check` adds formatting, lint, types, builds, and configuration checks. `make verify` also generates code and checks drift, the OpenAPI toolchain, backend race tests, integration tests, and smoke.
|
||||
|
||||
make test runs backend, frontend, and ML tests. make check also runs API contract, formatting, lint, type, build, Compose, observability, and documentation checks. make verify sequentially generates contracts, checks generated drift, runs root check, API toolchain/backend race and integration checks, and then starts an isolated deployment smoke. It uses Docker.
|
||||
Playwright, security scanners, real ML models, and the runner sandbox have separate checks. Passing `verify` does not replace them.
|
||||
|
||||
Useful focused commands:
|
||||
## Backend: unit and race
|
||||
|
||||
| Command | Coverage |
|
||||
| --- | --- |
|
||||
| make -C api check | Schema merge, bundles, OpenAPI lint, merge-script tests |
|
||||
| make -C backend test | Go unit suite with race detector |
|
||||
| make -C backend test-fast | Faster Go tests without race instrumentation |
|
||||
| make -C backend test-int | Go integration tests with Testcontainers/PostgreSQL/Redis/SeaweedFS/Kafka |
|
||||
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries, build |
|
||||
| make -C ml check | Ruff, mypy, pytest, and wheel build |
|
||||
| make -C ml check-generated | Pydantic models match the ML bundle without rewriting files |
|
||||
| make -C deploy config | Render Compose configurations without starting them |
|
||||
| make -C deploy check | Render Compose configurations and run `check-workflows`, which fails when a workflow `aggregate` job does not need every other job or lacks `if: always()`, and `check-release`; see [Release manifest tests](#release-manifest-tests) |
|
||||
| make -C deploy smoke | Isolated technical smoke of service health routes |
|
||||
| make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack |
|
||||
| make -C deploy release-smoke, release-e2e | The same smoke and browser suite against the release images; a passing run records evidence for the release manifest |
|
||||
| make -C observability check | Validate Prometheus config and alert rules with their unit tests, Loki, Alloy, and dashboard JSON |
|
||||
| make -C observability verify-product-metrics | Isolated core and monitoring stacks: product metrics in Prometheus and Grafana, no fixture address in metrics or Loki logs; see [Product metrics tests](#product-metrics-tests) |
|
||||
Tests next to source files cover domain/usecase behavior and adapters without external infrastructure. Use configured mockery mocks or small behavior-specific fakes for ports.
|
||||
|
||||
make -C deploy test-e2e currently runs a technical browser suite, not a business-flow suite; see [Browser E2E suite](#browser-e2e-suite).
|
||||
```sh
|
||||
make -C backend mocks
|
||||
make -C backend test-fast
|
||||
make -C backend test-race
|
||||
```
|
||||
|
||||
make -C ml check-generated uses datamodel-code-generator --check: a mismatch fails the check and leaves the models file unchanged. Prepare the bundle with make -C api bundle before checking; use make -C ml generate to update Python models. Generated models do not establish inference functionality or support for every OpenAPI 3.2 feature.
|
||||
For a changed workflow, cover success, domain rejection, and dependency failure. Concurrent operations need version, retry, and cancellation checks. Assert results and persisted effects rather than incidental internal call order.
|
||||
|
||||
Security checks run separately: `make -C security check` scans source/dependencies/secrets, `make -C security test` validates local Semgrep fixtures, installer integrity, and govulncheck failure handling, and `make -C security images` builds and scans all three service images. Install tools with `make -C security install` first. Scanner failure is a failed check, not a clean result. See [SECURITY.md](SECURITY.md) for Git/Docker requirements, blocking findings, and CI reports.
|
||||
## Integration tests
|
||||
|
||||
## Current scaffold coverage
|
||||
Tests in `backend/integration_test/` use the `integration` build tag and Testcontainers with real PostgreSQL, Redis, SeaweedFS, and explicitly selected Kafka.
|
||||
|
||||
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the private file layer and SeaweedFS access controls (see [Private file storage tests](#private-file-storage-tests)), the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. Registration and email confirmation have API integration coverage; login, assessment, search, invitation, and file workflows are not implemented. Confirmation writes an event to the transactional outbox, with no registered product consumer for that event; mail delivery is tested separately. There is no real model inference to validate as product behavior.
|
||||
```sh
|
||||
make -C backend test-int-compile
|
||||
make -C backend test-int-list
|
||||
make -C backend test-int
|
||||
```
|
||||
|
||||
TestEmailVerificationOverHTTP obtains a token from the Resend fixture after registration. It checks candidate and employer confirmation, no session or cookie, and unchanged state after an unknown, expired, replaced, or consumed token, a wrong password, or missing pending credentials. It also checks C1 version binding, missing, null, and foreign Origin values, plus rate limits, expiry after a lock wait, rollback after an outbox failure, and one event from concurrent confirmations. It covers the API only and does not send through an external mail provider. The separate local registration browser flow covers the frontend.
|
||||
`test-int-compile` compiles without containers; `test-int-list` lists selected top-level tests. Neither command proves that scenarios passed. `test-int` requires working Docker and fails if it is unavailable.
|
||||
|
||||
TestEmailVerificationCodeOverHTTP (`backend/integration_test/email_code_test.go`) takes the code and the link from the same fixture message. It checks that the code confirms like the link; that five wrong codes burn the token, after which the right code and the link both fail; that eight concurrent wrong codes count exactly five attempts; that a wrong password counts; that an expired code leaves the link valid; that the link and the code consume one token in either order; that a resend replaces the code; that a registration replaced by another registration cannot be confirmed with its code; that an unknown address and a wrong code give the same refusal; and that the address limit answers 429 after ten requests. Its origin case refuses a foreign Origin before the usecase runs.
|
||||
### Shared bootstrap
|
||||
|
||||
API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub.
|
||||
In `bootstrap_test.go`, `bootstrap(t)` starts PostgreSQL, Redis, and SeaweedFS, applies migrations, and returns configuration and clients. Select only what a test needs, for example `bootstrap(t, postgresService)` or `bootstrap(t, postgresService, kafkaService)`.
|
||||
|
||||
Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, isolation of SeaweedFS from the frontend (by name and by its storage network address), rejection of filer, master, and volume HTTP requests that do not come from inside the SeaweedFS container, and the backend startup log for `EMAIL_PROVIDER=disabled`. The backend relay connects to Kafka in the smoke stack, but the smoke does not check that it publishes. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
|
||||
Each call owns its containers and dynamic ports. `t.Cleanup` releases resources, including after startup failures. Call bootstrap in a parent test and share its environment with subtests; keep neighboring tests' data isolated.
|
||||
|
||||
Shared helpers create pools, separate databases, and Kafka topics. Use them instead of duplicating container setup. Add the HTTP server and domain fixtures for the specific scenario.
|
||||
|
||||
For SQL, check real transactions, constraints, and migrations. For outbox and events, check repeated delivery and recovery after failure. For data access, cover allowed requests, another account/organization, and revoked permission.
|
||||
|
||||
`TestCompanyQuota`, `TestHoldings` and the holding migration test check real PostgreSQL quotas: window boundaries, retries, the shared E0 pool, concurrency, policy changes and guarded rollback. Separate HTTP tests cover invitation sending, company isolation and immediate contact closure after revocation.
|
||||
|
||||
### Shards
|
||||
|
||||
`backend/scripts/run-integration-suite.py` discovers tests and distributes a sorted list. A top-level test and all its subtests stay in one shard. Indexes start at 1; set both variables together.
|
||||
|
||||
```sh
|
||||
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int-list
|
||||
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
make -C backend test-scripts
|
||||
```
|
||||
|
||||
With no variables, the whole suite runs. CI uses two shards. `test-scripts` checks distribution coverage, test selection, and failure propagation. Distribution is deterministic but does not balance individual test durations.
|
||||
|
||||
## Frontend
|
||||
|
||||
Vitest runs in Node and checks logic, data transformations, and components in its available environment. Browser specs in `frontend/e2e/` are excluded from this run.
|
||||
|
||||
```sh
|
||||
make -C frontend test
|
||||
make -C frontend typecheck
|
||||
make -C frontend check
|
||||
```
|
||||
|
||||
`check` includes formatting, ESLint, Stylelint, types, Vitest, FSD boundaries, and a production build. MSW and replaced API responses verify frontend behavior, not server authorization or persistence.
|
||||
|
||||
## Browser E2E suite
|
||||
|
||||
`make -C deploy test-e2e` runs the Playwright suite from `frontend/e2e/` in Chromium against the real frontend and backend images. It needs Docker and frontend dependencies installed with `make -C frontend install`; no browser is installed on the host. `deploy/scripts/e2e.sh` does the following:
|
||||
|
||||
- Reads the exact `@playwright/test` version from `frontend/package.json`, checks that the installed package matches it, and runs the suite in the official `mcr.microsoft.com/playwright:v<version>-noble` image with `frontend/` mounted read-only.
|
||||
- Starts the core stack under a unique project `lincodex-e2e-<random>` with fresh volumes and a generated throwaway env file: random passwords, `EMAIL_PROVIDER=disabled`, no mail transport settings. Shell variables other than Docker client settings do not reach Compose. The run refuses to reuse an existing project, network, or volume.
|
||||
- Publishes no host port. The browser container shares the frontend container's network namespace, so it opens `http://localhost:8080`, the same loopback origin as `APP_PUBLIC_URL`. The Playwright config refuses a base URL outside a loopback host.
|
||||
- Runs Playwright with the host UID/GID on rootful Docker; on rootless Docker it uses container UID 0, which maps to the owner of the host artifact directory. The runner drops all capabilities and mounts the source read-only.
|
||||
- Waits for backend readiness, runs the suite with retries disabled, and returns its exit code; make reports any failure as exit status 2.
|
||||
- Removes the containers, volumes, network, locally built images, and env file on every exit, including failures and interrupts. Only the cached Playwright image and the build cache remain.
|
||||
|
||||
Every browser of a run reaches the stand from the same client address: the browser container shares the frontend container's network namespace, so the app Nginx sees all requests from loopback. The per-address limit on `/api/v1/` (20 requests per second with a burst of 60, `deploy/nginx/nginx.conf` and `deploy/nginx/conf.d/app.conf`) is therefore one budget for the whole suite. A 429 from that limit is a failed stand, not a result of the flow under test, and the production limits stay unchanged; `deploy/scripts/test_perimeter.py` keeps checking them. The suite stays inside the budget by design. `frontend/playwright.config.ts` runs one worker. `frontend/e2e/assessment.spec.ts` pauses 250 ms after each saved answer of a full attempt, because a candidate reads each item. The real-bank search in `frontend/e2e/match-search.spec.ts` runs first, in its own project: an unfiltered bank search keeps ten entries per group, so candidates published by earlier specs would decide which entries the test sees. On the stand, a replay of this limit over the access log peaked at about two thirds of the burst with one worker and within about ten requests of it with two workers.
|
||||
|
||||
Artifacts of the last run are in `frontend/test-results/e2e/`, which Git ignores; the runner prints the path. `report/` holds the HTML report (`pnpm exec playwright show-report test-results/e2e/report` from `frontend/`). For each failed test, `results/` keeps `trace.zip` and a screenshot (`pnpm exec playwright show-trace <trace.zip>` needs a local browser; trace.playwright.dev opens the file without one). After a failed run, `stand.log` holds the stack logs. `E2E_SPEC_DIR=<dir>` runs specs from another directory, such as a scratch copy, against the same isolated stack.
|
||||
|
||||
## Local registration browser tests with a mail fixture
|
||||
|
||||
`make -C deploy test-e2e-registration` runs the same disposable browser stack with the additional `docker-compose.e2e-mail.yml` overlay. Only this mode builds the backend with the Go `e2e` build tag: its Resend constructor uses the fixed `http://mail-fixture:8025/emails` endpoint, and Compose supplies a synthetic key. Before Playwright starts, the runner sends one synthetic message through the Compose network, replays the same idempotency key, and verifies the message in the authenticated inbox. The `mail-fixture` service accepts Resend-compatible requests, deduplicates by key, and keeps at most 64 messages and 256 requests of up to 32 KiB each in memory. Its inbox requires bearer authentication, returns only messages for the requested `to`, and is reachable inside the stack. The registration network is marked internal, the fixture is not connected to the storage network, and no host port is published; requests cannot reach an external mail provider. Cleanup removes the containers and inbox.
|
||||
|
||||
Playwright receives `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8025/__e2e/inbox`, and the synthetic `E2E_MAILBOX_TOKEN=local-e2e-mailbox-token`. A test requests `GET $E2E_MAILBOX_URL?to=<urlencoded email>` with `Authorization: Bearer $E2E_MAILBOX_TOKEN`; the response contains `messages` with `id`, `to`, `subject`, `text`, and `html` fields. Registration-only tests should skip unless `E2E_MAIL_FIXTURE=1`, because neither ordinary `test-e2e` nor `release-e2e` sets it. Tests must not print message content or a link containing a one-time token. The runner disables Playwright tracing in this mode. The ordinary `test-e2e` still sets `EMAIL_PROVIDER=disabled`, and `release-e2e` uses release images without the fixture and records no evidence for a mail-fixture image. The registration mode refuses to run with `LINCODEX_RELEASE_TAG`.
|
||||
|
||||
The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Business tests use synthetic data in each fresh stack: registration through the public API and the separately documented test fixture for consent scopes. No real data are used.
|
||||
|
||||
`frontend/e2e/mail-unavailable.spec.ts` runs only in the ordinary `test-e2e`, whose stand sets `EMAIL_PROVIDER=disabled`, and skips when `E2E_MAIL_FIXTURE=1`. On the real backend it registers a candidate (202 `accepted`) and checks that the step waits for the message ("Запрос принят", "Письмо может прийти не сразу") and never says that a message was sent or delivered. A guessed code and a forged link answer 400 `verification_token_invalid`; the correct password answers 403 `email_not_verified` with the message in the form; afterwards `GET /api/v1/identity/sessions/current` and `GET /api/v1/me/profile` answer 401 and `/candidate` shows the sign-in page. The browser cannot see the delivery row: that it stays `pending` without an attempt while the transport is disabled is checked by the `EMAIL_PROVIDER=disabled` subtest of `TestServiceMailSending`.
|
||||
|
||||
The ordinary technical suite does not cover candidate or employer workflows beyond the unconfirmed registration of `mail-unavailable.spec.ts`, a successful sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, or screen readers. Its stubbed checks of the minimal path states, focus, and overflow are described in [Minimal path states and accessibility](#minimal-path-states-and-accessibility). CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-<n>` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate.
|
||||
|
||||
The registration-mode suite additionally runs `frontend/e2e/auth-registration.spec.ts`: candidate and employer registration with visible C1, real local resend and a distinct received message, same-tab replacement of the verification link, wrong-password retry, confirmation without automatic login, sign-in, and restoring the server step after reload. It checks keyboard focus and overflow at 360, 768, and 1280 pixels. Expired-link rendering uses a controlled problem response; actual token expiry is covered by backend integration tests. Only this isolated overlay sets `VERIFICATION_MAIL_MIN_INTERVAL=1s`; normal and release environments retain their configured interval. Auth traces, failure screenshots, and video are disabled; explicit review screenshots show only token-free states and synthetic addresses. No external mail or production edge flow is verified.
|
||||
|
||||
Since the code step, the same suite confirms each candidate and employer registration with the six-digit code from the message: a wrong code first, a reload that asks for the password again, and a check that no browser storage holds the password. A separate test keeps the link as the fallback: an expired link leads to the code step, which sends a new message, and the link from that message then confirms the registration.
|
||||
|
||||
In the same mode, the runner invokes `/consent-fixture` from the test backend image before starting the browser. The command exists only with the Go `e2e` build tag, requires `E2E_CONSENT_FIXTURE=1`, and uses domain objects and transactional ports to create a synthetic verified candidate, C1/C2, and two C4 scopes for different companies. A collision with an existing test address stops the run. Ordinary and release images contain neither the command nor its enabled flag. `frontend/e2e/consent-management.spec.ts` uses normal sign-in and real consent APIs to grant C3 independently, revoke C2 and one C4, retain the other scope, reload, and submit a C1 request whose returned status is shown. A controlled 403 exercises the failure UI; successful mutations reach PostgreSQL. Synthetic invitation IDs in the fixture do not prove the invitation acceptance flow. Traces and automatic screenshots are disabled; the explicit review screenshot contains only synthetic data.
|
||||
|
||||
The same command also seeds a second synthetic candidate for `frontend/e2e/privacy-visibility.spec.ts`: an active C1 and C2, one C4 for the first of two new companies, and three recorded card reads (a card view and a contact read by the first company, a card view by the second). The reads are inserted through the privacy port because the organization read path needs search results that do not exist yet; they do not prove that path. With the real backend, the suite confirms the search status without publishing, publishes after the explicit C2 step, compares the owner preview with the API response, hides one company and brings it back, revokes C2 and checks the closure explanation, grants C2 again without reopening the card, and republishes with the keyboard alone; in the mail-fixture mode a freshly registered candidate with two declared specializations and no test publishes and sees the not-confirmed grade status for each. A stubbed group renders a confirmed Backend next to unconfirmed specializations, the evidence basis and calibration labels, empty histories, a failed save that keeps the draft, and a revoked C2. No test reads the card as an employer, so the immediate loss of access of a hidden employer is not checked in a browser.
|
||||
|
||||
`frontend/e2e/profile-edit.spec.ts` walks the steps of the manual profile at 360px after real registration ("Далее" with the focus on the heading, a step blocked until overlapping periods are confirmed, "Назад" without losing data), acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step.
|
||||
|
||||
`frontend/e2e/candidate-home.spec.ts` has two parts. In the mail-fixture mode a candidate goes through registration, a profile with only a name (no FSP ID linking), the questionnaire, and signing in again: the home leads to the profile, then the questionnaire, then the test, shows the declared level apart from the empty confirmed category, and matches the `GET /me/assessment-availability` answer after a page refresh. The saved step stays "Consents" throughout, because the server advances it only from the matching step. The second part also runs in the ordinary `test-e2e`: it replaces API answers (`page.route`) and checks only how the home renders each state - a category with the result and privacy links, an open card and search status, no category with an empty history, a failed attempt, a failed read with retry, a denied read, a failed privacy read, and an expired session. It does not prove backend behavior and does not replace a check of category assignment on a real stack, which this spec does not perform. Review screenshots (360 and 1280 px) contain only synthetic data.
|
||||
|
||||
`frontend/e2e/company-management.spec.ts` creates a company, retries a lost response with the same key and body, edits the profile, and compares its preview with the API. Controlled responses check CSRF recovery, version conflict, and a delayed response. A separate `company-fixture` performs real revocation: Go build tag `e2e`, an explicit enable flag, a random bearer token per run, no published port, and only the internal network. It validates two synthetic verified employer accounts, adds a successor owner, and revokes the original owner in one transaction while preserving the mandatory-owner constraint. The browser with its original cookie checks real API denial and removal from its directory. The control endpoint is absent from the ordinary backend and release image; its URL and token reach only the test process through `E2E_COMPANY_FIXTURE_URL` and `E2E_COMPANY_FIXTURE_TOKEN`.
|
||||
|
||||
## Minimal path states and accessibility
|
||||
|
||||
`frontend/e2e/minimal-path-a11y.spec.ts` checks the states, the keyboard path, and the error binding of the sign-in, the candidate test start and profile, the candidate inbox, and the candidate invitation screen. Failures come from route interception, so no data is needed on the stand: HTTP 500 and 403 answers, a dropped connection, and the empty and forbidden answers. Each stubbed screen is checked at 360, 768, and 1280 px for horizontal overflow; the real-backend assessment check covers 360 and 768 px. Each control reached with Tab must match `:focus-visible` and draw a focus outline. The stubbed part runs in both `make -C deploy test-e2e` and `make -C deploy test-e2e-registration`. The one real-backend test runs only in the registration mode, because it needs the mail and questionnaire fixtures.
|
||||
|
||||
The other screens of the minimal path are covered by their existing specs: the employer candidate search and match list (`match-search.spec.ts`: a failed search with a retry, a refused search, an empty result, confirmed and declared grades as text, keyboard reach at every width), the invitation compose (`invitation-compose.spec.ts`: errors bound to fields, a lost send response retried with the same key, overflow at 360, 768, and 1280 px), registration and confirmation (`auth-registration.spec.ts`), and the profile and questionnaire (`profile-edit.spec.ts`, `questionnaire.spec.ts`).
|
||||
|
||||
Checklist for the minimal path. Each item is checked by the spec named in brackets; the result is the outcome of the last run of that spec.
|
||||
|
||||
- Sign-in [`minimal-path-a11y.spec.ts`]: Tab reaches both fields and the submit control with a visible outline at 360, 768, and 1280 px. An empty submit marks both fields `aria-invalid` and gives each one its message through `aria-describedby`. A failed answer keeps the typed email and keeps the focus in the form. While the answer is pending, the password field stays focused and read-only; it is not disabled, because a disabled field drops the focus.
|
||||
- Candidate profile [`minimal-path-a11y.spec.ts`]: a loading text while the profile loads, an alert with a retry after a failed load, and no retry after an access refusal.
|
||||
- Candidate test start [`minimal-path-a11y.spec.ts`]: an alert with a retry after a failed availability read; a candidate without a specialization sees the empty state with a link to the questionnaire.
|
||||
- Candidate inbox [`minimal-path-a11y.spec.ts`]: a loading text; a server error or a dropped connection gives an alert with a retry that works from the keyboard; the empty state; no retry after an access refusal; each card names the company, the role, and the state as text.
|
||||
- Candidate invitation [`minimal-path-a11y.spec.ts`]: an alert with a retry after a failed load; a failed decline keeps the chosen reason and the comment and moves the focus to the alert; the declined state is shown as text.
|
||||
- Assessment on a phone with the real backend [`minimal-path-a11y.spec.ts`, registration mode]: an unsent numeric answer survives a reload at 360 px, and the stored copy is removed when the answer is accepted.
|
||||
- Employer match list and invitation compose: see the specs named above; the compose page is also checked at 768 px.
|
||||
- Not covered by these checks: screen reader output, the contrast of the focus outline, and zoom above 200 percent. They were not checked by hand in this pass.
|
||||
|
||||
An unsent answer is kept in `sessionStorage` of the same browser tab, under a key that names the attempt and the item. It is never sent to the server. A reload restores it only when it fits the item; a stored value larger than 64 KiB is not kept; a blocked or full store leaves the answer in the form only. An accepted answer removes the stored copy. Answers accepted by the server come from the server after a reload.
|
||||
|
||||
## Release manifest tests
|
||||
|
||||
`make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile or backend/Dockerfile.demo-seed stop pinning Go 1.26.9, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that:
|
||||
|
||||
- the manifest copies no environment values, labels, or local paths, and two generations differ only in `generated_at`;
|
||||
- evidence counts only for the same tag, commit, and working tree fingerprint, and malformed evidence or build records are not used;
|
||||
- a component is `verified` only with evidence for its exact image ID, ML, monitoring, and missing components are never verified, and the release stays unverified without both smoke and E2E on the current images, on a dirty tree, with a core pulled image without a registry digest, a missing lockfile or Dockerfile, another Go version in the binary, or another Node version in the build image;
|
||||
- `release-build` refuses to write the build record when the commit or the working tree changes during the build;
|
||||
- the working tree fingerprint of a temporary Git repository ignores diff and line ending settings, covers untracked files, skips ignored ones, and leaves the real index unchanged;
|
||||
- the secret scan finds key blocks, tokens, credentials in URLs, local paths, user and host names, and values of secret-like variables, also as substrings and in base64, without echoing them;
|
||||
- the running-container comparison reports a different digest, a missing service, and an unknown service;
|
||||
- the demo seed image is built with pinned base images under its profile, recorded but never verified, and retained by its image ID; its absence blocks only the demo stand restore, a Go drift in its binary keeps the release unverified, and the demo override pins the core services and the seed to exact image IDs and digests and refuses a missing image, a changed demo overlay, or a manifest without a demo restore entry;
|
||||
- the `seed` entry hashes the non-test demo seed sources, and its version changes with them but not with a test file.
|
||||
|
||||
The test does not build images or start containers. The end-to-end path is `release-build`, `release-smoke` and `release-e2e`, `release-manifest`, `release-up`, `release-manifest-verify`, and `release-manifest-check`; see [DEPLOY.md](DEPLOY.md#release-manifest).
|
||||
|
||||
## Integration test bootstrap
|
||||
|
||||
The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling `env := bootstrap(t)` starts PostgreSQL, Redis, and SeaweedFS, waits for adapter readiness, and returns an environment with configuration and clients. To test one adapter, use `bootstrap(t, postgresService)`, `bootstrap(t, redisService)`, or `bootstrap(t, seaweedfsService)`. Multiple services can be selected.
|
||||
|
||||
Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable. Testcontainers also tries the Docker context and default sockets when `DOCKER_HOST` is unreachable, so an invalid `DOCKER_HOST` alone does not simulate a missing Docker.
|
||||
|
||||
Container startup makes at most three attempts, and only when rootless Docker returns the exact host-port networking error ending in `bind: address already in use` (`EADDRINUSE`). Before retrying, bootstrap terminates any partial container returned by the failed attempt; a cleanup error stops retries. Other startup and readiness errors, and test assertion failures, are not retried. This changes test setup behavior only and does not modify Docker or host networking configuration.
|
||||
|
||||
Bootstrap starts infrastructure and clients. When PostgreSQL is selected, it applies every embedded migration with the startup runner. `postgres_helpers_test.go` adds `env.newPool` for a pool to that database, `env.createIsolatedDatabase` for a separate database in the same container when a test changes the whole schema (for example up, down, and up again), `env.newPoolWithMaxConns` for concurrency tests that need one connection per transaction, and `truncateTables` for resetting shared tables between sequential subtests. Tests reach the transaction behind a unit of work only through `postgres.TransactionForIntegrationTest`, which is compiled only with the `integration` build tag. Test-only aggregates live in their own schema created by the test, not in production migrations. The application HTTP server, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness.
|
||||
|
||||
Kafka is not part of `bootstrap(t)` and starts only for tests that select `bootstrap(t, kafkaService)`. It runs the same `apache/kafka:latest` image as Compose with the same KRaft settings, including `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. The client listener is advertised on the dynamic host port, inter-broker and controller traffic stay on container loopback, and the data and declared image volumes use tmpfs, so a test broker leaves no volumes. Bootstrap sets `env.Config.KafkaBrokers` and creates `env.KafkaAdmin` from franz-go `kadm`.
|
||||
|
||||
`kafka_helpers_test.go` contains the helpers. `env.createKafkaTopic(ctx, t, partitions)` creates a topic with a unique random name and registers its deletion in `t.Cleanup` before creation, so the topic is removed even when the test fails. The broker never creates topics on demand: a test creates every topic it uses. `env.newKafkaClient(t, options...)` returns a `kgo` client that closes when `t` finishes. `produceKafkaRecords` and `env.consumeKafkaRecords` have bounded timeouts; the consumer reads partitions from the start without a consumer group, so no group offsets remain. The container is terminated in the cleanup of the test that called bootstrap, including after a failure. `env.pauseKafka(ctx, t)` freezes the broker with `docker pause` and returns a function that resumes it; cleanup also resumes it. A paused broker keeps its port and accepts connections but never answers, which models a hung broker. A stopped and restarted container would get a new host port that neither the advertised listener nor the clients follow, and its tmpfs topics would be gone.
|
||||
|
||||
## Private file storage tests
|
||||
|
||||
Unit tests in `backend/internal/usecase/files/` use an in-memory storage fake that, like an HTTP object store, commits an object as soon as it receives the declared number of bytes. They cover policy validation, key format and rejection of keys from other namespaces or shaped by clients, name sanitizing, the declared size limit, a source that is longer or shorter than declared (storage never receives a complete body and the key is deleted), cleanup after caller cancellation and after a lost response, a reported cleanup failure, the SHA-256 digest, a stored body that differs from its size, idempotent deletion, closing of the response on every `Open` rejection, and unique, valid declared namespaces. Adapter tests in `backend/internal/adapter/secondary/seaweedfs/` check that an upload and a download that last longer than `SEAWEEDFS_TIMEOUT` complete, while stalled response headers and an unreachable endpoint still fail within that bound.
|
||||
|
||||
The SeaweedFS bootstrap uses the same entrypoint and flags as Compose and also publishes the filer, master, and volume ports so tests can probe them. It does not model the Compose storage network; smoke checks that boundary. `TestPrivateFileStoreAgainstSeaweedFS` in `backend/integration_test/files_store_test.go` uses `bootstrap(t, seaweedfsService)` and the real adapter:
|
||||
|
||||
- writes and reads a synthetic object and an empty one, checking content, size, type, and digest;
|
||||
- sends unsigned requests and expects 403 from S3 for object reads (also with a presign-like query), bucket listing, upload, and deletion, and 401 from the filer for object reads, listing, and upload and from the master for volume assignment and collection deletion; the object stays readable afterwards;
|
||||
- assigns a file ID inside the container and expects 401 from the volume for a read without a token and for a write with the signed token that the master returned;
|
||||
- checks that a wrong secret cannot open, upload, or delete files and is not reported as absence;
|
||||
- opens, partly reads, and closes the object more times than the adapter's connection limit with a long storage timeout, so a leaked response body would block the loop;
|
||||
- rejects uploads over the limit or past or short of the declared size and lists the namespace through a separate signed client to show that no partial object remains;
|
||||
- deletes the object twice and then gets `files.ErrNotFound`.
|
||||
|
||||
The probes run from the host through published ports, so requests do not come from inside the SeaweedFS container, as for another member of the storage network. The gRPC and admin ports are not probed; their remaining exposure is described in [ARCHITECTURE.md](ARCHITECTURE.md#private-file-storage).
|
||||
|
||||
## Outbox relay tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the record envelope, key, and headers and an invalid payload that is not quoted in the error (`internal/adapter/secondary/kafka/`), a publish and a topic creation that fail within the produce timeout plus a 2-second scheduling margin when the broker is unreachable (the tests assert the elapsed time), the mapping of an unknown topic to `ErrEventDestinationMissing`, the comparison of an existing topic with the configured layout, the shared backoff schedule with and without jitter (`internal/worker/retry/`), relay passes that mark only acknowledged events, retries after failed `Prepare` calls and passes, no backoff after a pass that published part of its batch while a poison event leads every batch, a new `Prepare` after a missing destination, at most one backlog read per interval, a pass in progress that finishes after cancellation, a pass canceled by the shutdown timeout, a stop during backoff (`internal/worker/outboxrelay/`), the relay and topic settings, including the broker-default replication factor and `min.insync.replicas` (`config/`), SQLSTATE-only database errors and timeouts that would round to no limit (`internal/adapter/secondary/postgres/`), the relay counter and backlog gauges, and an application that runs the relay while serving and stops it with the servers (`internal/bootstrap/`).
|
||||
|
||||
`TestOutboxRelay` in `backend/integration_test/outbox_relay_test.go` uses `bootstrap(t, postgresService, kafkaService)`, writes events through the transactor with a test aggregate, and runs these sequential cases, each with its own topic:
|
||||
|
||||
- A committed event is published as the documented envelope with its key and headers, and `published_at` is set.
|
||||
- Kafka outage: with the broker paused, a business transaction still commits, the relay pass fails within the produce timeout, both events stay pending, and the business rows are intact. After the broker resumes, the relay publishes both and a consumer receives them with their `event_id`.
|
||||
- Failure between publish and mark: a publisher wrapper produces for real and then cancels the pass, as a killed process would; the row stays pending, and a new relay publishes it again, so the topic holds two records with the same `event_id`.
|
||||
- Competing claims: while one claim holds the earliest events of two aggregates, a second claim on a pool with a 500 ms `lock_timeout` gets only the third aggregate, without waiting and without the first aggregate's version 2; the next pass gets version 2.
|
||||
- Two relays run while 12 concurrent writers each commit 8 versions of their own aggregate. Every event is published, each aggregate stays in one partition, and the first delivery of each version follows `aggregate_version` order. A publisher wrapper adds 10 ms to every publish so the relays' passes overlap; the test logs how many events each relay published.
|
||||
- Shutdown with the broker paused and a 30-second produce timeout: the relay stops no sooner than the 1-second shutdown timeout and within 5 seconds after it, so only the shutdown timeout could have ended the pass; its event stays pending, and no connection stays busy.
|
||||
- Idle timeout: a claim whose publish callback ignores its context for 2 seconds, with a 300 ms `idle_in_transaction_session_timeout`, fails with SQLSTATE 25P03; the event stays pending, and no connection stays busy.
|
||||
- `Backlog` reports zero for an empty outbox and two pending events with a positive age after two writes.
|
||||
- `Prepare` creates a topic with the configured partitions, the broker default replication factor, and a topic-level `min.insync.replicas`, and accepts the topic again.
|
||||
|
||||
The suite runs against one broker and one PostgreSQL. It does not measure throughput or latency, and does not cover broker failover or replication. Consumers are covered in [Event consumer tests](#event-consumer-tests).
|
||||
|
||||
## Event consumer tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the consumer runtime with a fake source, store, and handler (`internal/worker/eventconsumer/`): applied, duplicate, and ignored records committed in poll order; store failures retried beyond the attempt limit without a dead letter, with the offset committed only after the store succeeded; a handler that keeps failing, retried exactly `MaxAttempts` times with at least the minimum backoff between attempts, then dead-lettered with its event ID, type, value size, and SHA-256 while the next record is applied; `ErrEventRejected` and a panic dead-lettered after one attempt without quoting the panic value; an invalid record dead-lettered without calling the handler, with the commit waiting until two failed dead letter writes succeed; a shutdown that abandons a stuck handler after the grace without committing it or anything after it; a record that finishes within the grace and is committed while the next one is not started; no retry and no dead letter during shutdown; backoff after failed polls; commits that PostgreSQL refuses after the handler swallowed an error, counted as attempts and ending in `retries_exhausted`; a serialization conflict at commit retried as an attempt; a panic in `Handles` dead-lettered without quoting its value; the prefix commit right after a dead letter, before the next record starts; `poll` and `commit` failure counts; and the reason sanitizer. The PostgreSQL adapter tests classify refused, conflicting, and transport commit failures and check that handler errors keep their identity without the PostgreSQL message. They also cover envelope decoding and its round trip with the producer, every rejected envelope rule without quoting the value, and commit bookkeeping of the group member, including the refusal of finished records that are not a gap-free prefix of the last poll per partition (`internal/adapter/secondary/kafka/`), the consumer settings and the rebalance budget, including the documented 42.5-second default (`config/`), the consumer counters (`internal/adapter/secondary/prometheus/`), and in `internal/bootstrap/` the skip cases, one consumer per handler, rejected duplicate and invalid names, the registered delivery handler, label values that match the prepared metrics, and an application that runs a consumer while serving and returns only after it stopped polling.
|
||||
|
||||
`TestEventConsumer` in `backend/integration_test/event_consumer_test.go` uses `bootstrap(t, postgresService, kafkaService)`. Its handler exists only in the test: it writes one row per applied event into `consumer_test.effects`, a table without a unique key that the test creates, so a second effect would stay visible. The sequential cases, each with its own topic and group, are:
|
||||
|
||||
- One event ID delivered three times, twice on partition 0 and once on partition 1, next to another event: the group commits both partitions, each event has exactly one effect row and one marker, and the counters show 2 `applied` and 2 `duplicate`.
|
||||
- Two consumers race on one event without Kafka: each reads the same record from an in-memory source. The first holds its uncommitted marker inside the handler until the test sees, in `pg_stat_activity`, the second consumer's marker insert waiting for a lock; then the first commits. The result is one effect, `applied` for the first and `duplicate` for the second, without the second calling its handler.
|
||||
- The same race where the first handler fails after the second started waiting: the first rolls back, the second applies the event, and the first's retry finds the marker. One effect row.
|
||||
- Restart before commit: a handler writes its effect and then blocks past a 300 ms shutdown grace, as a process killed before the commit. After the stop there is no effect row, no marker, and no committed offset for the group. A new consumer in the same group receives the record, applies it once, and commits offset 1.
|
||||
- Crash after the database commit but before the offset commit: the effect and marker are committed directly, then the record is consumed. It is a `duplicate`, the handler is not called, and the offset is committed.
|
||||
- Invalid record followed by a valid one on one partition: one dead letter row with offset 0, the header event ID, class `invalid_record`, zero attempts, the value size and SHA-256, and a reason that does not quote the value; the valid event is applied; offset 2 is committed; the `dead_lettered` counter is 1; and no further dead letter appears within 500 ms.
|
||||
- A handler that always fails for one event, with 3 attempts and a 200 ms backoff: exactly 3 attempts at least 100 ms apart and within 5 seconds, a `retries_exhausted` dead letter with the event ID, type, and handler error, no effect row of that event because every attempt rolled back, the next event applied, offset 2 committed, a handler failure count of 3, and no further attempt within 500 ms.
|
||||
- Hard crash before commit: the handler writes its effect, reads its own backend PID, and ends that backend with `pg_terminate_backend`, as a crashed process or a dropped connection would. The backend disappears from `pg_stat_activity`, no effect row, marker, or committed offset remains, and a new member of the group applies the event once.
|
||||
- A handler that runs `SELECT 1 / 0`, ignores the error, and returns nil: PostgreSQL refuses each commit, the consumer counts 3 handler attempts and no store failure, writes a `retries_exhausted` dead letter, commits offset 1, and leaves no effect or marker.
|
||||
- Dead letter upsert: the same record written twice keeps one row with the second outcome; another value at the same position gets its own row.
|
||||
- Rebalance handover with two members of one group: the first member's commits always fail, and it holds a record while a second member joins; the test waits until the group is in `PreparingRebalance`, releases the record, and waits until the group is stable with one partition per member. Each of four events has exactly one effect, the first member handled both first-round events before the rebalance, the joiner received nothing of the moved partition's first round (its position was committed in the revocation, the only commit path left) and counted no duplicate, the first member never tried to commit or handle a record of the moved partition after losing it, and after the first member leaves, the group's offsets are 2 on both partitions, so the moved partition was not rewound.
|
||||
- An event appended to the outbox through the transactor, published by the relay, and consumed: the decoded event matches the outbox row, so the producer and consumer agree on the envelope.
|
||||
|
||||
`TestPostgresMigrations` also checks that migration 00005 creates and drops both consumer tables. The suite uses one broker, one PostgreSQL, and test-only handlers. It does not measure throughput, does not cover a rebalance under load or with more than two members, broker failover, a member removed after the rebalance timeout, and does not check alert delivery; the product handler has its own [Mail delivery tests](#mail-delivery-tests).
|
||||
|
||||
## Mail delivery tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the delivery model and its creation path:
|
||||
|
||||
- `internal/domain/`: the content hash covers the version, subject, both parts, and part borders; content that no transport could send or that belongs to another kind is refused; a changed stored body fails the integrity check; a new delivery starts `pending`, due at creation, with version 1, the key `delivery/<id>`, and an optional source event; every attempt outcome applied to `pending`, `waiting_quota`, and `unknown` gives the documented status, attempt number, version, times, and provider ID, including `waiting_quota` without a known reset, and `accepted` and `rejected` refuse every further attempt; inconsistent attempt results are refused; `WaitForQuota` parks `pending` and `waiting_quota` with a known or unknown reset without an attempt, refuses `unknown` and terminal deliveries and times before the last change, and a later attempt must not precede it; `Rebind` changes only the provider account and version before the first attempt and is refused after it; stored rows that break an invariant are refused; a mail request accepts only the notification kind and storable text; and `fmt` and `slog` output of a delivery, its content, and a mail request never shows the address, subject, body, request text, or token.
|
||||
- `internal/usecase/notification/`: a request stores its text under the event's aggregate ID and the event payload carries only `mail_request_id` and `kind`; invalid requests write nothing; the handler stores one delivery under the request ID with the source event, the account address, the rendered content, the configured provider account, and the clock time, and deletes the request; the same event again finds no request; an existing delivery under the request ID is accepted for the same recipient and kind and rejected otherwise; broken events (another schema version or aggregate, a malformed payload, trailing data, a request ID that is not the aggregate ID, a token mail kind) and text the template refuses are rejected without quoting the payload; a request that is gone, an account that is gone, and an unverified address are skipped with a log line that names only the delivery and event IDs; storage failures, including an account deleted between its read and the insert, stay retryable and keep the request; and no error or log line holds the address, subject, or body.
|
||||
- `internal/adapter/secondary/postgres/`: delivery and mail request constraint errors map to their sentinels (`deliveries_content_immutable` and `delivery_attempts_immutable` to `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` to `ErrDeliveryProviderPinned`, the user foreign keys to `ErrUserNotFound`), and any other PostgreSQL error, such as a check violation, keeps only its SQLSTATE and constraint without the message or detail.
|
||||
- `internal/usecase/notification/mailtemplate/`: a rendering converts to the stored content with the same kind, version, parts, and hash.
|
||||
- `config/` and `internal/bootstrap/`: `EMAIL_ACCOUNT` defaults to `default`, accepts labels up to 64 characters, and refuses empty, mixed-case, key-like, and oversized values without echoing them; bootstrap registers exactly the `notification_delivery` and `notification_inbox` handlers and refuses an invalid account label.
|
||||
|
||||
`TestMailDelivery` in `backend/integration_test/delivery_test.go` uses `bootstrap(t, postgresService, kafkaService)` and the real request usecase, handler, relay, consumer runtime, and stores. Its sequential cases are:
|
||||
|
||||
- One event processed twice through the consumer: a request for a verified account is recorded in a business transaction, the relay publishes its event, the row is marked unpublished again as after a crash before the `published_at` commit, and the relay publishes it a second time with the same event ID. The consumer commits offset 2 and counts one `applied` and one `duplicate` record; the database holds exactly one delivery, addressed to the account, rendered with `notification.v1`, pinned to the configured provider account, naming the event as its source, and `pending` with no attempt, and no mail request remains.
|
||||
- A template change after creation: a first request is stored with `notification.v2`. A handler with a test renderer that stands for the later version `notification.v3` stores a second request with the new version, and a replay of the first request under another consumer name finds its request consumed and stores nothing. The first delivery, read through a new pool, still has the `notification.v2` subject, parts, and hash, and a direct `UPDATE` of its body fails with `deliveries_content_immutable`.
|
||||
- Restart persistence: one pool records an `unknown` attempt with a provider code and a wait hint with sub-millisecond parts, loses a second write of the same attempt with `ErrDeliveryVersionConflict`, records an `accepted` attempt with a provider message ID, and closes. A new pool and store read the delivery as `accepted` with that ID, two attempts, and version 3, and both attempt rows exactly as written, the wait hint to the nanosecond; a further attempt is refused, and an `UPDATE` of an attempt fails with `delivery_attempts_immutable`.
|
||||
- Rebind and quota wait: a delivery without attempts is moved to another provider account and parked in `waiting_quota` with an unknown reset, a stale second write fails with a version conflict, and no attempt row exists; after an attempt, `Rebind` is refused by the domain and a direct `UPDATE` of the provider account fails with `deliveries_provider_pinned`.
|
||||
- A notification to an unverified address stores no delivery, deletes its request, and logs the delivery ID.
|
||||
- A request whose account is deleted loses its request row with the account; the handler then stores no delivery and logs the delivery ID.
|
||||
- The unverified account cleanup skips an account whose delivery row another transaction holds, deletes it once the lock is gone, and its pending request and its delivery, created directly through the repository as token mail will be, go with it.
|
||||
|
||||
Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. `TestMailDelivery` does not send mail; it covers the product notification consumer. `TestEmailVerificationOverHTTP` exercises verification mail and confirmation through the Resend fixture but does not call an external provider. The password reset flow has no delivery test because it is not implemented.
|
||||
|
||||
## Mail quota tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the quota rules without a database:
|
||||
|
||||
- `internal/domain/`: the day and month windows of an instant are UTC calendar periods whatever its location: midnight UTC belongs to the new day and one nanosecond before it to the old one, a local time after local midnight can still be the previous UTC day, the day reset of February 28 in a common year and of February 29 in a leap year is March 1, and December resets into January of the next year; limits refuse zero, negative, and a daily limit above the monthly one.
|
||||
- `config/` and `internal/bootstrap/`: `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` default to 100 and 3000 for `resend` and `disabled`; `smtp` refuses to start without either and takes stated values; a lowered value is taken as configured for every provider; an empty value counts as unset; zero, negative, non-integer, out-of-range values and a daily limit above the monthly one are refused without echoing secrets; bootstrap refuses to start with a quota of zero.
|
||||
- `internal/adapter/secondary/mail/resend/`: 429 `daily_quota_exceeded` gives `QuotaPeriod` `day` with the wait until midnight, and `monthly_quota_exceeded` gives `month` without a wait.
|
||||
- `internal/usecase/notification/`, with an in-memory counter and journal and a fake clock:
|
||||
- `QuotaGate.PrepareSend` admits sends up to the daily limit and parks the next one in `waiting_quota` until 00:00 UTC without counting it, then admits it after midnight. It waits for the month start when the month is full (December 31 to January 1) and also when both windows are full.
|
||||
- It parks a delivery last changed by an instance whose clock is 5 ms ahead, past midnight, at that change time without an error.
|
||||
- It applies a lowered limit to `smtp` like any other transport, and refuses a delivery pinned to an account without a quota, reserving nothing for it.
|
||||
- It returns an `unknown` delivery unchanged with the reset time and refuses a terminal one.
|
||||
- A retry within 24 hours reuses the open reservation even with the day otherwise full; a rejection of that retry keeps it; after the window the retry counts again. An `smtp` gate, without provider deduplication, counts every retry.
|
||||
- `SettleSend` keeps the reservation for `accepted` and `unknown`, and releases it for a `Send` error and every `rejected` outcome. A repeated settlement releases once.
|
||||
- A daily quota answer marks the day and returns midnight, a monthly one marks the month and returns its end, an answer without a window parks only the delivery for its hint or without a time, and a window the provider reported full is not reopened by a release.
|
||||
- The window marked is the one current at settlement: a daily refusal on October 31 marks only the day and leaves November open, a reservation at 23:59:59 settled 5 ms after midnight marks the new day, and a hint computed by a provider clock 5 ms ahead still gives exactly midnight.
|
||||
- `ReportQuotaUsage` logs the usage and limits and warns with the other account labels.
|
||||
- `DeliveryStatusReader.LatestForUser` returns the kind, status, and change time, and `WaitingUntil` only for `waiting_quota`. It asks only for the given account, returns nothing without a delivery, and refuses a nil account and an unknown kind.
|
||||
- Logs hold no address, subject, or body.
|
||||
|
||||
`TestMailQuota` in `backend/integration_test/mail_quota_test.go` uses `bootstrap(t, postgresService)`, the real transactor, delivery store, and quota repository, and a fake clock. Each case starts from empty tables:
|
||||
|
||||
- Concurrency: 12 senders, each with its own connection and transaction, call `PrepareSend` at once. On windows without rows (the row creation races too) and a daily limit of 10 exactly 10 get a permit; after 7 sequential sends exactly 3 of the next 12 get one. Every other delivery is stored as `waiting_quota` with `next_attempt_at` at the next 00:00 UTC, and both counters end at 10. Without the row lock the case fails with all 12 admitted.
|
||||
- Midnight and month boundary: with limits of 2 per day and 3 per month starting October 30 at 22:00 UTC, the third send waits until October 31 00:00 UTC, still waits one second before it, and goes at midnight; the fourth waits for November 1 because the month is full, and goes then. The day and month rows hold 2, 1, 1 and 3, 1.
|
||||
- Lowered limit and SMTP: gates are built from `config.LoadFromEnv`. After 4 Resend sends with the default limit, a limit lowered to 3 parks the next send until midnight. `smtp` without quota settings fails to load; with 2 and 2 it admits two relay sends and parks the third until the month start, and a Resend delivery under the `smtp` gate fails with `ErrQuotaNotConfigured` and changes no counter.
|
||||
- Provider refinement: a `temporary` rejection gives its reservation back. A `daily_quota_exceeded` refusal while the local count is 1 of 100 stores the delivery as `waiting_quota` until midnight with one attempt, raises the day row to 100 with `provider_exhausted_at`, and the gate then parks the next delivery itself. After midnight a `monthly_quota_exceeded` refusal raises the month row to 3000 and parks the deliveries until November 1.
|
||||
- Account deletion: three accepted sends count 3 of 3; deleting the account deletes its deliveries and attempts by cascade, the counters keep 3, and a delivery for another account the same day waits until midnight.
|
||||
- Lock order, deterministic: the month row lies before the day row in the heap, and the writers run on sessions with `enable_indexscan=off`, so scans follow heap order as in the reproduced deadlock. A third transaction holds the day row; a reservation and a release queue on it in both orders, and the blocker is released. Neither gets a deadlock error, and the usage ends consistent. With the ordered lock removed from `Settle`, the case fails with SQLSTATE 40P01.
|
||||
- Lock order, bounded stress: 60 rounds, each starting at once a release of day two, a release of day one that marks day two across midnight, and two reservations of day two, on heap-order sessions. No round returns an error.
|
||||
- Journal: a transport error settled twice releases once. An unknown attempt's reservation is reused by a retry an hour later and not after the 24-hour window. The journal ends with 2 open rows, 1 released, and 2 with an outcome.
|
||||
- User status: an account without mail gets nothing; after one admitted and one parked notification it sees `waiting_quota` until midnight; another account and another kind get nothing.
|
||||
- Startup report: with usage under the label `old-label` and under the configured label, the report through `postgres.MailQuotaStore` logs the configured account's usage and warns with `old-label`.
|
||||
- The database refuses an unknown period kind, a month that does not start on day one, negative usage, a malformed account label, a reservation whose day is outside its month, and an unknown outcome.
|
||||
|
||||
`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The quota suite does not call a transport; the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is covered by the service mail sending tests below.
|
||||
|
||||
## Service mail sending tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover:
|
||||
|
||||
- `domain`: `Delivery.CheckServiceMail` names the first failed rule (missing token, purpose, owner, consumed, revoked, expired exactly at its deadline, registration moved, verified address, changed address) and leaves a current verification or reset mail sendable; `Delivery.Cancel` works from `pending` and `waiting_quota`, refuses `unknown` and the terminal statuses, leaves no attempt, and survives a restore; a notification cannot carry a token ID; the status names contain no claim of delivery to a person.
|
||||
- `usecase/notification`: `ServiceMailSender` against in-memory stores with the version rule and the lease of the PostgreSQL store, the in-memory quota of the gate, and a scripted transport. Every transport result becomes the right delivery state, due time, and quota effect (accepted, permanent and invalid-request refusal, temporary refusal after the first backoff, a provider wait hint longer than the backoff, the provider's daily quota answer until midnight UTC, a quota answer without a reset, unknown, a transport that answers without an outcome, no transport, an interrupted call, an invalid message); every cancel reason is reached without a transport call or a reservation; a full local quota parks the delivery without a call and sends it at the reset; a result that cannot be stored keeps the lease, is repeated three times, and is then covered by a replacement under the same key without counting twice; an attempt lost beyond the idempotency window, or with a transport without deduplication, is recorded as unknown and not repeated; a delivery whose content hash does not match is cancelled as `content_invalid` and reported without calling the transport; a row that fails by its own fault (unreadable for a reason other than a hash mismatch, a domain rule broken while reading its state) is counted, moved back by the retry schedule so the delivery behind it is sent, and cancelled as `processing_failed` after three failures; transient errors (deadline, cancellation, deadlock, network, EOF, missing quota configuration) are reported to the worker and never counted or cancelled however often they repeat; a `Send` error without an answer moves the row back without counting it; paused counting moves rows back without counting; a successful pass clears the count; a failure is not recorded for a row another worker holds; the idempotency window is counted from the first request across repeated lost workers and with the one-hour margin; a revocation between the claim and the call is honored; a result is dropped when the lease was lost during the call; the call is bounded by the lease minus the settle budget; jitter is bounded and injectable; mail stored while no transport ran is rebound to the configured account and a delivery of another account is left alone; logs never hold the address, the token, or the link. `ServiceMailer` stores a token-bound delivery under the token ID with the token in the fragment of the link and no `?token=`, repeats harmlessly, and refuses a token of the wrong purpose before rendering. `RetryPolicy` doubles to its maximum and honors a longer hint.
|
||||
- `worker/mailsender`: cancelled deliveries are counted by reason; the breaker pauses failure counting after three different rows fail in a row and resumes after a success, and one row failing again does not trip it; a failing row makes the loop wait by the backoff; the gauge is true only while the loop runs, an idle pass waits for the poll interval, a handled delivery is followed at once by the next pass, and a missing transport, an interrupted call, or a database failure back off instead of spinning.
|
||||
- `adapter/secondary/postgres`: only SQLSTATE classes 22 and 23 match `ErrRowFault`; deadlock, serialization, connection, resource, shutdown, and internal errors do not.
|
||||
- `adapter/secondary/prometheus`: `lincodex_mail_sender_cancelled_total` has every reason at zero and refuses an arbitrary label; `lincodex_mail_sender_running` exists at 0 and follows `SetMailSenderRunning`; every delivery status including `cancelled` exists at zero.
|
||||
- `adapter/secondary/mail/resend`: the loopback constructor accepts only an http URL on a loopback host, so the key and the messages of a deployment cannot be pointed at another host through it; `resendfixture` answers like Resend (accepts, replays a repeated key and body with the original message, refuses another body under the key, plays scripted errors).
|
||||
- `bootstrap`: no worker without a transport or a database; the loop starts and stops with the application and the gauge follows.
|
||||
- `observability/prometheus/tests`: `LincodexMailDeliveriesOverdue` stays silent without the gauge, while it is 0, and for a notification-only backlog (age 0), and fires while some instance reports 1; `LincodexMailCancelledBroken` fires on `content_invalid` and `processing_failed` and stays silent on user-caused reasons (`make -C observability check`).
|
||||
|
||||
`TestServiceMailSending` in `backend/integration_test/mail_sender_test.go` uses `bootstrap(t, postgresService)`, the real transactor, stores, quota gate, and sending usecase, the real Resend transport pointed at the local fixture, and a fake clock. Subtests share the database and start from empty tables:
|
||||
|
||||
- A service email for a synthetic account with no consent record of any purpose is enqueued with its token in one transaction and accepted by the fixture: one provider call with the key `delivery/<id>`, the address, and the link with the token in the fragment; the delivery is `accepted` with the provider message ID, one accepted attempt, one counted recipient, no lease left, the account's status is `accepted`, and a second pass does nothing. Logs hold neither the address nor the token.
|
||||
- A password reset email for a synthetic account without C2 is accepted by the fixture: one call with the key `delivery/<id>`, the address, and the `/reset-password` link with the token in the fragment; the log holds no address and no token.
|
||||
- A verification email goes out even if C2 is granted and revoked while the email waits for the worker: the check reads only the token and the account, and the fixture gets exactly one call.
|
||||
- A worker that holds a delivery keeps another off it: the fixture answers slowly, the second worker's pass is idle while the first one's request is in flight, and the fixture gets exactly one call and the database one attempt.
|
||||
- Four workers drain a queue of eight deliveries at once: eight provider calls under eight distinct keys, none replayed, eight accepted deliveries with one attempt each, eight counted recipients.
|
||||
- A worker that stopped after sending (the database fails when it stores the answer) is replaced after its lease expires: two calls under the same key, the second a replay, one message at the provider, one attempt, and the open reservation reused, so the recipient counts once. Beyond the 24-hour window the replacement records an unknown attempt and does not call the provider.
|
||||
- A delivery whose content hash was broken by a manual edit is cancelled as `content_invalid` at version 2 without a provider call, and the delivery behind it is sent in the next pass.
|
||||
- A row that fails for a reason of its own (a subject that breaks the domain rules, so the row cannot be restored although its hash is intact) is counted and moved back by a minute while the delivery behind it is sent, fails again at each due time, and is cancelled as `processing_failed` on the third failure with its bodies cleared; a transport error without an answer moves the row back by a minute without counting it, with the reservation given back and the delivery pending.
|
||||
- A failure recorded by a worker whose claim rolled back leaves a row alone that another worker holds, and an uncounted failure leaves `failure_count` at 0.
|
||||
- Three workers lost in turn do not hide the age of the first request: the delivery becomes `unknown` once `first_send_started_at` is 24 hours old, and the provider is not called a fourth time.
|
||||
- The lease is a few seconds by the database clock; a stranger cannot record an attempt or lock the row; `RecordClaimedAttempt` succeeds for the holder.
|
||||
- Over 5000 due notification rows the claim plan uses `deliveries_due_idx` and no sequential scan (`EXPLAIN`).
|
||||
- A notification-only backlog does not make the earliest pending age appear; a service mail does.
|
||||
- A token mail's bodies are cleared when it is accepted or cancelled and the token no longer appears in any row; a waiting mail cannot be cleared by hand; a cleared row cannot get a body back or lose its mark; the account still sees its status.
|
||||
- A token revoked by a resend, a token already used, an expired token, an account registered again, an address already verified, a changed address, and a token of another purpose each end the delivery as `cancelled` with the matching reason, no attempt, no lease, no next attempt, no reservation, and no provider call; the account sees `cancelled`; a further pass is idle. A deleted account takes its delivery with it.
|
||||
- A verification email revoked before its send is cancelled as `token_revoked` with no provider call and no attempt; the delivery keeps its provider account, its body is cleared, and the log holds no address, token, link, or account ID.
|
||||
- Provider answers: a 503 `service_unavailable` leaves the delivery `pending` due one minute later, a pass before that is idle, the retry at the due time repeats the key and is accepted; a 500 is `unknown` with no next attempt and no retry a day later; a 403 `validation_error` is `rejected`.
|
||||
- Quota: a local limit of one per day parks the second delivery in `waiting_quota` until midnight UTC without a provider call, the account sees the wait and its end, and the delivery is sent at the reset; the provider's `daily_quota_exceeded` answer parks the delivery until the next midnight.
|
||||
- A product notification is never claimed by the service worker; the notification lane sends it instead (`TestProductNoticeIsSentOnceByItsOwnWorker`).
|
||||
- `EMAIL_PROVIDER=disabled`: with the disabled transport the pass reports the channel unavailable, the delivery stays untouched at version 1, the lease and the reservation are released, nothing reaches the fixture, a loop run against it makes at most four passes in under a second, and the gauge is 1 while it runs and 0 after; with a transport the same mail is rebound to the configured account and accepted.
|
||||
- The schema refuses a cancelled delivery without a reason, a reason on another status, a half lease, a lease on a terminal delivery, a notification bound to a token, a change of the token binding, and the deletion of a token that a delivery references; deleting the account removes both.
|
||||
|
||||
`TestDeliverySendingMigration` rolls back and applies migration 00012 over a cancelled and redacted reset delivery: the earlier schema keeps it as `rejected` with a placeholder body, drops reset tokens and the new columns, and the migration applies again. `TestPostgresMigrations` covers the generic up, down, and up path.
|
||||
|
||||
`make -C backend lint` also forbids importing `resendfixture` and calling `resend.NewLoopbackSender` outside `_test.go` files (depguard and forbidigo in `backend/.golangci.yml`).
|
||||
|
||||
No check calls the real Resend API: the fixture is the only provider, so these tests prove the protocol the transport speaks and the delivery rules, not Resend's behavior, deliverability, or the account's real quota.
|
||||
|
||||
## Product notification tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover:
|
||||
|
||||
- `domain`: `Delivery.CheckInvitationNotice` decides in its documented order (a missing or unverified recipient, a changed address, a missing or foreign invitation, an invitation that was answered, expired, or past its deadline, a hidden organization, a withdrawn publication, and a notice without a subject), and the first failed rule decides, so an unverified address outranks a hidden organization; `MailSubject` accepts only known kinds with complete IDs and prints no identifier; only a notification names a subject; `MailQuotaLimits.WithReserve` keeps each window's share and refuses a reserve that leaves no room; the three rights reasons parse and exist at zero in the metrics set.
|
||||
- `config`: the service reserve defaults to a fifth of each quota limit (20 and 600 on the Resend Free plan), a stated zero is kept, and a reserve that is negative or reaches its limit is refused with a message that names the setting.
|
||||
- `adapter/secondary/prometheus`: `lincodex_notification_sender_running` exists at 0 and follows `SetNotificationSenderRunning` without moving the service gauge; the rights reasons exist at zero in `lincodex_mail_sender_cancelled_total`.
|
||||
- `bootstrap`: no notification worker without a transport or a database, and the notification loop starts and stops with the application while its gauge follows.
|
||||
- `observability/prometheus/tests`: `LincodexMailCancelledBroken` stays silent on `rights_revoked`, `recipient_ineligible`, and `source_closed` (`make -C observability check`).
|
||||
|
||||
`TestProductNotice*` in `backend/integration_test/product_notification_test.go` use `bootstrap(t, postgresService)`, an isolated database with the real invitation send and the real notifier, the consumer `DeliveryHandler` run on the stored request, the real notification sender with the Resend fixture as its transport, and a fake clock. Each top-level test uses its own isolated database, so quota counts never mix between them; the subtests of the rights test share one database:
|
||||
|
||||
- `TestProductNoticeIsSentOnceByItsOwnWorker`: the notice of a delivered invitation is sent once by the notification lane, with the neutral body, which names neither the organization nor the candidate and links to the inbox; the service worker takes nothing (idle, no provider call); a second pass is idle; the logs hold neither the address, the candidate ID, nor the card handle.
|
||||
- `TestProductNoticeRightsAreCheckedBeforeEverySend`: a candidate who hides the organization between the send and the worker gets no mail, and the notice is cancelled as `rights_revoked` with no provider call, its bodies cleared, a further pass idle, and no address in the logs; an address that is no longer verified is cancelled as `recipient_ineligible`; a notice that names no subject is cancelled as `source_closed` with its body cleared; an invitation past its response deadline is cancelled as `rights_revoked`. The deadline subtest moves the clock, so it runs last.
|
||||
- `TestProductNoticeReserveLeavesServiceQuotaToServiceMail`: with a daily limit of 10 and a reserve of 8, the notification lane sends two notices and parks the third in `waiting_quota` until the next UTC midnight, without a provider call and without a spin; a verification mail then goes out under the full limit, and the day counts three recipients.
|
||||
- `TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers`: four senders drain six notices at once; the provider sees six calls, and each notice is accepted after one attempt.
|
||||
- `TestProductNoticeClaimReadsItsOwnDueIndex`: over 5000 service-mail rows the product claim plan uses `deliveries_product_due_idx` and no sequential scan (`EXPLAIN`).
|
||||
|
||||
These tests prove the rights rules and the lane mechanics against the local fixture. They do not decide the product questions listed under [Sending product notifications](ARCHITECTURE.md#sending-product-notifications), such as whether a withdrawn publication should cancel a pending notice.
|
||||
|
||||
`TestInvitationNoticesSurviveRelayAndConsumerRestarts` in `backend/integration_test/notification_restart_test.go` uses `bootstrap(t, postgresService, kafkaService)` with the same fixture and follows two real invitation sends through the outbox, the relay, a one-partition Kafka topic, and the `notification_inbox` and `notification_delivery` consumers built as bootstrap builds them. The relay produces all four events and is killed before its mark commits; the consumers apply them. A restarted relay then publishes the same event IDs again, and restarted consumers in the same groups count each repeated record as a duplicate; consumers in new groups, as after lost offsets, replay the whole topic as duplicates too. After each stage every recipient has exactly one row in `notification_inbox_events` and one notification delivery, and no dead letter exists; the notification lane then sends one message to each recipient.
|
||||
|
||||
## Scheduled job tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the job runtime with an in-memory store that applies the claim, lease guard, and release rules of the PostgreSQL store and a fake clock from `backend/pkg/testutil/` (`internal/worker/jobrunner/`): only due jobs of registered kinds run, in due order, and a job due in two days runs exactly when the clock reaches it; a failing job is retried after the backoff by the clock, is not claimed again before it, and is dead after the last attempt with an error log and metrics; `ErrJobRejected` and a panic end a job after one attempt without logging the panic value; a handler that outlives its lease fails as `timeout`; a job reclaimed by another worker before it starts is skipped without calling the handler; a job whose last started lease expired becomes dead without running; a slow first job of a batch neither spends the next job's single attempt nor lets it die, and another worker runs a job that a busy worker claimed but did not start, on the same attempt; a database failure outside the handler releases the job and the rest of the batch without counting attempts; failed claims back off instead of looping; at shutdown the job in progress finishes within the grace, a job that outlasts it is canceled and released without an effect or a counted attempt, and claimed jobs that did not start are released; a panic during shutdown still makes the job dead; and the backlog of all kinds is reported. Further unit tests cover the job rules (`internal/domain/`: kind, key, flat payload, size limit, UTC microsecond due time), the settings (`config/`), the counters and gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), and in `internal/bootstrap/` the skip cases with their log lines, the empty kind registry, a duplicate kind, and an application that runs the worker against an unreachable database and still stops.
|
||||
|
||||
`TestScheduledJobs` in `backend/integration_test/scheduled_jobs_test.go` uses `bootstrap(t, postgresService)`. Its handler exists only in the test: it writes one row into `job_test.effects`, a table without a unique key, in the transaction that completes the job, so a second effect would stay visible. Each simulated process gets its own pool, store, and worker; building a new one is a restart. All due and lease decisions use one `FakeClock`. The sequential cases are:
|
||||
|
||||
- Jobs on different dates: two jobs scheduled through `UnitOfWork.ScheduledJobs()` for tomorrow and in three days, and a repeated schedule that is ignored and does not move the due time. Nothing runs at the start; after a restart and one day the first job runs; after another restart the second job does not run a microsecond early and runs at its due time; a month later nothing runs again. The effects are one per job, in due order.
|
||||
- Two workers with their own pools run their loops against 40 due jobs at once: every job is done, and there are exactly 40 effects for 40 distinct jobs.
|
||||
- A handler that outlives its lease by the clock still holds the job row lock, so another worker's claim skips the job; the first worker then completes it, with one effect.
|
||||
- An expired lease: worker A claims and starts the job and stops inside it. Worker B cannot claim it a microsecond before the lease expires and runs it at expiry, with two counted attempts and `lease_expired` recorded. A's late start is refused, its late `Run` returns `ErrJobLeaseLost` without calling its handler, and its late failure record and release are refused; one effect remains.
|
||||
- A started attempt with a limit of one attempt whose lease expired: the next claim makes the job dead with one attempt and `lease_expired`, without calling the handler.
|
||||
- A claim that never started, with a limit of one attempt: after its lease expires another worker runs the job on the same attempt, with no error class.
|
||||
- A slow first job of a batch runs past the claim lease: the next job, limited to one attempt, is released with its attempt intact and runs in the next pass. With two workers, while the slow job holds its row, the other worker claims only the waiting job and runs it on its single attempt; the busy worker then counts it as `lease_lost`.
|
||||
- A handler that cancels its own job through the unit: its effect commits, the job stays `cancelled`, and the next job of the pass runs. A handler that changes its own job otherwise makes it dead with `completion_conflict` and leaves no effect.
|
||||
- Graceful shutdown: a handler writes its effect and then outlasts a 200 ms grace. After the stop the effect is rolled back and the job is `pending` with no attempt and no lease, and a new process runs it at once without waiting for a lease.
|
||||
- A failing job with its own limit of two attempts: the first attempt moves only `available_at` by the backoff and keeps `due_at`, the job is not claimed before the backoff, the second attempt makes it dead, the handler saw the original due time both times, no effect remains, the backlog reports one dead job, and the counters show one `retry` and one `dead`.
|
||||
- Cancel: a canceled job is never claimed, a second cancel and a new schedule of the same key do nothing, and nothing is due.
|
||||
- Cancel during a run: while a handler holds the job, a cancel in another transaction is observed waiting for the row lock in `pg_stat_activity`; after the handler commits, the job is done and the cancel reports false.
|
||||
|
||||
`TestPostgresMigrations` also checks that migration 00008 creates and drops `scheduled_jobs`. The suite uses one PostgreSQL and a test-only kind. It does not measure throughput, does not cover clock skew between instances, a database failover, or a product handler, and does not check alert delivery.
|
||||
|
||||
## Product metrics tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the product metrics. In `internal/adapter/primary/http/`, requests through the real router and the real collector are labeled with the route template of their operation (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) and never with a path parameter, an address in the path, or a query string; unknown paths and methods keep `/api/v1/*`, `/api/*`, or `unmatched`; problem responses are counted by code (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), a plain 404 outside `/api` is not; and the exposition holds no email-like or UUID-like value; every contract problem code keeps its own label. The request log test sends an address and a UUID in paths and queries through the same router and checks that the JSON log names only route templates, statuses, problem codes, and query parameter counts, skips `/healthz` and `/readyz`, and holds neither value. `internal/adapter/primary/http/middleware/` tests the log and metrics middleware on a plain chi router: the shared route and problem code, no problem for a response that finally succeeded, the error level for 5xx, an unknown method logged as `OTHER`, and a collector without problem counting. In `internal/adapter/secondary/prometheus/`: latency by status class, every delivery kind and status pair exposed at zero and reset when a status empties, quota gauges without an account label, the answer save hook mapping unknown values to `other` and exposing no series before its first call, and a scan of the whole exposition after every hook was called with email and UUID fixtures. `internal/worker/deliverymetrics/` covers the due age of the earliest pending delivery (zero when it is not due yet), the current quota windows, a failed read that does not skip the other, and the loop lifecycle; `internal/bootstrap/` covers the skip without a database, the quota only for an active transport, and an application that runs the sampler against an unreachable database and still stops. `pkg/testutil/` tests the identifier scan itself.
|
||||
|
||||
`TestDeliveryStatistics` in `backend/integration_test/delivery_statistics_test.go` checks the sqlc query `GetDeliveryStatistics` on PostgreSQL: an empty table, then deliveries of three kinds in all five statuses, set within the table constraints, give exact counts per kind and status, and the earliest due time comes only from deliveries that are still pending.
|
||||
|
||||
`make -C observability check` validates the alert rules with `promtool check config` and runs `promtool test rules` on `observability/prometheus/tests/lincodex_rules_test.yml`: every alert fires in a positive case (backend down, 5xx share, outbox lag, dead letter, stalled consumer, dead and lagging jobs, unknown delivery outcome counted once across two instances, overdue deliveries, stale mail gauges, the used-up quota by count and by provider refusal), and the guards stay silent: quiet traffic with only failing requests, overdue deliveries without `lincodex_mail_sender_running`, a sampler that keeps succeeding, and a month window with room.
|
||||
|
||||
`make -C observability verify-product-metrics` is the end-to-end check described in [DEPLOY.md](DEPLOY.md#separate-monitoring-compose-project). It needs Docker and free host ports 18085 and 13085, builds the core images, and takes several minutes. It sends the fixture address in a query through Nginx and in a path straight to the backend and provokes a unique violation on it in PostgreSQL. It proves that the metrics reach Prometheus and the product dashboard queries run in Grafana, that PostgreSQL logs errors tersely, and that the fixture address is absent from the metric exposition, every series and label value, the federated samples, and the Loki logs of the core services in that run. It does not test alert delivery, production retention, load, or latency targets, and it does not send mail.
|
||||
|
||||
## Integration test sharding
|
||||
|
||||
`make -C backend test-int` runs the full suite through `backend/scripts/run-integration-suite.py`. The runner discovers every top-level `Test*` in `./integration_test/...`, sorts by package and name, and distributes tests round-robin. Each test belongs to exactly one shard with all its subtests. Changing the test set may change the assignment; duration-based balancing is not implemented.
|
||||
|
||||
```sh
|
||||
make -C backend test-int-list
|
||||
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
make -C frontend install
|
||||
make -C deploy test-e2e
|
||||
make -C deploy test-e2e-registration
|
||||
```
|
||||
|
||||
Indexes start at 1. Set both variables together; invalid settings, an empty suite, excess shards, and discovery failures fail the command. `test-int-list` compiles test packages and lists selected tests without starting containers. `make -C backend test-scripts` verifies for every shard count that each test runs in exactly one shard, that a shard listing matches the tests the shard runs, parent-test selection, and runner failure propagation. It is included in `make -C backend check`.
|
||||
Both commands create a throwaway Compose project with its own secrets and volumes. The browser reaches the application through Nginx. The script removes test containers and volumes on exit; results remain in `frontend/test-results/e2e/`.
|
||||
|
||||
CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database or a broker, so a Kafka test passes in whichever shard it lands. CI takes `TEST_SHARD_TOTAL` from the matrix size (`strategy.job-total`), so adding a shard index to the matrix is enough when suite duration warrants more runners; an index above the total fails the job. The `go test` timeout shares a 30-minute budget of the whole suite between shards with a floor of 10 minutes: an unsharded local run gets 30 minutes, each of the two CI shards gets 15.
|
||||
Ordinary `test-e2e` disables mail. It runs technical and available UI scenarios while skipping tests that require mail and special fixtures. `test-e2e-registration` enables a local Resend-compatible receiver and synthetic data for registration and business flows. It does not send mail through real Resend.
|
||||
|
||||
## Consent ledger tests
|
||||
The suite contains two kinds of checks:
|
||||
|
||||
Unit tests (`make -C backend test`) cover the ledger rules without a database:
|
||||
- Real backend flows: registration, profile, questionnaire, organizations, hiring needs, search, invitations, and the minimal path in `acceptance-path.spec.ts`. The mail stand enables their fixtures.
|
||||
- API replacement through `page.route`: screen states, errors, conflicts, and parts of assessment and accessibility scenarios. These tests verify browser behavior in the supplied state.
|
||||
|
||||
- `internal/domain/` (`consent_test.go`): only `c1` to `c5` are purposes and only C4 is organization scoped; a text version follows the contract pattern of 1 to 64 characters; a text hash must be 32 bytes and not all zero; a stored text whose body no longer matches its hash, a C4 text without the `{organization}` placeholder, and another text with it are refused; the rendered C4 text hashes differently per organization and from its template, and an empty, padded, or multi-line organization name is refused. `NewConsentGrant` refuses C4, an empty or malformed version, a missing hash, subject, or time, and a source that the purpose does not allow; `NewContactConsentGrant` requires the C4 text, the organization with a valid name, a field set, the invitation, and a positive terms version, and hashes the text as shown for that name. Grants and revocations print and log no subject, organization, name, or field. A field set is canonical in any input order and refuses empty, repeated, unknown, and more than four fields. `RestoreConsentRecord` refuses what the database refuses, and a record prints and logs only its ID, purpose, and state.
|
||||
- `internal/adapter/secondary/postgres/` (`consents_test.go`): ledger constraint errors map to their sentinels by SQLSTATE and constraint name without the row detail, the restricting consent key in the cleanup maps to `ErrTransactionConflict`, invalid input fails before any statement, every generated row type converts to one record row, and the stored field set keeps the order the database accepts.
|
||||
- `internal/usecase/consent/` (`service_test.go`, with an in-memory text repository, ledger, transactor, and a controllable clock): a grant of C1, C2, C3, and C5 records the current text version and hash, the source of its entry point (`GrantAtRegistration` fixes C1 and `registration`, `GrantInSettings` fixes `consent_settings`), and the time of the injected clock, never another time; a grant with an older, unknown, or scheduled version fails with `ErrStaleConsentText`, names the current version, and never reaches the ledger; granting version one, publishing version two, and repeating version one is stale and leaves one record; `CheckTextVersion` returns the current text, fails stale for an older, unknown, and scheduled version, refuses an unknown purpose and a malformed version, and never touches the ledger; C4 on the generic path fails with `ErrScopedConsentRequired` before any repository is read; a malformed or empty version, an unknown purpose, and a nil subject are refused; a repeat returns the existing record with `Created` false and its first time, and the ledger keeps one record; failures of the repositories (no published text, unknown subject) keep their sentinel and a missing text is not reported as stale; a subject who withheld C3 has the other purposes with their own records and no C3 record; `GrantContact` records the scope, the source `invitation_acceptance`, and the hash of the text as shown, returns the existing record for a repeat, reports an invitation of another subject as taken, and refuses a stale C4 version, a padded name, and missing fields, organization, invitation, subject, or terms version; `GrantInSettingsInNewTransaction` retries a transaction conflict after a wait, stops after three attempts, does not retry another error or a canceled context, and rolls back a stale grant; `NewService` panics on a nil transactor or clock.
|
||||
- `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` answers 501 after validation for a session and 400 with the query pointer for an unknown state, a limit over 100, and a malformed cursor; under `DenyAllSecurity` it answers 401 with or without a cookie and with a `subject_id` parameter; the DTOs carry no hash, subject, or contact field, the parameters are only the state and the page, and the contract example decodes and validates.
|
||||
- `frontend/src/shared/api/consent-contract.test.ts`: the generated Zod schemas accept a C4 record with its scope and a revoked unscoped record, refuse an unknown purpose, state, or source, an empty or malformed version, an empty or oversized field set, an unknown contact kind, and a terms version below 1, require every nullable field, and drop a hash or subject; the operation takes only the state and page parameters.
|
||||
Playwright runs Chromium with one worker and no retries. The real-bank search runs first so other specs cannot change its results. The configuration accepts only a loopback stand address.
|
||||
|
||||
`TestConsentLedger` in `backend/integration_test/consent_ledger_test.go` uses `bootstrap(t, postgresService)` with the migrated schema, publishes a second C1 text the way a migration would, and truncates the ledger between cases:
|
||||
Inspect the HTML report, trace, and screenshot on failure. Report passed, failed, and skipped counts: a green run with a required scenario skipped does not complete its acceptance. Never point E2E at a shared or production stand.
|
||||
|
||||
- The migration publishes one demo text per purpose with a matching hash; the current C1 text depends on the time; an unknown version and a version of another purpose are not found.
|
||||
- Versions and purposes: C1 at registration, C2, and a newer C1 version give three rows; the older C1 row stays byte-for-byte the same and is listed as `superseded`, the current C1 is the newer one, a repeated grant of the older version returns the existing row without a new one, and revoking C2 leaves C1 unchanged.
|
||||
- Revocation stamps once: a second revocation finds nothing and keeps the first time, the current C3 is gone, and a new grant is a new row next to the revoked one. Revoking C1 also closes its superseded row.
|
||||
- C4: the generic grant and a scoped grant without organization and fields are refused by the domain; a grant stores the organization, the canonical fields, the invitation, and the terms version, with the hash of the shown text rather than the template; a repeat returns the same row; an invitation consent of another subject fails with `ErrConsentInvitationTaken`; revoking C4 for organization A leaves organization B, and a revoked invitation consent never comes back.
|
||||
- Repository validation: an unknown subject, an empty or malformed version, an empty hash, an invented version, a version of another purpose, a hash of another text, and a grant before publication are refused and store nothing. Another subject neither sees nor revokes the owner's consent.
|
||||
- Database constraints through raw SQL: an empty version, an empty or short hash, C4 without a scope or with an empty, repeated, or unknown field, C2 with a scope or from the registration, a revocation without a source, and a hash of another text are refused by name; an update of a granted row, a revocation that also moves the grant, a second revocation, an update or delete of a published text, and a delete of an account with consent history are refused.
|
||||
- Read model: pages of three return exactly the owner's four records newest first and never the other subject's; the state filter returns the active and the revoked records.
|
||||
- Business transaction: a C4 grant rolls back with a failing acceptance, a failing statement after the grant rolls back the whole transaction, and a committed acceptance is visible after the commit and to its own transaction before it.
|
||||
- The unverified account cleanup deletes the stale account with its C1 row and keeps the verified account and its record.
|
||||
- C4 snapshot: raw rows whose hash belongs to another organization name, to another name than the stored one, or to the template are refused (`consent_records_c4_text_hash`), C4 without a name and C1 with one are refused (`consent_records_c4_scope`); after a rename, two acceptances keep their own names, and each hash still proves the text shown with its snapshot.
|
||||
- A revocation dated an hour before the grant is stamped at the grant time.
|
||||
- Deleting a consent row of a confirmed account is refused (`consent_records_retained`); a row of an unconfirmed account can be deleted.
|
||||
- Re-registration: `UpdateRegistration` and a new C1 grant in one transaction leave only the new C1; a stale re-registration and an attempt on a verified account change and delete nothing.
|
||||
- Eight concurrent grants of one version on their own connections store one record, and all of them return it with exactly one `created`.
|
||||
- Twenty rounds of a grant racing a revocation return no error other than `ErrTransactionConflict` and never leave more than one unrevoked record of the version.
|
||||
- With only the consent row of a stale account locked, the cleanup on a session with a 200 ms lock timeout skips the account without waiting, and deletes it after the lock is gone.
|
||||
### Demonstration flow acceptance
|
||||
|
||||
`TestConsentGrants` in `backend/integration_test/consent_usecase_test.go` runs the usecase on the bootstrap database with a fixed application clock, a second C1 text, and a C5 text scheduled after the clock:
|
||||
Before presenting, run `make docs-check`, `make -C deploy check`, smoke and the mail-enabled E2E suite. `acceptance-path.spec.ts` must pass the full test with a `synthetic_demo` category, publication, search with an explanation, invitation, C4 and contact disclosure; repeated acceptance must not create duplicates, and revocation must close contact access. A skipped spec is not acceptance.
|
||||
|
||||
- Registration: `UserRepository.Create` and `GrantAtRegistration` of C1 run in one `Transactor` transaction with no session (the sessions table stays empty) and commit one account and one C1 at the application time with the current text version. C2 and C5 follow as separate operations, each with its own active record; C3 is withheld and has no record while the others stand; a C3 granted later and revoked leaves C1, C2, and C5 active.
|
||||
- Atomicity: a transaction that fails after the account and C1 were written leaves neither, and a grant for a subject without an account fails with `ErrUserNotFound` and stores nothing.
|
||||
- Idempotency and versions: a repeat in its own transaction and in a business transaction returns the first record and its time and stores no row, and a repeat does not abort the transaction. An outdated C1 version, a scheduled C5 version, and an unknown C3 version fail with a stale error that names the current version and store nothing; the current C1 version goes through and the outdated one stays refused. A grant after a revocation is a new row. Eight concurrent repeats create exactly one row.
|
||||
- Republication: after C3 version one is granted and version two is published, a repeat of version one is stale, names version two, and leaves one row and the first record as the current C3.
|
||||
- Re-registration: `UpdateRegistration` followed by `GrantAtRegistration` in one transaction returns `created` true with a new record and leaves exactly one C1. The opposite order is shown as a hazard: the grant finds the earlier registrant's C1 and returns it with `created` false, the update then deletes it, and the account ends with no C1.
|
||||
- C4: the generic path refuses it and stores nothing; `GrantContact` in a transaction stores the organization, the name, the fields, the invitation, and the source `invitation_acceptance`; a repeat returns the same record, an outdated C4 version is stale, and the C4 does not create a C2.
|
||||
- Restart: after the pool is closed, a new pool, store, and usecase list the same four records in order with their states, the revocation stamp and source, and the original grant times, and a repeat grant through the new instance stores nothing.
|
||||
Match the evidence to the deployed commit or images. A local mail fixture does not demonstrate real Resend delivery, local Nginx does not prove external HTTPS, and a synthetic bank does not establish grade accuracy. For a release, repeat smoke and E2E on the fixed images as described in [DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
|
||||
`TestRegistrationConsentMigration` applies migration 00016 in an isolated database and checks legacy C1 binding, no binding for settings grants, inserts through the old row shape, rejection of a supplied mismatched version, protection against changing the version during revocation, and down/up. A separate case confirms that stale registration C1 stops the migration without partial changes. `TestPostgresMigrations` continues to cover migration 00009. Registration and email confirmation integration tests exercise the consent service through the API flow; `TestConsentGrants` covers the usecase separately from HTTP. Revocation and C4 invitation acceptance are not covered as business flows. The cleanup race with SQLSTATE 23001 is covered only by its mapping unit test because its window cannot be reproduced deterministically.
|
||||
## ML and models
|
||||
|
||||
## Organization tests
|
||||
`make -C ml verify` checks formatting, Ruff, mypy, pytest, packaging, the contract, and Pydantic model drift. Ordinary tests are separate from slow checks using real weights.
|
||||
|
||||
Unit tests (`make -C backend test`) cover the organization rules without a database:
|
||||
```sh
|
||||
make -C ml model-fetch
|
||||
make -C ml test-model
|
||||
```
|
||||
|
||||
- `internal/domain/` (`organization_test.go`, `membership_test.go`): a profile accepts a name only and a complete card; every rule names the field that breaks it by a JSON Pointer (`/name`, `/contacts/website`, `/representatives/1/name`) without quoting the value: an empty, padded, multi-line, over-long, or non-UTF-8 name, a description or sphere with a line break or control character, a website that is not `https` or has credentials, a port, an IP address, a numeric or hexadecimal host, or no dot, an email without a domain dot, a phone outside E.164, a Telegram username without `@`, and eleven representatives. CRLF in a description is stored as LF. `NewOrganization` starts at version 1 with a UUIDv7 and the level `e0` on `confirmed_email`, whatever the profile looks like; `ApplyProfile` keeps the identifier, the version, and the verification and never moves the update time backwards; a level pairs only with its own bases; `e0` to `e2` map to the quota tiers of the policy and `e3` has none; a stored row that was changed outside the application fails to restore. The card holds the profile and the level only. A representative is redacted in `fmt` and `slog` output, also inside an enclosing struct, and an organization logs only its identifier, version, and level. Only the owner manages the company, only an `active` membership gives access, the four roles and four states are the contract values, and `NewMembership` refuses a nil identifier, an unknown role, and a zero time.
|
||||
- `internal/adapter/secondary/postgres/` (`organizations_test.go`): organization constraint errors map to their sentinels by SQLSTATE and constraint name without the failing row, which holds representative names; other errors keep only the SQLSTATE and the constraint; a deadlock maps to `ErrTransactionConflict`; invalid input fails before any statement; the manager roles passed to SQL come from the domain rule.
|
||||
- `internal/adapter/primary/http/` (`organization_test.go`): under a session the operations answer 501 after validation and 400 with the pointer for each rule of the schema (a name over 200 characters or with a line break, a missing `expected_version`, contacts that omit a field, an http website or one with credentials, a phone outside E.164, a Telegram username without `@`, eleven representatives, a representative with a contact, null `name`, `contacts`, or `representatives`, a limit over 100, an identifier that is not a UUID); the representatives of the candidate card may be absent, null, or empty, and a card without contacts is refused. Each of eleven fields that would carry a right or a trust level (`role`, `owner_id`, `verification_level`, `verification`, `verification_basis`, `members`, `membership`, `candidate_card`, `id`, `version`, `created_at`) is refused alone on create and on update with the whole-body pointer. Under `DenyAllSecurity` all four operations answer 401, with or without a cookie and with a `user_id` parameter. The request DTOs have exactly the profile fields and no role, owner, member, or verification field, the card has no membership, role, basis, or time, the list takes only the page, an absent list differs from an empty one in `OrganizationUpdate`, every documented example decodes and validates, and the bundle has closed request objects, the CSRF scheme on both writes, the Idempotency-Key on create, 412 on update, and no operation that sets a level or a role.
|
||||
- `frontend/src/shared/api/organization-contract.test.ts`: the generated Zod schemas accept a name only and a complete card for create and update, require `expected_version`, accept null only for `description` and `sphere`, refuse the same limits as the contract, drop a role or a verification level that a client adds, list the four levels, roles, and states, and, at the type level, give the requests no role, owner, member, verification, or identity field, the card no membership or basis, and the membership no account.
|
||||
`model-fetch` downloads pinned Giga and Qwen3 embedding files and checks SHA-256; it requires access to the weight source and disk space. `test-model` compares real models with research vectors; set `ML_TEST_DEVICE=cuda` for a GPU. This checks inference reproducibility, not matching quality for real candidates.
|
||||
|
||||
`TestOrganizationsAndMemberships` in `backend/integration_test/organizations_test.go` uses `bootstrap(t, postgresService)` with the migrated schema and truncates the organization tables with `users` between cases:
|
||||
## Runner and labs
|
||||
|
||||
- Storage: an organization is stored with its owner and read back with its profile, representatives in order, version 1, the level `e0`, and the active owner membership; fields that are not set are NULL.
|
||||
- Membership uniqueness: a repeated membership of the same account and organization, in each of the four roles and after the member left, fails with `ErrMembershipExists` naming `memberships_user_id_organization_id_key`, a raw insert fails with SQLSTATE 23505, and only one row remains; another account or organization is another pair.
|
||||
- Atomic creation: an unknown owner account rolls back the organization, its representatives, and the membership; a later failure of the same transaction does too; an owner membership that is a recruiter, belongs to another organization, or is zero is refused before any write.
|
||||
- Owner at commit: a transaction that inserts an organization alone, with a recruiter only, with a suspended owner only, or with an owner that it moves to `removed` before it commits fails at commit with SQLSTATE 23514 on `organizations_owner_required` and leaves nothing; an organization and an active owner inserted in one transaction commit.
|
||||
- Scoped list: the organizations of one account include the ones where it is a recruiter and exclude those where its membership is suspended, left, or removed and every organization of another account; pages of two follow the same order with no gap or repeat; memberships created at the same instant order by the organization identifier; invalid queries, including a position without an organization identifier, are refused; an organization without representatives reads back with an empty list.
|
||||
- Access: an account that is no member, an unknown account, an unknown organization, and a `suspended`, `removed`, or `left` member all get `ErrOrganizationNotFound`, a restored member reads again, and `Memberships().Get` returns the stored state in any state.
|
||||
- Update: the owner replaces the profile, the representative list, and the contacts, the version advances to 2 and the update time changes, cleared fields become NULL, and a verification level that a process set to `e1` is still `e1` after the next profile update. A recruiter gets `ErrOrganizationManagerRequired`, a suspended owner, an outsider, and an unknown account get `ErrOrganizationNotFound` even with a stale version, a stale version gets `ErrOrganizationVersionConflict`, and none of them changes the stored organization.
|
||||
- Revocation during an update: a transaction that revokes the second owner stays open, an update by that owner queues behind its membership lock (seen in `pg_stat_activity`), and when the revocation commits the update returns `ErrOrganizationNotFound` and writes nothing. Without `FOR SHARE` on the actor's membership the test fails.
|
||||
- Concurrency: eight updates from the same version on their own connections give exactly one success and seven conflicts, and the stored name and representative belong to the same winner.
|
||||
- Constraints through raw SQL: an empty, padded, multi-line, or over-long name, an unknown level, a basis of another level, version zero, a description with a padded end or a control character, a sphere with a line break, an http website or one with credentials, an email with a space, a phone without `+`, a Telegram username without `@`, an update before the creation time, the level and basis pairs of `e1`, `e2`, and `e3` (the right ones accepted, the wrong ones refused), a composite foreign key onto `(organization_id, id)` of the memberships (accepted for the member's own organization, refused for another), an unknown role (including `manager`), an unknown state (including `invited`), an eleventh representative, and a padded job title are refused by constraint name; the organizations table has no column for a role, an owner, a member, or a user.
|
||||
- Deletion: an account with a membership and an organization with a member cannot be deleted (SQLSTATE 23001); once the memberships are gone, the organization takes its representatives with it.
|
||||
`make -C runner check` and `make -C labd check` check the Go modules. Their unit tests need neither a running sandbox nor LXD.
|
||||
|
||||
`TestPostgresMigrations` rolls migration 00010 back with the others, checks that its three tables and its function disappear while the identity tables stay, and checks them again after the second migration. The tests that truncate `users` name `usersDependentTables` (identity, delivery, consent, and organization tables), the one list to extend when a migration adds a table that references users. This storage suite does not cover the usecases or HTTP; the separate tests below use real sessions and CSRF. The atomicity of the single-statement read of the organization with its representatives is not proven by a test, because the window between two statements cannot be reproduced deterministically.
|
||||
Real runner, isolation, and lab checks run separately in environments intended for testing. [runner/](../../runner/README.en.md) and [labd/](../../labd/README.en.md) describe their requirements and commands. Results from a local development container do not establish isolation of the deployed runner.
|
||||
|
||||
`TestOrganizationCreationAndOwnerEditingOverHTTP` and `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` exercise organization creation and editing, idempotent replay, the caller's paginated directory, owner-only actions, foreign organizations, and revoked membership over real HTTP and PostgreSQL. Revoking a second owner closes the profile and tenant operations for the same cookie while preserving another owner's access. Middleware tests enumerate every tenant operation in the contract.
|
||||
## Contracts, infrastructure, and security
|
||||
|
||||
`TestCompanyIsolationAndRevocationOverHTTP` (`backend/integration_test/company_isolation_http_test.go`) checks company isolation and revocation across the minimal path over real HTTP and PostgreSQL. Company A runs a need, a search, a card with its evidence, an invitation accepted with C4, the contact read, and an inbox item. Company B, and a second company of A's own owner in the same holding, then call every organization-scoped operation with a valid session, on A's path and on their own path with the identifiers from A's responses. Each call must answer the documented refusal, identical to the answer for a random identifier, and A's objects must stay unchanged. A candidate gets the same check against another candidate's invitation and notification. The test also checks that hiding the organization, revoking C4, and withdrawing C2 close the very next read through the handles of an earlier search, the invitation page, and the contact read. A new C2 or a new publication must not revive a grant that C4 revocation closed. The MVP must serve no PDF, selection snapshot, or stored search result, and the server log, outbox payloads, inbox rows, and stored email requests must carry no contact, name, or profile value. It does not cover Kafka, the browser, or roles other than the owner.
|
||||
After an API change, run `make generate`, check its consumers, and run `make check-generated`. For intentional output updates, review and commit the expected diff together with its source.
|
||||
|
||||
## Candidate profile tests
|
||||
`make -C deploy check` validates configuration and supporting scripts. `smoke` checks infrastructure readiness and HTTP routes; `perimeter-test` checks Nginx rules using throwaway containers. Neither replaces a business flow. `make -C observability check` validates monitoring configuration.
|
||||
|
||||
Unit tests (`make -C backend test`) check the profile rules without a database:
|
||||
`make security` checks dependencies, source, and secrets; `make security-images` builds and scans images. [security/](../../security/README.en.md) explains tool installation and reports.
|
||||
|
||||
- `internal/domain/candidate_test.go`: manual values get the source `manual`, trust level 0, and the save time; a field sent as null is removed and a list is replaced; an imported suggestion stays unconfirmed under `extracted` with the same value, is confirmed under `confirmed` while keeping its source and quote, becomes manual under another value, while `extracted` for a value that is not among the suggestions and moving a confirmed value back to a suggestion are rejected with the pointer `/stack/1/status`; a table of values names the field that broke the rule (a phone outside E.164, a Telegram name without `@`, a name with whitespace, a salary that is not a multiple of 1000, an unknown specialization or grade, a tag repeated without regard to case, a repeated role specialization, a month outside `YYYY-MM`, a period that ends before it starts or lies in the future, too many items); an error never contains the submitted value; a body that changes nothing leaves the profile and the confirmation time unchanged; the storage rows (`StoredClaims`) restore to the same content in any order, and a row with an unknown kind, a trust level above 0, a quote on a manual value, a value of another type, an extra `confirmed_grade` key, a gap in a list, or a repeat is rejected; the profile types have no field for a confirmed grade, a category, or a trust level; the values are hidden in `fmt` and `slog` output.
|
||||
- `internal/adapter/primary/http/candidate_profile_contract_test.go`: by the contract bundle, the operations follow the conventions (session and CSRF for the save, the version in the body, no Idempotency-Key or If-Match, 412 rather than 409, `no-store`); a request carries no confirmed category, source, trust level, or confirmation time, and every profile schema closes its objects; each claim carries `status` and `source`, and `trust_level` is limited to zero; the full name uses `ContactFullName`; **no schema outside the profile family and no operation of an organization reaches a profile schema through references, and the profile refers to no organization, invitation, or need schema**; through the generated server the schema rejects a client-sent category, source, and unknown fields before the implementation, a valid profile answers 501, and a denied session answers 401.
|
||||
- `frontend/src/shared/api/profile-contract.test.ts`: the generated Zod schemas accept a complete profile and a profile with no value at all (that is, without a file or FSP), require `expected_version`, reject each broken format and extra list items, let no confirmed grade, category, or source into the parsed body, require every claim to have a source with trust level 0, and the request types have none of these fields; the generated organization, invitation, and need files hold no profile keys, and vice versa.
|
||||
## Reporting checks
|
||||
|
||||
`TestCandidateProfileStorage` in `backend/integration_test/candidate_profile_test.go` uses `bootstrap(t, postgresService)` with the migrated schema; `candidateProfileTables` belong to `usersDependentTables`, so the other tests truncate them together with `users`:
|
||||
Record the command, checked commit or diff, outcome, and relevant limitations. Preserve a reproducible failure case without secrets. Assessment validity, matching quality, and performance need separate datasets, methods, and measurements.
|
||||
|
||||
- Saving without a file, ML, or FSP: a profile with only a name, and a profile row with no claim at all, are saved and read back, and a complete profile returns the same content and sources through `StoredClaims` and `RestoreCandidateProfile`; a stored import suggestion reads back with its quote, extraction version, and level 0.
|
||||
- Schema: the columns of the two tables equal the expected list (no file, FSP, confirmed grade, or category), and the only foreign keys lead to the account and to the profile row.
|
||||
- Constraints through direct SQL: each rule refuses a row with its own constraint (a trust level above 0, an unknown kind, status, and origin, a single field with a position, a list past its limit, a confirmation without a time, a manual value with a quote, an import without an extraction version, wrong values of a tag, a phone, a Telegram name, relocation, a salary, a role with a `confirmed_grade` key, and experience); a repeated tag, skill, or role specialization, a profile without an account, version 0, and a claim without a profile are refused too, while the same valid row is accepted.
|
||||
- Deleting the account deletes the profile and its claims; two accounts keep their profiles apart.
|
||||
- Version: a lost second first save and a stale version return no row, eight advances from one version and eight concurrent first saves on their own connections give exactly one success, and an advance with an earlier application clock keeps the update time and violates no CHECK. Reading uses the single `ReadCandidateProfile` query.
|
||||
|
||||
`TestCandidateProfileMigrationRollsBack` rolls migration 00013 back on an isolated database and checks that both tables disappear while `users` stays.
|
||||
|
||||
`TestCandidateProfileOverHTTP` checks the caller's profile through a session and CSRF: an empty GET, complete save and API restart, specific date and overlap errors, parallel-work confirmation, 412, no history write on a no-op, foreign-profile isolation, and employer denial. History, data, and the conditional onboarding transition share one transaction; injected history and step-transition failures roll back the save. Changing self-assessment does not create a confirmed category.
|
||||
|
||||
## Candidate questionnaire tests
|
||||
|
||||
`TestCandidateQuestionnaireOverHTTP` uses real sessions, CSRF, and PostgreSQL. It checks an empty version-zero questionnaire, save and handler restart, account isolation, employer denial, rejection of unknown confirmed-grade fields, different concurrent writes returning 200/412, identical concurrent writes returning 200 with one version increment, conditional onboarding, rollback, paired experience constraints, and catalog invalidation after a policy change or family retirement. Self-assessment never creates a confirmed category. The canonical API uses 412 for version conflicts; older task wording mentions 409.
|
||||
|
||||
The isolated mail overlay sets `IDENTITY_CLIENT_HOURLY_LIMIT=200` because all browser scenarios share one proxy address. Ordinary and release configuration retain 30, and per-email limits remain unchanged.
|
||||
|
||||
`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior with Go and Python. The test-only `questionnaire-fixture` command accepts only the unchanged initial demo policy, explicitly publishes `DemoProductPolicyV2`, then publishes the required number of reviewed families before binding the catalog. This also enables the support and assessment policy sections for browser tests. It refuses existing backend bank ownership or another current or scheduled policy and is absent from ordinary and release images. Normal startup still seeds V1 only. The browser scenario walks the questionnaire steps (step validation, the focus on the heading, "Назад" and "Изменить" without losing answers) and covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled.
|
||||
|
||||
`assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training with the resumption of an unfinished run after a reload (409 to a new start, then 201 for the stored key), offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration.
|
||||
|
||||
## Minimal path from registration to disclosed contacts
|
||||
|
||||
In the registration mode the overlay `docker-compose.e2e-mail.yml` sets `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` on the test backend and gives Playwright `E2E_DEMO_CATEGORIES=1`. After `questionnaire-fixture`, the runner attests the opened Backend Junior category with the operator command `/assessment-category-attest` from the test backend image, so a passed full test of this stand receives the uncalibrated `synthetic_demo` category, as on the demo stand. The ordinary and release suites keep the default `false`, and `make -C deploy check-e2e-mail` checks both settings.
|
||||
|
||||
`frontend/e2e/acceptance-path.spec.ts` walks the minimal path on the real backend without an FSP ID. Five candidates register with the link from the received message, fill the profile and the questionnaire, grant C3, solve every item of the full test from its statement, and publish an identical card after an explicit C2, because a card is shown only in a group of five. The spec then checks:
|
||||
|
||||
- the result `confirmed` with the category decision `assigned`, `demo_basic_pass_mark`, `synthetic_demo`; a reload in the middle of the attempt returns the same attempt without a second answer, and the result history keeps one entry after a reload and a step back and forward in the browser history;
|
||||
- a need, the search by its requirements version with the five confirmed entries and the explanation from the server, a filter by the declared grade senior that removes all five cards and keeps only cards of other specs with that grade, and the unchanged result of the first requirements version after the need is edited;
|
||||
- three invitations bound to the first requirements version, delivered once each; no search result, invitation list, or organization notification holds an email, a phone, or a name;
|
||||
- an acceptance in the browser with the email only, after which a reload and a history step add no record, there is one C4 record for the organization, and the organization reads only the email;
|
||||
- two concurrent acceptances of one invitation with different keys: both answer 200 with the same body, one C4 record and one grant;
|
||||
- a decline without access and the refusal 409 `state_conflict` of a new invitation for the same pair;
|
||||
- a second company that gets 404 or a field error, never data, for the need, the search by that need, the cards, the invitations, and the contacts of the first one;
|
||||
- C2 revocation that closes the contact read and the cards of the earlier result at once (the four remaining cards fall below the group of five and are suppressed too), and a new C2 and publication that reopen the cards but not the grant of the accepted invitation.
|
||||
|
||||
The spec does not check the planned transitions without an operation (withdrawal, cancellation by the candidate, the counter offer, the interview, the closed final), the 20-invitation limit per need and the expiry (backend integration tests cover them), category recommendations for a need, which stay `pending`, or a PDF. Traces and screenshots are off; the data are synthetic.
|
||||
|
||||
## Candidate visibility tests
|
||||
|
||||
Unit tests (`make -C backend test`) check the visibility rules without a database:
|
||||
|
||||
- `internal/domain/visibility_test.go`: the card field set is canonical, closed, and refuses the full name, any contact, and the salary; a publication request needs a field to publish and none to close; a new profile is closed and never published; publishing needs an active C2 and names no consent; the order of checks (a future version, an unchanged state over a stale version, a stale change, a missing consent); a revoked C2 closes the card and a new C2 does not reopen it; the search status lapses after the interval of the policy to the non-public status without a write, is confirmed again explicitly, and takes the interval from the policy version; stored rows that break an invariant are rejected; the types log only identifiers.
|
||||
- `internal/adapter/primary/http/candidate_privacy_contract_test.go`: by the contract bundle, the operations follow the conventions (the CSRF scheme exactly for changes, the version in the body, no Idempotency-Key or If-Match, the same 404 for hiding, 204 without a 404 for lifting); the publication and the search status carry no consent and reach no schema of each other; **the anonymous card and the preview reach no profile, contact, consent, invitation, or organization schema and have no property that names or identifies a person**, and no organization path reaches a setting; through the generated server the schema rejects a contact as a card field, a consent identifier, and a client-sent time before the implementation, a valid request answers 501, and a denied session answers 401.
|
||||
- `frontend/src/shared/api/privacy-contract.test.ts`: the generated Zod schemas read a new candidate as closed and not looking at version 0, reject a card field that is a name, a contact, or the salary, strip a consent, a time, and an interval from the parsed requests, keep the card closed to contacts, and the generated organization, invitation, need, profile, and consent files hold no setting keys.
|
||||
|
||||
`TestCandidatePrivacyStorage` in `backend/integration_test/candidate_privacy_test.go` uses `bootstrap(t, postgresService)`; `candidatePrivacyTables` belong to `usersDependentTables`:
|
||||
|
||||
- A new profile has no published state: after saving a profile all four tables are empty and the reads return no row. A hidden organization is unique per candidate and belongs to the candidate; an unknown organization is refused by the reference; lifting deletes once; the 1001st record is refused by the trigger.
|
||||
- Publication: the foreign key accepts only a C2 record of the same account; a revocation in the ledger closes the card without a write; a new C2 grant publishes nothing; a stale update returns no row; the constraints refuse a contact as a field, a wrong order, and a wrong state shape.
|
||||
- Search status: in a fixture the status is set, confirmed, and cleared, and the raw rows of the consent ledger, the publication, and the hidden organizations stay equal; looking stores the confirmation under the policy version with the interval of the policy; a lapse changes no row; the constraints refuse looking without its confirmation; the table has no consent column and references only users.
|
||||
- Closing over a revoked C2 normalizes the stored row and records the closing; an organization reads a publication only through the effective view and not when it hides the reading organization (the same no-row answer as for an unpublished profile); a revocation racing with a publication, held under `LockCurrentC2Record`, waits for it and closes the card after it, or finds nothing to lock; eight concurrent hidings at 999 records let exactly one through; the unverified account cleanup removes the hiding records and history of an unverified account and spares a confirmed one. `backend/db/privacy_queries_test.go` fails when a query other than the three settings queries names `candidate_publications`, and `TestCardTextLooksLikeContact` pins the drop of free text that looks like a contact.
|
||||
- History: append-only (UPDATE refused, DELETE refused while the account is confirmed), identifiers only, the shape of each kind is checked, pages continue by position, and the published fields and the C2 record are kept with their time. No privacy table has a column for a profile value, a name, a contact, or a file.
|
||||
|
||||
## Assessment bank tests
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. `assessment_choice_test.go` covers the choice format without a database: the same seed gives identical options, IDs, and order, and across 400 seeds the correct option appears at every position; every distractor of `lru_hits_choice.v1` is recomputed from the statement as the result of a named error model (and the nearby fill-in is used only when the models give fewer than three distinct values), the options never repeat a text, the cache models match hand-computed cases and the LRU model equals the solver of `lru_hits.v1`, and a golden test pins the options, their IDs, and the key of one seed; the correct option, a wrong option, an option of no item, two options, a number answer for a choice item, and a choice answer for an integer item are graded or refused as stated, the candidate projection holds only the opaque IDs and texts, and a broken key or repeated option of a frozen variant is refused. `assessment_table_test.go` covers table families: rows are selected by seed, the answer is the written one, the selection of fixed seeds is pinned, each of 39 format errors (missing column, repeated row, bad answer, duplicate distractor, oversized statement, a call or pipeline in the template, an algorithm beside a table, and so on) is refused with the index of the row, the scheme 2 hash of a fixed table is pinned against its canonical document, any change of the table changes the hash, scheme 1 and scheme 2 each refuse the other kind of generator, and an edited stored table fails the integrity check. `bundle_test.go` reads a table bundle and refuses a row with an unknown field. With in-memory fakes of the repository and the unit of work, the usecase tests prove that a concurrent identical import reports the version as unchanged and a concurrent import with other content is refused, that the sentinels of database races become refusals with the matching reason, that publishing retires the older published version after taking the category lock and is refused when a newer one is published, that opening requires the policy version in force, that availability is refused when the published count falls below the opening's requirement or when the opening's policy version is no longer in force, and that an older approved draft is refused while a newer version exists as a draft, a published, or a retired one. `internal/adapter/secondary/postgres/assessment_bank_test.go` checks that the bank constraints map to their sentinels without the failing row, that a list page outside its limit fails before any statement, and that the category lock is refused outside a transaction.
|
||||
|
||||
`TestAssessmentBank` in `backend/integration_test/assessment_bank_test.go` uses `bootstrap(t, postgresService)` and gives every case its own migrated database:
|
||||
|
||||
- Two versions of one family are imported and version 1 is read back with its original key, while version 2 has a different key; a repeated import changes nothing, the same version with other content and a skipped version number are refused with reasons, and raw SQL cannot edit the key, the version, or the review, delete, or truncate (SQLSTATE 23000 on `assessment_families_immutable`).
|
||||
- One seed gives the same statement and reference answer from the stored version, and a different seed keeps the rubric of every demo family.
|
||||
- The demo bundle imports as drafts; publishing each family is refused with `reviewer_missing`, the table refuses publication without an approved review, and opening `backend` is refused with `coverage_insufficient` and stores no opening.
|
||||
- An opening without a policy reference, with an unknown one, or with a policy version that is not the one in force is refused with the matching reason.
|
||||
- A test bundle that carries an approved review by a reviewer who is not its author (a fixture of the loader rules, not demo content) is published one family at a time; the category opens only when the published families reach the policy's `max_scored_items` plus `seed_items`; the opening records the policy version, the operator, and the counts, the required number the database derived equals the one the domain computes, and the opening cannot be edited. Retiring one family afterwards makes the availability read refuse with `coverage_insufficient`. A published version cannot be published again, can be retired once, and cannot move backward.
|
||||
- Publishing a later version of a family retires the published older version and records both operators; publishing an older version while a newer one is published is refused; the table allows one published version per family and refuses a rewrite of the recorded publisher.
|
||||
- A transaction that holds the category lock makes an opening wait until the deadline, and the opening succeeds after the lock is released.
|
||||
- An older approved draft cannot be published once a newer version exists, also when that version is retired. Policy-in-force checks use the database clock, with no clock offset in the test.
|
||||
- A bundle with a table family and a choice family is imported with hash scheme 2 for the tables and scheme 1 for the algorithm, imported again as unchanged, and the stored rows generate the same variants twice; a raw edit of a stored table is refused as an edit of a stored version.
|
||||
- `TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP` in `backend/integration_test/assessment_choice_http_test.go` runs a real attempt over a bank of a choice algorithm, an integer table, and a choice table: every item the candidate receives has only the allowlisted fields (for a choice the option IDs and texts in the stored order, and no key, seed, or distractor field), an option of no item and two options are refused with 400, a wrong choice scores nothing and a right one scores through the key, the result matches the expected points, and every answer left a signal observation.
|
||||
- Raw policy rows whose document lacks the scored item bounds or holds them as text, as an oversized, fractional, or negative number, or without the seed items are refused by the opening trigger with the thresholds refusal, not with a cast error; a stored hash scheme outside the CHECK list is refused, and the scheme cannot be edited.
|
||||
- Written around the usecase, an opening that claims a lower requirement, an opening below the coverage, an opening under an unknown policy version, and a title with a bidirectional override are refused by the table.
|
||||
- Families are listed in pages of two after a cursor, each once and in order.
|
||||
|
||||
`TestPostgresMigrations` rolls migration 00011 back with the others and checks that its two tables and five functions disappear while the policy table stays. The suite proves the storage and loader rules only: it does not validate the content of the demo bundle, task difficulty, or any grade, it does not prove the serialization of concurrent publications beyond the held-lock case, and it does not cover a candidate-facing flow, because none exists yet. Integration tests need Docker.
|
||||
|
||||
## Assessment signal and review band tests
|
||||
|
||||
`backend/internal/domain/assessment_signal_policy_test.go` and `assessment_signal_review_test.go` check without a database: the demo signal section is valid and round-trips through the schema 2 document, a signal section alone is a valid extension and never acquires defaults, schema 1 rejects the key, out-of-range and inconsistent thresholds are refused, response times follow the per-format floors and the median ratio only on the fast side within one format and leave out the first item of a session, origin marks count alternations and distinct networks in time order (a return to an earlier network is not a new one), the band follows the policy, weak signals (parallel sessions and extra networks, one correlated group) stop at attention unless a strong signal is raised, an answer counts once as fast or as a deviation, client signals only raise a band to attention, and the operator handle must be `operator:<handle>`. `backend/internal/usecase/identity/keyring_test.go` checks the new keyring methods: the answer fingerprint is deterministic, keyed, and scoped to the family version; session and network digests differ across attempts (no linking), across sessions, and across client keys, and use separate purpose keys.
|
||||
|
||||
`backend/internal/usecase/assessment/signal_review_test.go` checks the observer and the review job with fake ports: an accepted answer stores the server time, whether it is measured from the previous answer, the key version, and the keyed fingerprint only, with no answer text, address, or session ID in the stored values or in the error text; origin marks are written only when the session or network changes; the first answer schedules the deadline job (one minute after the deadline) and finalization the ended job; training attempts and requests without a session store nothing; a policy version without a signal section makes no review; the job rejects a broken payload, ignores a missing attempt, locks the reviews of a pair in ascending attempt order before it reads any fact and writes them under their own pinned policies, and refreshes only ended attempts at the attention level, bounded. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each demo family, builds the distribution of shared values with their bits, and computes the probability that one honest pair reaches each demo threshold on a 23-item attempt; times 10,000 rivals it gives about 4e-5 (attention) and 3e-9 (review), against the targets 1e-3 and 1e-8. `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs for the demo thresholds to flag it (26 for attention and 61 for review at 13 items, 9 and 14 at 23 items). The FP model uses the distribution of reference answers only, not wrong answers or correlated mistakes. The targets are test constants chosen here, not a product decision, and the measurement covers four AI-drafted families.
|
||||
|
||||
`backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go` walks every path of the public contract through its references and refuses any property, schema name, or enum that would carry the band, its reasons, fingerprints, or origin digests, and checks that the signal receipt still has exactly `status`, `accepted_events`, and `received_at`. `backend/internal/adapter/primary/cli/assessmentreview/command_test.go` checks argument validation before any environment read, the printed fields, and sanitized errors. The bootstrap test checks that the review job kind is registered.
|
||||
|
||||
`TestAssessmentSignalReviewOverHTTP` in `backend/integration_test/assessment_signal_review_http_test.go` runs the real router, PostgreSQL, and the scheduled job worker:
|
||||
|
||||
- A candidate answers every item within milliseconds from two login sessions and three network addresses and sends paste events from the second session. Before the worker runs no review exists and the review jobs are pending, so nothing was computed in a candidate's transaction. Then the attempt has the band `attention` with the reasons fast answers, parallel sessions, extra networks, and client signals, and its result is `confirmed`, equal in outcome, score, limitations, and mode to the result of an equally correct attempt with band `normal`; no assessment table other than the review table has a band column.
|
||||
- A policy version with other thresholds is published while attempts are in progress and the category is opened under it. The attempts started earlier keep the first version, the attempt created later is pinned to the new version and stays `normal` for the same behavior, and its facts are still stored.
|
||||
- Two candidates with different seeds copy the same wrong answers: the first attempt has no duplicate flag until the second candidate has answered and ended, and then both have the band `review` with the reason duplicate answers. A third copying attempt is abandoned: while it runs it is not flagged, and after it ends its job at the deadline (the worker clock is moved past it) flags it. Honest attempts with correct answers are not flagged even when a low-entropy answer coincides, and an attempt with one session and one network has exactly one origin mark.
|
||||
- Candidate reads of the attempt, the result, and the availability contain no band, reasons, fingerprints, or signal names. The operator command prints the band and its audit rows are written for a found and a missing attempt; an actor without the `operator:` prefix is refused. Facts, reviews, and audit rows refuse UPDATE and DELETE, and the audit refuses TRUNCATE.
|
||||
- The logs and the text of the new tables and of `scheduled_jobs` contain no network address, answer value, session token, or CSRF token.
|
||||
|
||||
`TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag` creates 30 honest candidates with different seeds who answer each item correctly or not at random (a fixed generator) and two who copy the same answers: no honest attempt is flagged as a duplicate and both copied attempts are. The population is small, so the test uses thresholds of 32 and 44 bits instead of the demo ones. `TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt` ends four copied attempts at the same moment among eight honest ones and runs their jobs on four workers at once: no job fails or is retried and every copied attempt is flagged. `TestAssessmentSignalReviewJobWaitsForTheReviewLock` holds the review lock of an attempt in one transaction and checks that the review job waits, writes nothing, and computes the review from the committed facts once the lock is released; this is the ordering that prevents a stale evaluation from overwriting a newer review. The concurrent test was run ten times in a row (`-count=10`). `TestAssessmentSignalReviewMigrationDownRetainsAudit` checks that the rollback of migration 33 is refused while the audit holds a row (the tables and the row stay, TRUNCATE is refused) and succeeds with an empty audit.
|
||||
|
||||
The tests prove the stored facts, the policy pinning, the job-based computation, and the absence of the band from the contract and from candidate reads. They do not prove detection quality: the thresholds are uncalibrated, the false-positive measurement covers four drafted families, and no study of real candidates exists. The employer reads are covered by the contract walk, not by an HTTP call per operation.
|
||||
|
||||
## Assessment lockdown tests
|
||||
|
||||
Vitest runs in Node without a DOM, so the lockdown is checked in parts. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` covers support detection (including a browser without element fullscreen, such as iPhone Safari), that the request is issued synchronously inside the call so it stays in the click, and that a refusal is a result and not an exception. `model/cover.test.ts` is the table of when the task is covered: fullscreen exit, a hidden tab, a window without focus, a request in flight, and the mode without fullscreen. `ui/protected-region.test.tsx` renders the region with a fake lockdown and checks that a covered task leaves no text of the prompt or the options in the markup, that a cover for a left tab has no fullscreen button, and the explanation shown for an unsupported browser; `features/answer-assessment/ui/answer-form.test.tsx` checks that a concealed form renders nothing. The notice text version 4 and its list of measures are checked in `features/assessment-signals/ui/signal-notice.test.tsx`. In the backend, `usecase/assessment/signal_notice_test.go` checks that every version except the current one is refused, and `TestAssessmentSignalNoticeOverHTTP` checks over HTTP with PostgreSQL that a stored acknowledgement of version 1 does not count for the current version, and its versions follow `CurrentSignalNoticeVersion`.
|
||||
|
||||
Unit tests of the task protection: `model/task-guard.test.ts` runs the rules with small fake elements and events: selection, the context menu, and drag are cancelled on the task text and left alone in a field, a drop never fills a field, paste is refused in answer fields (and reported, so the screen can say so) and allowed in the code editor, the `beforeinput` routes of paste and drop are closed while typing and composing are never touched, and a copy or cut is refused when the target or the selection reaches into the task but not when it is inside a field. `features/answer-assessment/ui/answer-form.test.tsx` checks that only the code editor carries the paste exception.
|
||||
|
||||
Two browser specs run against a mocked API, so they need no backend data and also run against the Vite server (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`) as well as in `make -C deploy test-e2e`; the mock is in `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: leaving fullscreen covers the task (its text is not in the page), sends a `fullscreen_exit` signal, and the continue button restores the task with the typed draft; leaving the tab covers the task and returning in fullscreen shows it; a browser without the fullscreen API shows the explanation and still takes the test from the keyboard; a refused fullscreen request continues without it; closing the notice without confirming leaves fullscreen and stores nothing. `assessment-task-protection.spec.ts`: the task text is not selectable, a select-all or scripted copy leaves no task text in the clipboard, the context menu and drag are cancelled on the task but not in a field, a field copies its own text, the text stays in the accessibility tree, and printing hides the task; an answer field refuses a paste, shows the notice, and the refused paste is sent as a `paste` signal with its size and without its text; the practice code editor accepts a paste and sends its size; an item is answered with the keyboard alone. The notice acknowledgement over the real backend is covered by the existing notice test in `assessment.spec.ts`, which now expects version 4. These specs show the page behavior in Chromium with a mocked server; they do not show behavior in other browsers, on a phone, with a real screen reader, or against a window manager that changes fullscreen on its own. The paste rule cannot see text that an on-screen keyboard inserts as typing.
|
||||
|
||||
## Assessment watermark tests
|
||||
|
||||
`backend/internal/domain/assessment_watermark_test.go` covers the mark: two attempts that were served one real generated variant get different marked statements whose canonical text and reference answer are equal; marking is deterministic and idempotent; the invisible run decodes to the visible code, survives a copy of two sentences, and a cut, padded, or mis-checked run is ignored; the accessible text holds the words only; the alignment of a stored statement with a leak reads only the phrases that it finds there (words around the statement, such as a quotation or a message, are ignored), the wording agreement of the attempt that wrote the text holds for every phrase group, other seeds disagree, a fragment yields the phrases of the fragment, an unrelated text aligns nothing, and another variant of the same family aligns for fewer characters than the leaked one; the pieces between the phrases are the same in every copy of a statement; the number guard keeps `at most` at the end of a sentence; codes parse the way an operator or OCR reads them. `usecase/assessment/watermark_test.go` checks that only root and corrective attempts are marked, that the stored snapshot is not changed, that the visible code equals the invisible one, and that a missing `Watermarker` leaves snapshots alone; `adapter/primary/http/v1/assessment_test.go` checks that every attempt response goes through the presenter and that a presenter failure is an error. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) checks over HTTP that a real attempt shows the code derived on the server and a marked prompt on creation, on a read, and on a replay, that a training run shows neither, that the response holds only the code, and that the stored statement has no mark. In the frontend, `features/assessment-watermark` has Vitest tests of the text split, of the accessible text of the rendered markup (everything in `aria-hidden` removed leaves exactly the words), and of the tile (code and UTC time, no `@`, hidden from assistive technology). `e2e/assessment-watermark.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): the tile is on the task screen with the code and the time and without the account e-mail, is faint and takes no click, an attempt without a code shows no tile, and the accessibility tree of the marked prompt holds the words and no format character while the document keeps them. These tests do not run a real screen reader, a braille display, or another browser, so they do not show how a reader speaks the text; they do not show how many attempts a leak can be told from either, because the wording channel gives about one bit per phrase group.
|
||||
|
||||
## Assessment capture hint and work session tests
|
||||
|
||||
Domain and usecase. `assessment_signal_review_test.go` has the band rules: capture hints, extra User-Agents, and every weak signal together stop at attention however large their counts, the extra agents reach review only beside a strong signal, and a policy without the capture thresholds ignores the hints. `assessment_signal_policy_test.go` checks that a version published before these fields decodes with them off and encodes back to the same document (so its content hash holds), that the demo policy was not edited, that the thresholds round-trip, and that out-of-range or inconsistent values are rejected. `assessment_signal_test.go` covers the two new event kinds and their refusal with a measurement. `assessment_work_lease_test.go` covers the hold: one page admitted, a second refused until release or expiry, a renewal that keeps the acquisition time, release only by the holder, and invalid leases. `usecase/assessment/work_session_test.go` runs the steps of the hold and the check of the answer and the session start against in-memory repositories: a second page, a page without the header, and a request after an expiry; a training run and a service without work sessions are never refused; the origin of a hold is recorded with the User-Agent digest only. `signal_review_test.go` checks that the origin mark keeps the User-Agent as a keyed digest, writes a new mark only on a change, and that the review counts the extra agents and capture hints and stops at attention. `keyring_test.go` checks the new digests are keyed, bound to the attempt, and separate from each other. The HTTP adapter tests check the mapping of the hold, the release, the refusal of a held attempt on the session start and the answer, the new event variants and their mismatches, and the User-Agent bound.
|
||||
|
||||
Over HTTP with PostgreSQL. `TestAssessmentWorkSessionOverHTTP` creates a real attempt and checks that the first page holds the session, that a second page, and a request without the header, are refused for the hold, the session start, and the answer with 409 and nothing is stored, that the refusal is not stored under the key (the holder reuses both keys), that another page's release changes nothing, that the holder's release frees the session at once, that a hold that stopped renewing ends by itself, that bad page identifiers answer 400 and a missing CSRF token 403, that only digests of the page and the User-Agent are stored (no table text holds a page identifier or a browser string), that the capture events are stored without a measurement and refused with one, and that the review job gives the band attention with the extra agents and capture hints counted. `TestAssessmentSignalNoticeOverHTTP` follows `CurrentSignalNoticeVersion`. The migration 50 constraints are exercised by these tests.
|
||||
|
||||
Frontend. Vitest covers the key rules (`capture-keys.test.ts`), the heuristic and its watcher with fake windows and timers (`devtools-heuristic.test.ts`), the collector (one event for a press and its release, no cancelling, no event without an item), the session wiring of the watcher, the work session controller (held, busy, lost at a renewal, a network gap, a release during a renewal, the renewal bounds, `work-session.test.ts`), the page identifier header of the answer command, and the notice version 4 text. `e2e/assessment-capture.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen and Cmd+Shift+4 are recorded as `screenshot_key` events with no key or image, the key event is not cancelled and the test goes on to an answer; a faked docked panel is recorded as `devtools_open`; a second tab opened on the attempt is refused with the explanation and shows no task, nothing is started in it, the first tab is undisturbed, and after the first tab leaves the second continues; `pagehide` releases the session; a tab that loses the session at a renewal stops and says so. These tests do not show behavior in other browsers or on a phone, whether the operating system hands a shortcut to the page, what a real screenshot looks like, or how often the heuristic is wrong on real windows; the mock server stands for the rules of the real one, which the HTTP test covers.
|
||||
|
||||
## Assessment leak trace tests
|
||||
|
||||
`backend/internal/usecase/assessment/leak_trace_test.go` runs the tracer against in-memory repositories with real watermarks: the leaked text of a variant, among other words, finds the right one of three attempts that were served the same statement (by the invisible mark); with the invisible characters removed, the visible code of the tile text finds the attempt, and the wording alone separates the attempts that were served the same statement and chose different phrases; the visible code tolerates one misread character and not two; unrelated text, a text that is too short, and a mark of no attempt are not found and say why; a statement that only one attempt holds is found by the variant and excluded when its wording contradicts the text; attempts that chose the same phrases, or a text with no phrase group, are ambiguous without naming one; a mark attached to another text is found and flagged; a mark and a visible code that name different attempts are ambiguous; another variant of the same family does not compete with the leaked one, and the leak of a deleted attempt is not attributed to the variant of its family that is left; a leak cut inside the statement is found, while other words where the statement continues are not; every search is audited with a keyed digest and no part of the text, the same text gives the same digest, and a failed audit fails the search; bad requests are refused without quoting the text. `domain/assessment_watermark_test.go` covers the alignment and the wording agreement (only the phrases aligned with the stored statement are read, a fragment, unrelated text, another variant aligning for fewer characters), `domain/assessment_leak_trace_test.go` the audit record, `usecase/identity/keyring_test.go` the keyed text digest, `config/identity_test.go` the secret reader, and `adapter/primary/cli/leaktrace/command_test.go` the argument rules, the file and standard input reading with its limit, the output (the outcome and fixed notes, never the text, an honest not found), safe error messages, and that the environment is not read before the arguments are valid. `TestAssessmentLeakTraceOverHTTP` (PostgreSQL) creates two real attempts over HTTP and checks that the marked prompt finds the first by its mark, the prompt without invisible characters finds the second by its statement, the text of a screenshot with the tile finds the first by its visible code and the tile time, unrelated and short text are not found, a search changes no attempt version or state and no review or result, every search is audited without the text, the audit refuses UPDATE, DELETE, and TRUNCATE and a found row without an attempt, the audit outlives a deleted attempt (which is then not found), and the command with the secret of the server finds the attempt while one with another secret does not read the mark. They do not run an OCR tool, so what the command does with the real recognition errors of a screenshot, and how well the wording separates attempts on a real bank, are not measured here.
|
||||
|
||||
## Internal notification tests
|
||||
|
||||
Unit tests (`make -C backend test`, `make -C frontend test`):
|
||||
|
||||
- `domain/notification_inbox_test.go`: an entry accepts only the allowlisted pairs of event type and source type (the synthetic event with the organization, `invitation.delivered` with the invitation), a new entry starts unread, and `MarkRead` keeps the first time.
|
||||
- `usecase/notification/inbox_test.go` with an in-memory repository and a fake unit of work: the list resolves each item against its current source and falls back to no content; a candidate cabinet refuses an employer, the organization cabinet refuses a candidate, an unknown or unverified account, and a revoked membership (which answers like an unknown organization, for the list and for the mark); a repository row outside the recipient scope is an internal error; an owner and a recruiter (and the other roles) read and mark only their own items of the organization, with the membership locked for the read; an unverified employer gets `ErrInboxEmailNotVerified`; a mark keeps the first time and cannot touch another recipient's item; content links reject an external URL, a protocol-relative URL, a query, a fragment, a backslash, an escape, a dot segment, and a long path; the synthetic resolver follows the recipient's standing and an unregistered source type is unavailable.
|
||||
- `usecase/notification/inbox_handler_test.go`: a repeated event stores one row; a broken schema version, aggregate, unknown field, missing organization, non-object payload, trailing data, and an event ID reused with other metadata are rejected for good; a deleted recipient is skipped; a store failure stays retryable; an unverified address still gets its row (the inbox reads no mail state); a recipient that vanished between the check and the insert is retried and then skipped, not rejected; the synthetic event is ignored while its switch is off; an `invitation.delivered` event with the same payload contract stores the invitation as its source.
|
||||
- `adapter/primary/http/v1/notifications_test.go` and `adapter/primary/http/notification_contract_test.go`: the mapping of content and fallback, the cursor bound to the account and the cabinet (a foreign or crossed cursor is a 400), the refusals, the conventions of the four operations, and closed schemas. `bootstrap/consumers_test.go` pins the two registered consumers.
|
||||
- Frontend: `features/notifications/` tests the link check, the retry of a mark once after a 403 (and no retry of a 401, 404, or 500), the labels, the wording of an item without content, the query keys and their removal by account, and the rendered list (read state as a word, a mark button only for unread items, no unsafe link, the empty state, the refusal of the other cabinet).
|
||||
|
||||
Integration tests (`make -C backend test-int`; PostgreSQL and Redis, no Kafka): `TestNotificationInboxOverHTTP` writes a synthetic event through the real outbox writer and delivers it through the consumer store with the real handler. One event delivered twice and once more by a renamed consumer stores one row. The same router then checks the candidate list, a foreign candidate, the wrong cabinet, a missing CSRF token and a foreign Origin, the mark and its repeat (the first time is kept), the persistence of the read state, the loss of content when the candidate hides the organization, paging with a cursor bound to the account, the employer cabinet with only its own items of the organization, a recruiter with its own items, a non-member, an item of another organization, and the 404 for the list and the mark after the membership is revoked. `TestSyntheticNotificationMigrationAllowlistAndGuardedRollback` and `TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows` check the allowlist of migration 00036, the refused rollback with a synthetic row, and the restored constraint. `TestNotificationInboxStoreNamesTheMissingReference` checks that a missing recipient and a missing organization are told apart. `TestPostgresMigrations` covers up and down to zero.
|
||||
|
||||
Browser test: `frontend/e2e/notifications.spec.ts` runs in `make -C deploy test-e2e-registration`, whose overlay sets `NOTIFICATION_SYNTHETIC_ENABLED=true`. The `company-fixture` (Go build tag `e2e`, bearer token, synthetic `@example.test` recipients only) appends a synthetic event to the real outbox, so the relay, Kafka, and the `notification_inbox` consumer deliver it; the test waits for the item. It then replays the event through the fixture, which must report that the real consumer had already applied it, and checks that the list still has one item. A candidate then opens the list, marks the item with the keyboard, reloads and sees the state kept, and a second candidate gets an empty list and a 404 for the same ID. After the organization is hidden the item stays without content. A second test reads the organization inbox as an owner, checks a non-member, revokes the membership through the fixture, and checks that the same ID is refused and that the page shows no content.
|
||||
|
||||
What these tests do not show: a real invitation event through Kafka and the relay (`TestOrganizationInvitationSendOverHTTP` delivers it through the handler storage only), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check).
|
||||
|
||||
## Demo seed tests
|
||||
|
||||
`backend/internal/usecase/demoseed/seeder_test.go` checks without a database that a reset is allowed only for a database without accounts or with synthetic accounts only, that the synthetic bundles pass the loader rules and are identical between builds (so a repeated import changes nothing), that the prepared answers have the intended correctness, and that the dataset has two employers on the synthetic domain, one self-service candidate, and a cohort of at least five prepared candidates. `backend/internal/adapter/primary/cli/demoseed/command_test.go` checks the argument parsing, that every subcommand refuses without `DEMO_MODE=isolated` before it reads the database settings, that a short password is refused without echoing it, that the seed output names the logins and the prepared attempts but never the password, that failures become safe messages, and that `check-reset` fails on any account outside the synthetic domain.
|
||||
|
||||
`TestDemoSeedCommand` in `backend/integration_test/demo_seed_test.go` uses `bootstrap(t, postgresService)` and runs the operator command against migrated databases that carry the startup policy:
|
||||
|
||||
- Without the isolated mode, also against an unreachable database, every subcommand refuses, and nothing is written.
|
||||
- A database with an ordinary account and no seed is refused by both the seed and the reset check; the account and the policy stay as they were.
|
||||
- The first seed creates nine confirmed synthetic accounts, two organizations, three memberships (the owner of Alpha is a recruiter of Beta), six prepared attempts with results, current synthetic categories, evidence, and published cards, the seed policy version, 28 published families, one opening, one attestation, and one training binding. A second seed by another operator creates nothing and prints the same inventory.
|
||||
- Every synthetic candidate stands at the onboarding step `candidate_assessment`, which a saved questionnaire leaves, and both employers stand at `employer_company`. A stand whose candidates were left at the consent step is repaired by one more run: it prints an `updated` line for each candidate on an earlier step, keeps a candidate on a later step, creates nothing, and keeps the inventory the same.
|
||||
- Every organization, profile name, and prepared profile carries its synthetic or prepared marker, and every category is an uncalibrated `synthetic_demo` category.
|
||||
- The owner of Alpha sees exactly the six prepared cards through the card listing that the search uses, and not the unpublished self-service candidate.
|
||||
- A perfect express run of the self-service candidate through the attempt operations draws three items from the training category, ends as `demonstration` with the Russian training summary, and adds no category and no evidence; the same candidate can then start the full test.
|
||||
- After an ordinary account registers on the seeded database, the reset check refuses and counts it, a repeated seed still creates nothing, and the account is unchanged.
|
||||
|
||||
`make -C deploy check-demo` (part of `make -C deploy check`) runs `deploy/scripts/demo.sh` against a recording stub of the docker CLI: every action refuses without `DEMO_MODE=isolated`, with a project name that equals `APP_PROJECT` or lacks `demo`, with an invalid actor, or without the env file, before any Docker command; a project volume without the demo label is refused before any Compose command; a refused reset check stops the reset before `down`; a reset addresses only the demo project and seeds again; `down` keeps the volumes; a release manifest that cannot be restored stops `seed` and `reset` before any Compose command, and `down` ignores it. With the docker CLI it also renders the overlay: only the frontend is published, on loopback; the seed container has only the default network, a read-only root, and the explicit profile; every volume carries the demo label; the demo backend enables synthetic categories; the release overlay names the seed image `lincodex.invalid/demo-seed:<tag>` with `pull_policy: never`; and the backend images do not contain the command.
|
||||
|
||||
The tests do not run the Make targets against a real stack. A manual check on a throwaway project: `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` twice with identical inventories, a sign-in of the prepared accounts with mail disabled, an express run and the start of the full test, then `demo-reset` refused after a visitor registered. Remove the project afterwards with `docker compose -p lincodex-demo-check down --volumes` and the same variables. The tests do not validate the content of the synthetic bank or any grade, and the browser route of the jury is not covered here. Integration tests need Docker.
|
||||
|
||||
## Code runner tests
|
||||
|
||||
| Command | What it checks |
|
||||
| --- | --- |
|
||||
| make -C runner test | Unit tests with the race detector: checkers, configuration, judge outcomes on a scripted sandbox, idempotency and busy handling of the run manager, the HTTP API (token, 202/200/422/503, 400, 413, 404), and that logs carry no source, input, or token |
|
||||
| make -C runner lint | golangci-lint for Linux, including the isolation tests |
|
||||
| make -C runner check-generated | The generated ogen server matches the bundle |
|
||||
| make -C runner test-sandbox | Reference solutions and isolation tests in a privileged dev container with real nsjail and cgroup v2 |
|
||||
| make -C runner test-a16 | The A16 suite only, with a report in `runner/.reports/`; `A16_ENV` passes `RUNNER_*` variables |
|
||||
| make -C runner a16-bundle | A bundle of the A16 suite for the runner host |
|
||||
| make -C deploy check-runner-dev | Dev switches stay out of production files |
|
||||
| make -C deploy check-runner-vm | The runner VM script keeps the VM boundary: a VM with only its profile, no shared device, privileged or raw setting, sudo, or dev switch, the sandbox and budget settings of the unit, a static address without a route, and secrets outside the repository |
|
||||
| make -C deploy runner-vm-check | On the app host: the live runner VM, see [DEPLOY.md](DEPLOY.md#steps-of-the-vm-script) |
|
||||
| make -C deploy runner-vm-a16 | On the app host: the A16 suite in the runner VM with the service's sandbox settings |
|
||||
|
||||
First, `test-sandbox` runs the reference solutions of `runner/testdata/judge/manifest.json` on three tasks with one public and three hidden groups: correct and incorrect Python and Go solutions get the expected outcome of every group (`exact` and `tokens`; `numbers` on fractional answers with an absolute and a relative tolerance; `custom` with a Python and a Go checker in nsjail); Go code with a compile error gives `compile_error` with a `main.go:` message and no test runs. The test also checks that a group stops at its first failed test, hidden tests carry no diagnostic, and the run directories and cgroups are removed.
|
||||
|
||||
Then `test-sandbox` runs the A16 suite (see below).
|
||||
|
||||
### A16 hostile-program suite
|
||||
|
||||
`make -C runner test-a16` builds the image and runs only the A16 suite in a privileged dev container without network and without an init; a JSON report is written to `runner/.reports/` (ignored by Git). The cases and expectations are in `runner/testdata/hostile/manifest.json`, with programs in Python and in Go:
|
||||
|
||||
| Category | Attempts | Expectation |
|
||||
| --- | --- | --- |
|
||||
| network | TCP, UDP, listen, DNS, raw ICMP, AF_PACKET, and netlink sockets | all refused; the probe prints `blocked` |
|
||||
| files_and_secrets | `/etc/passwd`, `/etc/shadow`, `/run/secrets` and the API token, runner files, `/proc`, `/sys`, `/dev/mem`, environment variables with `RUNNER`, `TOKEN`, or `SECRET`, writes to the root, the source, and `/out` | nothing is visible or writable except `/tmp` |
|
||||
| privileges | setuid, setgid, chown to root, raising an rlimit | refused; uid and gid are not 0 |
|
||||
| escape | ptrace, mounting a fresh procfs, unsharing a user namespace | the process is killed by seccomp (SIGSYS, `runtime_error`) |
|
||||
| processes | fork bomb, and a thread bomb in Go (256 goroutines blocked in system calls, so the stacks stay far below the memory limit) | the cgroup process limit (`runtime_error`, limit `processes`) |
|
||||
| memory | unbounded allocation, and in Go unbounded goroutines parked on a channel (no new threads) | the cgroup memory limit (`memory_limit_exceeded`) |
|
||||
| disk | one large file and filling `/tmp` | refused by the file size limit and the tmpfs size |
|
||||
| output | endless output | the output limit (`output_limit_exceeded`) |
|
||||
| timeout | a busy loop that ignores signals, a sleep, a detached daemon in its own session | the CPU limit, the wall-clock limit; the daemon dies with the PID namespace |
|
||||
|
||||
Baseline cases check that a correct solution is accepted and a syntax error gives `compile_error`. After every case the test checks that the run directory is empty, the run cgroups are gone, no live uid 99999 process is left, and no new unreaped (zombie) process appeared; the suite runs without an init, so this confirms that nsjail reaps every stopped process.
|
||||
|
||||
The report records the runner version (`git describe`), the kernel (`uname`), the cgroup controllers, the nsjail package version and SHA-256, the isolation profile (nsjail arguments of a sample test run, the seccomp policy, cgroup and rlimit limits), the result of every case, and the verdict. Any failed case gives the verdict `fail` and `practice_may_be_enabled: false`: practice must not be enabled until the suite passes on the runner host.
|
||||
|
||||
Checking the suite itself: `TestA16WeakenedProcessLimitIsDetected` raises the process limit to 4096 in a test copy of the configuration and requires the processes cases to fail. The same by hand: `make -C runner test-a16 A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096"` exits with an error and a `fail` report on exactly the three processes cases.
|
||||
|
||||
On the runner host the suite runs from a bundle: `make -C runner a16-bundle` (`A16_GOARCH=amd64` by default) builds `runner/bin/a16-bundle.tar.gz` with the test binary, the fixtures, and `run-a16.sh`; on the VM it is unpacked and started with `sudo sh run-a16.sh [report.json]` and the same `RUNNER_*` variables as the service. The script does not use the network and writes only the report and the work directory. On the production VM, `make -C deploy runner-vm-a16` does this in a transient systemd unit with the sandbox settings of the service; the results of 2026-10-11 (20 of 20 runs pass with exit status 0) are in [DEPLOY.md](DEPLOY.md#verification-on-the-app-host).
|
||||
|
||||
What the tests do not prove: isolation in the production VM until the suite has passed there; protection against kernel, nsjail, or cgroup vulnerabilities; the absence of side channels (timing, CPU caches); or behavior under load.
|
||||
|
||||
## Code practice tests
|
||||
|
||||
`TestAssessmentPracticeSubmissionStorage` in `backend/integration_test/assessment_practice_http_test.go` uses `bootstrap(t, postgresService, redisService)`, an isolated migrated database, the real router, the practice usecase, and the PostgreSQL repository. No flow serves practice items yet, so the test moves a real attempt to `practice_pending` and creates its main and additional practices directly; the synthetic task marks every hidden test text. The sequential cases are:
|
||||
|
||||
- A debug run answers 202 with `Cache-Control: no-store`, is stored with exactly one queued job, and a repeat with the same key and body returns the same run without a new row; the same key with another body answers 422. Another candidate, another attempt, and an unknown run read as 404.
|
||||
- Refusals store nothing: a practice of another candidate (404), the additional practice while the attempt is at the main one (409), and a source over the bound of the task (400).
|
||||
- A stored result that also holds a hidden group is shown with the public tests only; the response has only the contract fields and no hidden text, source, or test text.
|
||||
- A final solution marks the practice `pending` and is stored with one job; a replay returns it, the same solution under a new key stores nothing, another solution conflicts, and a reused key with another body is refused. The database refuses to replace the source or the language of the stored solution, to delete it, and to write a second result. After a sandbox failure the practice accepts another solution, and the first one stays as it was.
|
||||
- With the runner disabled a run is refused as unavailable and nothing is stored. At the end every stored submission has exactly one job.
|
||||
|
||||
`backend/internal/usecase/practice/request_test.go` checks that the runner request of a debug run holds only the public examples and the candidate's tests, and that of a final solution exactly the three hidden groups.
|
||||
|
||||
`TestAssessmentPracticeQueue` in `backend/integration_test/assessment_practice_queue_test.go` uses the same harness with the Redis limiter (two debug runs a minute), the real PostgreSQL job store, executor, and worker, a fake runner that is idempotent by run key and counts the runs it starts, and a test clock for leases and waits. Its sequential cases are:
|
||||
|
||||
- Twelve candidates start a debug run at the same moment: eleven are accepted and exactly one answers 503 `service_unavailable` with `Retry-After` and stores nothing. While the runner holds the run, the jobs are one `running` and ten `queued`, and a second worker claims nothing. After the runner finishes, all eleven are `finished`, each submission ran once, and eleven results are stored.
|
||||
- With eleven runs queued, a final solution is answered with the practice `failed` and `sandbox_busy`: no submission is stored and the attempt version does not move. After the queue drains, the same solution is accepted and finished.
|
||||
- A busy runner puts the job back without a counted attempt and the job waits for the runner's `Retry-After`; an infrastructure failure counts one attempt, raises the generation, and keeps the practice `pending` without a result; after the backoff the next try finishes it.
|
||||
- A worker is killed mid-job (its pool closed, so it cannot give the job back): another worker claims nothing while the lease lives, takes the job over after it expires, and finishes it on the same run key, with one run on the runner, one counted takeover, and one result; a late completion by the killed worker is refused and leaves the result unchanged.
|
||||
- A second debug run while the first is unfinished, and a third within a minute, answer 429 `rate_limited` with `Retry-After` and store nothing.
|
||||
|
||||
`TestAssessmentPracticeRunnerProtocol` in `backend/integration_test/assessment_practice_runner_test.go` uses the same harness with the real queue worker and the real TLS 1.3 client of the code runner (`adapter/secondary/code_runner`), against a local fixture of the runner protocol (`practice_runner_fixture_test.go`: an `httptest` TLS server with the bearer token, PUT and GET of `/v1/runs/{id}`, one run per run ID, and 422 for another payload). The fixture does not run code: it recognizes one Python and one Go program that print the sum of two integers and compares their output with the expected output of each test, and a failed public test carries the program output as its diagnostic. The production runner VM is not called. Sequential cases:
|
||||
|
||||
- A Python and a Go debug run of two candidates finish through the API. Each candidate's own test expects a wrong sum, so the diagnostic shows what that program printed: `got 42` for the Python submission and `got 123` for the Go one, never the other's. The job keeps the `runner_run_id` of the run, and the fixture started that run from the source of that submission. The wire request has the fields `groups`, `language`, `limits`, and `source` only, the groups `public` and `custom` and no hidden group, headers limited to transport and the service token, a version 8 run ID that is none of the user, attempt, practice, or submission IDs, and none of those IDs, the email, or the session cookie in the path, headers, or body. Another candidate reads the run as 404.
|
||||
- A final solution whose response is cut after the runner accepted the run (the connection is dropped) is retried after the backoff on the same run key: the runner holds one run, the job is `finished` with one counted attempt and generation 0, exactly one final result is stored, and its `runner_run_id` is that run. The wire request of a final solution has the groups `hidden-1` to `hidden-3` only.
|
||||
- A debug run whose answer outlasts the request timeout ends the try as a retry, the run reads as `queued`, and the repeat joins the run the runner already holds.
|
||||
- A worker that died mid-run (its pool is closed) is replaced by a worker with a new client built from the same settings after the lease expires. The new client derives the same run ID, so the runner still holds one run, one takeover is counted, and one result and one `runner_run_id` are stored.
|
||||
- With the runner stopped, a debug run stays `queued` while tries remain, then reads as `failed` with `sandbox_error`, no result, no `runner_run_id`, and a finished time. The attempt state and version, the result count, and the confirmed categories of the candidate are the same before and after, and the practice is still `not_started`. A new debug run on the same practice is accepted and finishes once a working runner is back. A final solution with the stopped runner makes the practice `failed` with `sandbox_error` and no result, leaves the candidate state unchanged, and is accepted again and finished by a working runner. In the end no `runner_run_id` belongs to two jobs.
|
||||
|
||||
The fixture proves the protocol path and the storage and retry rules; it does not prove that a real sandbox compiles or runs Python and Go or the timing of a real runner.
|
||||
|
||||
Unit tests: `usecase/practice/execute_test.go` checks with fakes that an unreachable runner keeps the run key, an infrastructure failure and a reused key raise the generation, an invalid request and the last attempt fail without a stored result, a lost run is submitted again, a shutdown gives the job back uncounted, and a finished run without a valid run ID is retried and stores no result while a valid one is stored with the result. `config/practice_test.go` checks the defaults and refused values of the practice settings. The tests do not run code in a sandbox and do not prove the timing of a real runner.
|
||||
|
||||
## Semantic matching tests
|
||||
|
||||
- ML service (`make -C ml test`, no model, no network): `tests/test_embeddings.py` checks the `POST /v1/embeddings` contract on the deterministic hash encoder: response order, normalization, equal vectors for two equal requests, micro-batches by length, 503 `service_unavailable` before readiness and ready only after the warm-up, 400 for too many texts, a length, and unknown fields, 413 for a body over the limit (with Content-Length and streamed), and no request text in the logs; `tests/test_model_files.py` checks the lock file (only safetensors and configs, a full revision, no code or pickle) and the size and SHA-256 verification.
|
||||
- Ensemble and ML token (`make -C ml test`): `tests/test_ensemble_and_auth.py` checks the choice of one of several loaded models by `model` and 400 for another one, readiness only after every model, a refusal of two encoders with one id, 503 and a readiness cool-down after a lack of device memory with recovery, a retried load on a lack of memory and the exit through `ML_EXIT_ON_LOAD_FAILURE` on another failure, 401 without a token, with a wrong token, with the Basic scheme, and on `/metrics`, open `/healthz` and `/readyz`, loopback only without a token, a refusal before the body is read, no token in logs or settings errors, and the entry point refusing a non-loopback address without a token. Checked by hand on CUDA: a load without enough memory is retried while the process stays alive and not ready; a request over the allocator limit answers 503, `/readyz` answers 503 for 30 seconds, and then the service answers 200 again.
|
||||
- The real models: `make -C ml model-fetch` and `make -C ml test-model` (marker `slow`, skipped by the ordinary checks) compare the Giga-480M and Qwen3-Embedding-0.6B vectors with the study's vectors for four texts (difference below 1e-4) and a repeated encode (the same vector); `ML_TEST_DEVICE=cuda` runs them on the GPU in float32. On 2026-10-11 both models passed on CPU and on CUDA on the GPU host. This checks that the recipe is reproduced, not model quality; the float16 against float32 comparison and the fit of the ensemble policy are a separate evaluation on the study's DEV data (see [DEPLOY.md](DEPLOY.md#ml-service-on-a-gpu-host)).
|
||||
- Backend unit: need and card views (`domain/semantic_test.go`: the exact study text, confirmed values only, metadata only for a verified repository), the float32 codec and cosine, the calibration (interpolation, steps, a monotone demo table), the thresholds, validation and the round trip of the V5 policy document; projects and GitHub addresses (`domain/candidate_project_test.go`: accepted and rejected addresses, normalization, limits, a repeated repository, no address in the card); explanation selection (`usecase/matching/semantic_test.go`: order, limit, a stale title, a hidden stack or hidden projects explain nothing, the `projects` field record); Fit with a known and the neutral Sem; the ML client (batches of 32, response checks, the circuit breaker, no text in errors); GitHub (`adapter/secondary/github`: httptest, public repositories only, the token only when set, ETag and 304, 403/429 limits with the wait, server errors, a refused redirect to another origin, size caps, README text without markup or HTML); jobs and the trigger (keys and payloads without the repository address, disabled features schedule nothing).
|
||||
- Integration (Testcontainers): `TestSemanticMatchingOverHTTP` runs over HTTP, PostgreSQL, and the real job worker with a fake ML service (httptest on the contract) and a fake GitHub: a profile save schedules jobs without the address in their keys, the repository check and the card vectors, the neutral Sem and flag before the need vectors, then the candidate with the close project first, the explanation names the project and `repository_verified`, and neither the response nor the card carries the repository address or owner; equal responses of two searches; the access history with the `projects` field; a repeated backfill with the same label schedules nothing twice and calls ML for no unchanged text; unpublishing `projects` removes the project vectors and the title from the explanation; an unavailable ML keeps the job in retry while the search answers; the refresh limit (429, then 202).
|
||||
- Ensemble and token in the backend: unit tests `domain/policy_matching_ensemble_test.go` (the ensemble policy validates, Giga explains with its thresholds, the fused score is 0 at the means, the calibration is monotone and clipped, the V6 document round trip), `usecase/policy` (the ensemble published on top of V5, a repeat publishes nothing, the single-model command leaves the ensemble alone), `cli/policypublish` (the `semantic-ensemble` track), `adapter/secondary/ml` (the bearer token on every request, 401 as unavailability without the token text, no client without a token), `config` (the token is required while matching is enabled, short and spaced tokens are refused, formatted settings hide the tokens). In `TestSemanticMatchingOverHTTP` the fake ML requires the token and serves both models; after the ensemble publication and before the backfill every entry has the neutral `Sem`, and the backfill adds Qwen3 `whole` vectors for the six cards and the need without re-encoding Giga and without Qwen3 item vectors, after which every entry has a known `Sem`.
|
||||
- Not checked: ranking quality and explanation precision on real data, latency on the production server, the ML image build on this machine, and a stand with the model. Tests never call the real GitHub.
|
||||
|
||||
## Future software validation
|
||||
|
||||
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
|
||||
|
||||
Isolate test data by database/schema or run scenarios with a sequential reset. Do not run parallel cases against shared truncation. Reuse the bootstrap environment within a parent test; independent tests create their own environments. Integration CI must not silently skip tests when its container runtime is unavailable.
|
||||
|
||||
Validate contract changes with bundle, lint, codegen for every Go, TypeScript, and Python consumer, and generated drift, including new untracked files. Frontend component tests do not replace browser tests of the complete flow. After product implementation, extend the Playwright suite with both roles and a synthetic candidate without FSP history.
|
||||
|
||||
Critical future checks:
|
||||
|
||||
- Before offer acceptance, another company sees no contacts through API, search, PDF, errors, or ML explanations.
|
||||
- A candidate cannot access another user's invitations, files, jobs, or attempts; a company cannot access another company's needs or search runs.
|
||||
- Assessment failure does not lower grade; the first lower-level retry is allowed; concurrent requests cannot bypass cooldown.
|
||||
- Repeated submission or acceptance is idempotent; concurrent status transitions are serialized.
|
||||
- The manual path works with ML off; expired worker leases recover; stale results do not overwrite a newer profile.
|
||||
- Missing FSP history differs from an integration error and does not exclude the candidate.
|
||||
- Search refinement preserves an earlier snapshot; a withdrawn profile disappears from it.
|
||||
|
||||
## Future quality evaluation
|
||||
|
||||
Evaluate ranking separately from functional tests. Initial plan: 60-100 synthetic candidates, 8-12 needs, two independent labelers, disagreement review, and a holdout split by need. Near-duplicate profiles must not appear in both tuning and holdout.
|
||||
|
||||
Compare keyword search, verified skills, and ML. Measure Precision@5, nDCG@5, hard-filter violations, category coverage, and the share of relevant results without FSP history. Define the denominator before the run when fewer than five candidates qualify and report result-set size. Synthetic data does not prove quality for the real market.
|
||||
|
||||
Assessment evaluation needs a human pilot and independent expert skill ratings. Compare equivalent forms, vary their order, and measure grade agreement, score spread, task-level decisions, and group separation. Synthetic answers help debug a rubric; they do not replace a pilot.
|
||||
|
||||
ML evaluation records a fixed document set and field labels, extraction precision, invented facts, recommendation usefulness, schema-valid rate, latency, and failures. Record model, prompt/schema version, parameters, and date. Compare against a simple baseline and use lawfully handled de-identified documents.
|
||||
|
||||
Proposed targets are 30 concurrent users, p95 profile reads under 500 ms, and baseline search under one second on demo data excluding external network time. These are future acceptance criteria; no results are available. Set a separate ML latency budget.
|
||||
An old result does not verify a new commit. Health checks do not prove business flows, synthetic categories do not establish grade validity, and a replaced dependency does not prove the real service works.
|
||||
+103
-1283
File diff suppressed because it is too large.
Load diff
@@ -1,47 +0,0 @@
|
||||
# Квоты компании
|
||||
|
||||
Резервирование квот компании реализовано в домене, usecase `companyquota` и адаптере PostgreSQL. Для резервирования приглашений и просмотров карточек кандидатов используется порт, связанный с транзакцией. Приглашение тратит одно место недельной квоты при отправке (`SendOrganizationInvitation`): черновик квоту не тратит, а повтор отправки того же приглашения не тратит второе место. Уход приглашения из ожидания ответа (отказ, истечение, принятие) освобождает место в пределе ожидающих приглашений на потребность, но не возвращает недельную квоту; см. [Предел ожидающих, пауза и истечение](ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение).
|
||||
|
||||
## Политика и доверенный уровень компании
|
||||
|
||||
Каждая операция один раз получает снимок часов приложения в UTC и читает действующую версию `ProductPolicyKey`. Лимиты берутся из этой версии политики. Подключенная демо-политика сейчас включает для E0 10 приглашений за скользящие 7 дней и 50 уникальных просмотров карточек кандидатов за скользящие 24 часа. Для E1 заданы 40 приглашений за 7 дней и 150 уникальных просмотров за 24 часа.
|
||||
|
||||
Для E2 заданы лимиты 100 приглашений и 400 уникальных просмотров, но в подключенной демо-политике этот уровень выключен. E2 можно использовать только если действующая политика включает его, а загруженная из хранилища компания имеет соответствующий подтвержденный уровень и основание. Для E3 квотного уровня нет, поэтому операция запрещается. Вызывающий код не может выбрать или повысить уровень.
|
||||
|
||||
Снимок квоты содержит версию политики, сохраненные уровень и основание проверки компании, а также время изменения проверки. Перед записью адаптер PostgreSQL блокирует компанию и повторно проверяет эти значения и действующую версию политики. Если данные изменились, он возвращает `outbound.ErrCompanyQuotaSnapshotChanged` и не записывает использование. Вызывающий код должен перечитать политику и компанию, затем повторить всю транзакцию.
|
||||
|
||||
## Резервирование и порядок транзакции
|
||||
|
||||
Вызывайте `companyquota.Service.ReserveInvitation` или `ReserveCardView`, передавая репозитории текущего `outbound.UnitOfWork`. Репозиторий из `UnitOfWork.CompanyQuotas()` привязан к транзакции и не должен сохраняться после нее. Резервирование квоты и связанное с ним бизнес-изменение выполняются в одной транзакции, чтобы откат отменял обе записи. Сервис создается с часами приложения и один раз читает действующую политику на операцию.
|
||||
|
||||
Проверка доступа к компании остается ответственностью вызывающего кода. В той же транзакции нужно повторно проверить активное членство и права владельца. Писатели соблюдают такой порядок блокировок: компания, для компании на E0 - ее холдинг (см. [Пул холдинга](#пул-холдинга)), активное членство, запись приглашения или видимости, затем использование квоты. Адаптер квот первым блокирует строку компании, а для компании на E0 сразу после нее - строку холдинга; вызывающий код может повторно заблокировать эти строки в этой транзакции. Не меняйте этот порядок на обратный.
|
||||
|
||||
Блокировка компании сериализует параллельные резервирования одной компании, а блокировка холдинга сериализует общий пул E0. Пока они удерживаются, адаптер проверяет существующую запись, считает активное окно и добавляет или обновляет использование. Решение либо разрешает операцию, либо запрещает ее; повторное использование означает разрешение. При отказе запись использования не создается, а `RetryAt` содержит ближайший момент освобождения места по истечении активной записи.
|
||||
|
||||
## Окна и повторы
|
||||
|
||||
Приглашение определяется парой `(organization_id, invitation_id)`. Повтор с тем же ID разрешается как уже учтенный, даже если ключ идемпотентности запроса другой или скользящее окно уже прошло. Запись использования остается на срок жизни компании, поэтому удаление приглашения в будущем не вернет квоту.
|
||||
|
||||
Просмотр карточки определяется парой `(organization_id, candidate_id)`. Повторный просмотр того же кандидата в активном окне не расходует еще один слот уникального просмотра. Время `last_seen_at` обновляется монотонно: часы приложения, переведенные назад, не уменьшают сохраненное время.
|
||||
|
||||
Для активного окна используется строгое сравнение с границей. Запись ровно в момент `now - window` уже истекла. Использование приглашений считается за скользящие 7 дней, просмотры карточек - за скользящие 24 часа. Лимиты общие для запросов и пользователей компании; исключение - компания на E0, которая делит свои лимиты с остальными E0-компаниями своего холдинга (см. [Пул холдинга](#пул-холдинга)).
|
||||
|
||||
Истекшие записи просмотров удаляются партиями максимум по 100 только после успешного разрешенного резервирования. Истечение окна логическое; очистка не обещает удаление в точно заданный момент. При удалении аккаунта кандидата его запись просмотра удаляется каскадно. При удалении компании удаляются обе таблицы квот. Для использования приглашений нет внешнего ключа на приглашение, поэтому будущее удаление приглашения не сможет удалить ключ идемпотентности.
|
||||
|
||||
## Пул холдинга
|
||||
|
||||
Холдинг объединяет компании, созданные одним аккаунтом-основателем; его хранит таблица `holdings`, миграция `00041_create_holdings.sql`. `CreateWithOwner` сохраняет каждую новую компанию в холдинге аккаунта-владельца в той же транзакции. Холдинг аккаунта создается с его первой компанией, а параллельные создания одного аккаунта дают один холдинг: вставка игнорирует уже существующий ключ основателя, а затем транзакция читает сохраненный холдинг. Холдинг не несет ни профиля, ни права; его единственный эффект - общий пул E0.
|
||||
|
||||
Лимиты E0 (в подключенной демо-политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа) общие для E0-компаний одного холдинга. Резервирование E0 считает строки использования всех компаний холдинга, чей уровень проверки в момент подсчета равен E0. Каждая строка использования остается за компанией, которая ее потребила, а использование компании, которая уже не E0, выходит из общего пула. Компания на E1 и выше считает только свое использование и имеет собственный пул, поэтому ее использование не входит в пул E0.
|
||||
|
||||
Идемпотентность остается на уровне компании. Тот же ID приглашения или повторный просмотр одного кандидата той же компанией внутри окна не списываются второй раз. Один кандидат, просмотренный двумя компаниями одного холдинга, - два списания общего пула.
|
||||
|
||||
Блокировки: для компании на E0 `CompanyQuotaRepository.LockOrganization` и каждое резервирование берут строку холдинга с `FOR NO KEY UPDATE` сразу после строки компании. Поэтому резервирования одного пула идут друг за другом, а второе считает использование, которое первое уже зафиксировало: подсчет начинается после блокировки холдинга. Каждый писатель берет блокировку компании раньше блокировки холдинга, а ни один код не берет блокировку компании, удерживая блокировку холдинга, поэтому блокировка холдинга не добавляет цикл в документированный порядок. Цена: поиски E0, чтения карточек и черновики или отправки приглашений одного холдинга ждут друг друга, пока открыты их транзакции; поиск держит блокировку на всю транзакцию ранжирования.
|
||||
|
||||
Миграция дает каждому основателю один холдинг: основатель компании - аккаунт ее самого раннего членства, то есть владельца, созданного вместе с компанией, а холдинг датируется первой компанией. Откат отказывает, пока холдинг объединяет несколько компаний, потому что схема без холдингов не сохранила бы их общий пул E0. Слияние холдингов разных владельцев не входит в объем.
|
||||
|
||||
## Проверки
|
||||
|
||||
`TestHoldings` в `backend/integration_test/holding_test.go` проверяет общий пул E0 двух компаний одного аккаунта при отдельном пуле компании на E1, отдельный холдинг второго аккаунта, выход использования из пула при повышении компании, параллельные резервирования двух компаний, которые никогда не превышают общий лимит, параллельные создания, заканчивающиеся одним холдингом, и отказ создания с неизвестным основателем. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` в `backend/integration_test/holding_migration_test.go` проверяет заполнение и защищенный откат миграции.
|
||||
|
||||
`TestCompanyQuota` в `backend/integration_test/company_quota_test.go` проверяет настоящий адаптер PostgreSQL на изолированной базе. Тест покрывает параллельные резервирования E0, границы E0 и E1, точные границы окон и `RetryAt`, повтор того же ID приглашения, повторный просмотр в рамках компании, монотонное обновление, откат, изменение снимка политики или компании, разрешенное резервирование при включенной E2 и сохраненной проверке компании, отказ для поддельного снимка E2 при сохраненном E0, отказ для выключенной E2 и E3, а также очистку после удаления кандидата. Проверки доставки приглашения нет, поскольку этот процесс пока не реализован.
|
||||
-1049
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,276 @@
|
||||
# Запуск и развертывание
|
||||
|
||||
Команды выполняются из корня репозитория. Нужны Docker с Compose, GNU make, Python 3 и OpenSSL. Для Go-команд оператора нужен toolchain из `backend/go.mod`; они читают экспортированные переменные окружения, а не `.env` автоматически. Настройки описаны в [.env.example](../../.env.example); значения по умолчанию и проброс в контейнеры - в [deploy/Makefile](../../deploy/Makefile) и [Compose](../../deploy/docker/).
|
||||
|
||||
## Запуск MVP: быстрый старт
|
||||
|
||||
Создайте `.env`, если его еще нет: скопируйте `.env.example`, замените `replace-this-*` и заполните `IDENTITY_KEY_SECRET` случайным секретом (`openssl rand -base64 48`). Пароль PostgreSQL входит в URL подключения, поэтому используйте URL-safe символы, например hex. Файл хранит секреты и не коммитится.
|
||||
|
||||
```sh
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl --fail http://localhost:8080/api/v1/healthz
|
||||
```
|
||||
|
||||
`config` проверяет примеры настроек, а `up` читает настоящий `.env`. Основной проект `app` запускает frontend Nginx, Go backend, PostgreSQL, Redis, SeaweedFS и Kafka. Backend применяет миграции при старте. Чистая база не содержит банка заданий и подготовленных аккаунтов: для показа продукта используйте [демонстрационный стенд](#изолированный-демонстрационный-стенд).
|
||||
|
||||
| Контур | Запуск | Адрес по умолчанию |
|
||||
| --- | --- | --- |
|
||||
| Основной | `make -C deploy up` | `http://localhost:8080` |
|
||||
| Синтетическая демонстрация | `make -C deploy demo-seed DEMO_MODE=isolated` | `http://localhost:8090` |
|
||||
| ML, после core | `make -C deploy ml-up` | `127.0.0.1:8000` |
|
||||
| Мониторинг, после core | `make -C deploy monitoring-up` | Grafana: `127.0.0.1:3000` |
|
||||
| Dev-исполнитель кода | `make -C deploy runner-dev-up` | `127.0.0.1:8070` |
|
||||
|
||||
ML, мониторинг, исполнитель и labd не запускаются с основным стеком. Имя проекта передавайте одинаково всем целям: например, `APP_PROJECT=my-app` для `up`, `logs` и `down`. Make не берет имя проекта из `.env`.
|
||||
|
||||
## Core сервис
|
||||
|
||||
`make -C deploy logs` показывает журналы. `make -C deploy down` сохраняет именованные тома; остановите мониторинг перед core. PostgreSQL, SeaweedFS и Kafka хранят данные в томах, Redis работает как ограниченный по памяти кеш без persistence. Удаление томов уничтожает данные. Один узел Compose не обеспечивает HA или внешнюю резервную копию.
|
||||
|
||||
### Публичный периметр и адрес клиента
|
||||
|
||||
Единственная HTTP-точка входа - frontend Nginx: SPA и `/api/v1/` на одном origin. Открывайте ровно `APP_PUBLIC_URL`; небезопасные запросы проверяют Origin и, для сессии, CSRF-токен. Для локального HTTP используйте `localhost`, для публичного имени - HTTPS: cookie сессии имеет флаг `Secure`.
|
||||
|
||||
Оставляйте `APP_HTTP_BIND=127.0.0.1` локально или задавайте приватный адрес туннеля. Не публикуйте backend, `/metrics`, базы, брокер и хранилище. Публикация порта Docker может обходить правила ufw. `TRUSTED_PROXY_CIDRS` должен доверять только frontend Nginx; при изменении `APP_SUBNET` и `APP_FRONTEND_IP` согласуйте адреса прокси и ACL.
|
||||
|
||||
### Relay outbox
|
||||
|
||||
Backend публикует outbox в Kafka и запускает обработчики событий и задания по сроку в одном процессе. Настройки `RELAY_*`, `CONSUMER_*` и `JOBS_*` определены в [backend/config](../../backend/config/). Добавление переменной в `.env` действует на контейнер только при ее явном пробросе в Compose. Сохраняйте запас `stop_grace_period` при увеличении тайм-аутов завершения.
|
||||
|
||||
### Обработчики событий
|
||||
|
||||
В Grafana следите за отставанием outbox, ошибками обработчиков и наступившими заданиями. Dead letters смотрите в базе, Kafka lag - через CLI брокера. Доставка допускает повторы; обработчики используют дедупликацию. Смена `CONSUMER_GROUP_PREFIX` создает новые группы, читающие сохранившиеся события сначала.
|
||||
|
||||
#### Dead letters и повторный запуск
|
||||
|
||||
После устранения причины найдите запись в `consumer_dead_letters`. Для известного `event_id` можно повторно опубликовать сохраненную строку outbox, сбросив только ее `published_at`; успешные обработчики распознают дубликат. `invalid_record` так не исправляется. Перед ручной перемоткой Kafka остановите всех участников нужной группы. Подтверждение обработки находится в `consumer_processed_events`; payload и персональные данные не копируйте в журналы инцидентов.
|
||||
|
||||
### Задания по сроку
|
||||
|
||||
Состояния и ошибки хранятся в `scheduled_jobs`. После исправления причины повторяйте только конкретное задание с учетом его обработчика; не сбрасывайте всю очередь. Синхронизируйте часы backend через NTP: сроки и аренды сравниваются по часам приложения. Практика имеет отдельную очередь, описанную ниже.
|
||||
|
||||
## Почта
|
||||
|
||||
| Режим | Что требуется |
|
||||
| --- | --- |
|
||||
| `EMAIL_PROVIDER=disabled` | Ничего не отправляет; новый аккаунт останется неподтвержденным |
|
||||
| `EMAIL_PROVIDER=resend` | `RESEND_API_KEY`, `EMAIL_FROM` на подтвержденном домене, правильный `APP_PUBLIC_URL` |
|
||||
| `EMAIL_PROVIDER=smtp` | Конфигурация предусмотрена, транспорт пока не реализован: backend откажется стартовать |
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Resend отправляет подтверждение адреса и поддержанные продуктовые уведомления через outbox. Ошибка транспорта не означает успешную отправку. Тест `make -C deploy test-e2e-registration` использует локальный Resend-совместимый inbox, а не настоящий аккаунт провайдера.
|
||||
|
||||
### Квоты почты
|
||||
|
||||
`EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` ограничивают получателей по UTC: по умолчанию 100 и 3000. `EMAIL_SERVICE_RESERVE_*` оставляют часть квоты для служебной почты. `EMAIL_ACCOUNT` обозначает реальный аккаунт поставщика; не меняйте его ради обхода локального учета. Значения приложения не гарантируют тариф или квоты провайдера.
|
||||
|
||||
### Шаблоны писем
|
||||
|
||||
Тексты и рендеринг находятся в `backend/internal/usecase/notification/mailtemplate/`. Передавайте только необходимые адресату данные; одноразовая ссылка и код допустимы в письме подтверждения. Ключи сервиса и данные, на которые получатель утратил права, в письмо не включаются.
|
||||
|
||||
## Изолированный демонстрационный стенд
|
||||
|
||||
```sh
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
make -C deploy monitoring-up DEMO_MODE=isolated
|
||||
make -C deploy demo-down DEMO_MODE=isolated
|
||||
```
|
||||
|
||||
Seed создает отдельный проект `lincodex-demo`, банк и аккаунты с синтетическими данными; повторный запуск идемпотентен. Локальный frontend доступен на `http://localhost:8090`; передавать `APP_HTTP_BIND` в командной строке не нужно. Цель использует корневой `.env` и `deploy/demo/demo.env`, а при отсутствии последнего - публичный пример. Логины печатает команда, пароль задает `DEMO_ACCOUNT_PASSWORD`. Для внешнего доступа выберите свой пароль и передайте его участникам отдельно.
|
||||
|
||||
Гид находится на `/demo`. Основные аккаунты: `candidate@demo.lincodex.test`, `prepared-1@demo.lincodex.test` - `prepared-6@demo.lincodex.test`, `employer-alpha@demo.lincodex.test` и `employer-beta@demo.lincodex.test`. Пройдите путь кандидата от теста до результата, затем от работодателя отправьте приглашение и примите его кандидатом с выбранными контактами.
|
||||
|
||||
`demo-reset DEMO_MODE=isolated` удаляет данные только своего проекта и заполняет его заново; цель отказывается работать при обычных аккаунтах. Не используйте стенд для реальных людей. Демонстрационные категории не откалиброваны, экспресс-прогон не присваивает грейд. Официальная интеграция ФСП не подключена.
|
||||
|
||||
### Сценарий демонстрации
|
||||
|
||||
1. Заполните профиль и анкету кандидата, пройдите тест или откройте подготовленный результат. Банк Backend Junior с Go синтетический; `demo_express` не присваивает грейд или доказательство.
|
||||
2. Выдайте C2 и опубликуйте карточку после предпросмотра. Для анонимной выдачи нужна достаточная группа: один опубликованный кандидат может не появиться в поиске.
|
||||
3. От владельца компании создайте потребность с зарплатной вилкой, найдите кандидата, откройте объяснение и отправьте приглашение.
|
||||
4. Примите его кандидатом с C4 и выбранными контактами. Проверьте чтение только этих полей компанией, затем отзовите доступ или скройте компанию и проверьте отказ.
|
||||
|
||||
Категория `synthetic_demo` демонстрирует механику, а не подтвержденное качество оценки. Встроенные тексты согласий имеют тип `demo`. Практика требует отдельного runner и подходящего банка, поэтому не заявляйте ее частью обычного демонстрационного теста. Остальные границы реализации перечислены в [ARCHITECTURE.md](ARCHITECTURE.md), приемка - в [TESTING.md](TESTING.md).
|
||||
|
||||
Регламент выступления - 10 минут; видео разрешено вместо живого показа. Прогоните рассказ по таймеру и обозначьте ограничения. По возможности сохраните стенд на период оценки; точные даты и включение вопросов жюри в десять минут требуют уточнения.
|
||||
|
||||
### Демонстрационные категории на стенде
|
||||
|
||||
Seed подготавливает категории сам. При ручной настройке нужны открытая категория с опубликованным банком, демонстрационная политика, `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` и аттестация оператора:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:maintainer'
|
||||
```
|
||||
|
||||
Команда требует `DATABASE_URL`. Аттестация закрепляет открытие категории, банк и версию политики; после их изменения повторите открытие и аттестацию. В рабочей среде с реальными кандидатами синтетические категории выключены.
|
||||
|
||||
### Политика подбора на стенде
|
||||
|
||||
На чистом стенде стартовая политика не содержит раздела `matching`. Опубликуйте его до демонстрации поиска:
|
||||
|
||||
```sh
|
||||
make -C backend policy-publish ARGS='matching --actor operator:maintainer'
|
||||
```
|
||||
|
||||
Команда требует `DATABASE_URL` и создает следующую демонстрационную версию. Seed выполняет подготовку сам. Смена политики требует повторного открытия и аттестации демонстрационных категорий; уже начатые попытки сохраняют прежнюю версию.
|
||||
|
||||
### Полоса проверки оценки
|
||||
|
||||
```sh
|
||||
make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operator:maintainer'
|
||||
```
|
||||
|
||||
Команда требует `DATABASE_URL` и показывает сигналы для ручного разбора. Они не доказывают нарушение и не снижают оценку автоматически. Метка `operator:*` нужна для аудита; доступ к базе остается границей доступа оператора.
|
||||
|
||||
### Поиск источника утечки
|
||||
|
||||
```sh
|
||||
make -C backend assessment-leak-trace ARGS='search --actor operator:maintainer --file leaked.txt'
|
||||
```
|
||||
|
||||
Нужны `DATABASE_URL` и тот же `IDENTITY_KEY_SECRET`, которым выданы попытки. Передавайте текст файлом или через `--stdin`, чтобы он не попал в историю команд. Результат и аудит не содержат исходного текста; совпадение - повод для ручной проверки, а не автоматическое решение.
|
||||
|
||||
## Отдельный ML Compose
|
||||
|
||||
ML обслуживает эмбеддинги Giga-Embeddings-instruct-480M и Qwen3-Embedding-0.6B. Образ скачивает закрепленные веса при сборке, проверяет SHA-256 и работает офлайн. Compose использует CPU, лимит 4 CPU и 8 GiB. Это отдельный проект во внешней сети core с DNS-именем `ml`.
|
||||
|
||||
1. Задайте в `.env` общий `ML_SERVICE_TOKEN` для ML и backend: не менее 32 печатных символов без пробелов.
|
||||
2. Запустите core, затем `make -C deploy ml-build` и `make -C deploy ml-up`.
|
||||
3. Дождитесь `/readyz` 200. `/healthz` проверяет процесс, а не загрузку моделей.
|
||||
|
||||
`ML_EMBEDDER=giga,qwen3` загружает обе модели; `none` оставляет сервис неготовым, `fake` предназначен для фикстур. Все маршруты, кроме health/readiness, требуют bearer-токен при его настройке. Без токена сервис допускает только loopback, а контейнер с адресом `0.0.0.0` не стартует. `ml-logs` и `ml-down` управляют этим проектом отдельно.
|
||||
|
||||
Для разработки: `make -C ml install`, `make -C ml model-fetch`, затем `make -C ml run` с `ML_EMBEDDER` и каталогами моделей в окружении. `model-fetch` скачивает около 2.2 GB весов. `make -C ml test-model` проверяет реальные модели отдельно от обычных тестов.
|
||||
|
||||
### ML-сервис на GPU-хосте
|
||||
|
||||
Используйте [шаблон systemd](../../deploy/ml-gpu/lincodex-ml.service) и [пример настроек](../../deploy/ml-gpu/ml.env.example). Сервис ожидает код в `~/lincodex-ml/app/ml`, virtualenv в `~/lincodex-ml/venv`, настройки в `~/.config/lincodex-ml/ml.env` с правами 0600. Версию Python берите из `ml/.python-version`; `make -C ml cuda-requirements` готовит закрепленные зависимости с CUDA-сборкой torch, которую нужно установить с соответствующего индекса PyTorch.
|
||||
|
||||
Подготовьте веса из lock-файлов, укажите приватный адрес, `ML_DEVICE=cuda`, dtype и лимит `ML_CUDA_MEMORY_LIMIT_MB` под ресурсы хоста. После установки юнита и настройки linger: `systemctl --user daemon-reload`, затем `systemctl --user enable --now lincodex-ml.service`. Проверяйте `/readyz`, журнал и реальные модельные тесты на целевом устройстве. Чужие замеры памяти и задержки не являются гарантией для вашего хоста.
|
||||
|
||||
Ограничьте доступ адресом backend. Сервис сам не завершает TLS: для связи через недоверенную сеть нужен защищенный канал. Нехватка CUDA-памяти дает 503 и повтор загрузки; другие постоянные ошибки загрузки при `ML_EXIT_ON_LOAD_FAILURE=true` завершают процесс для перезапуска supervisor.
|
||||
|
||||
### Семантический подбор
|
||||
|
||||
Поиск читает заранее рассчитанные векторы и не вызывает модель в HTTP-запросе.
|
||||
|
||||
1. Дождитесь готовности ML, задайте `SEMANTIC_MATCHING_ENABLED=true`, общий токен и `ML_SERVICE_URL` (по умолчанию `http://ml:8000`), повторите `make -C deploy up`.
|
||||
2. С `DATABASE_URL` стенда выполните `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:maintainer'`. Эта политика требует обе модели; вариант `semantic` использует одну Giga.
|
||||
3. Поставьте существующие данные в обработку: `make -C backend semantic-backfill ARGS='all --run initial'`. Повтор с той же меткой идемпотентен; для новой волны используйте другую метку.
|
||||
|
||||
После новой политики переоткройте и аттестуйте демонстрационные категории. При недоступных или несовместимых векторах поиск использует нейтральное `Sem=0.5` и флаг `ml_unavailable`. Проверки репозиториев GitHub включаются отдельно через `GITHUB_REPOSITORY_CHECKS_ENABLED`; это не условие запуска ML.
|
||||
|
||||
## Отдельный monitoring Compose
|
||||
|
||||
```sh
|
||||
make -C observability check
|
||||
make -C deploy monitoring-up
|
||||
make -C deploy monitoring-logs
|
||||
make -C deploy monitoring-down
|
||||
```
|
||||
|
||||
По умолчанию проект подключается к сети core. После запуска демо используйте `make -C deploy monitoring-up DEMO_MODE=isolated`, чтобы подключить его к сети `lincodex-demo`. Grafana доступна только на loopback; Prometheus, Loki, Alloy и exporters остаются внутри. Дашборды охватывают Go, PostgreSQL, Redis, SeaweedFS, хост и продуктовые метрики. Kafka пока не имеет собственного scrape. React SDK телеметрии пока не подключен. Alert rules есть, доставка уведомлений требует отдельной настройки.
|
||||
|
||||
Prometheus хранит метрики 14 дней с пределом 4 GB, Loki - логи 7 дней. В labels нельзя добавлять контакты, резюме, сырые URL или идентификаторы пользователей. Alloy получает Docker API через ограниченный socket proxy; даже read-only доступ к Docker API позволяет читать чувствительную конфигурацию контейнеров. Считайте этот контур привилегированным.
|
||||
|
||||
Роль PostgreSQL exporter создается только при первом запуске пустого тома: задайте `POSTGRES_EXPORTER_USER` и `POSTGRES_EXPORTER_PASSWORD` заранее. Для существующей базы роль нужно подготовить отдельно. `ML_METRICS_TARGET` добавляет приватный target, но текущий шаблон scrape не передает bearer-токен: защищенный ML потребует также настройки авторизации Prometheus.
|
||||
|
||||
`make -C observability verify-product-metrics` запускает одноразовые core и monitoring, проверяет метрики и отсутствие тестовых персональных данных в телеметрии, затем удаляет их. Это отдельная интеграционная проверка, не часть `check`.
|
||||
|
||||
## Edge proxy, HTTPS и туннель
|
||||
|
||||
Публичный путь: браузер -> HTTPS Nginx на edge -> приватный туннель AmneziaWG -> frontend Nginx -> Go. Шаблоны и скрипты находятся в [deploy/edge](../../deploy/edge/); основной Compose сам TLS не завершает.
|
||||
|
||||
1. Подготовьте `deploy/edge/edge.env` из примера: домен, отдельный `EDGE_LISTEN_IP`, адреса и порт туннеля. Проверьте DNS, свободные listeners и отсутствие пересечения подсетей. На общем edge-хосте сохраняйте существующие сайты и маршруты.
|
||||
2. `make -C deploy edge-config` проверяет шаблоны и `nginx -t` в контейнере; `edge-render` пишет nginx-конфиги в `deploy/edge/rendered/`. Эти цели ничего не устанавливают на хост.
|
||||
3. На edge установите HTTP-конфиг для ACME, получите сертификат certbot, затем установите HTTPS-конфиг и hook [reload-nginx.sh](../../deploy/edge/certbot/reload-nginx.sh). Проверяйте `nginx -t` перед reload и продление через `certbot renew --dry-run`.
|
||||
4. Создайте ключи туннеля через `deploy/edge/scripts/awg-keys.sh` и отрисуйте соответствующую сторону через `render.sh --params`. Файлы ключей хранятся вне репозитория с доступом только root. Подготовьте AmneziaWG и необходимые systemd drop-ins на обоих хостах.
|
||||
5. На app задайте `APP_HTTP_BIND` равным адресу его туннеля, `APP_PUBLIC_URL=https://<domain>`. Firewall разрешает core-порт только edge, а frontend доверяет forwarded headers только адресу edge. Проверьте правила с обеих сторон; Docker publish не заменяет firewall.
|
||||
|
||||
Перед открытием доступа проверьте HTTPS и цепочку сертификата, HTTP-редирект, глубокую ссылку SPA, вход и CSRF, запрет `/metrics` и административных путей. Edge заменяет forwarded headers, а не доверяет присланным клиентом. Выполните `make -C deploy check-perimeter` и `make -C deploy perimeter-test`; последний поднимает одноразовые Nginx-контейнеры.
|
||||
|
||||
Для отката храните предыдущие конфиги и сертификаты, проверяйте их перед reload. Не удаляйте чужие интерфейсы, правила firewall или конфигурацию сайтов. Проверка шаблонов не подтверждает доступность публичного домена.
|
||||
|
||||
## Изолированный хост раннера и лабораторий (LXD)
|
||||
|
||||
LXD требует Linux с KVM, места для btrfs-пула и прав оператора. Сначала проверьте [acls.sh](../../deploy/labs/acls.sh) и [lxd-preseed.yaml](../../deploy/labs/lxd-preseed.yaml) под сеть хоста, затем примените ACL перед preseed. Скрипты создают отдельные мосты runner и управления лабораториями; гостям назначаются статические адреса без NAT, DHCP и DNS. Не применяйте схему поверх чужих одноименных объектов.
|
||||
|
||||
Backend не получает сокет LXD. Группа `lxd` дает права, эквивалентные root; доступ имеют только оператор и labd. Проверьте запрет доступа гостей к core, хосту, LAN и интернету на реальном хосте: конфигурация сама по себе этого не доказывает.
|
||||
|
||||
## Исполнитель кода
|
||||
|
||||
Сервис `runner/` запускает Python и Go в nsjail с cgroup v2, seccomp и лимитами. Супервизору нужны привилегии для изоляции; код кандидата выполняется непривилегированным пользователем. История прогонов находится в памяти runner и теряется при перезапуске.
|
||||
|
||||
### Локально (только разработка)
|
||||
|
||||
`make -C deploy runner-dev-up` создает токен в `runner/.dev/api-token` и поднимает отдельный привилегированный контейнер с HTTP на loopback. Остановка: `runner-dev-down`. Этот режим запрещен на core-хосте и не входит в release. Backend требует TLS и не подключается напрямую к этому HTTP-режиму.
|
||||
|
||||
### Production: VM исполнителя
|
||||
|
||||
Используйте отдельную LXD VM с собственным ядром, без каталога core, Docker socket, секретов приложения и маршрута по умолчанию. Сеть разрешает вход к API только от app-сети и стороны хоста, а исходящие соединения гостя запрещены. Обязательны TLS 1.3 и bearer-токен. nsjail требует делегированную cgroup v2 и рабочий tmpfs с `exec,nosuid,nodev`.
|
||||
|
||||
### Шаги скрипта VM
|
||||
|
||||
На подготовленном app-хосте от участника групп `docker` и `lxd`:
|
||||
|
||||
```sh
|
||||
make -C deploy runner-vm-up
|
||||
make -C runner a16-bundle
|
||||
make -C deploy runner-vm-a16 A16_BUNDLE=/path/to/a16-bundle.tar.gz
|
||||
make -C deploy runner-vm-check
|
||||
```
|
||||
|
||||
Пакет A16 можно собрать на машине с Go и перенести на app-хост. `runner-vm-up` последовательно готовит секреты, rootfs, VM и сервис. Отдельные цели: `runner-vm-secrets`, `runner-vm-rootfs`, `runner-vm-create`, `runner-vm-install`. Секреты и отчеты находятся в `RUNNER_VM_STATE_DIR`, по умолчанию `~/lincodex-runner`, вне репозитория.
|
||||
|
||||
### Проверка на хосте приложения
|
||||
|
||||
До включения практики должны пройти A16 на целевой VM и `runner-vm-check`: TLS, токен, выполнение безвредных программ, лимиты, очистка и сетевые запреты. Неудача блокирует включение практики. После изменения ядра, runtime или настроек изоляции повторите проверки. Прошлый успешный прогон на другом выпуске не заменяет их.
|
||||
|
||||
### Клиент исполнителя кода
|
||||
|
||||
Задайте в backend `CODE_RUNNER_URL` с HTTPS, `CODE_RUNNER_TOKEN`, отдельный `CODE_RUNNER_RUN_KEY` и ровно один из `CODE_RUNNER_CA_FILE`/`CODE_RUNNER_CA_PEM`. CA-файл нужно смонтировать в контейнер вручную. При необходимости задайте `CODE_RUNNER_SERVER_NAME`; проверка сертификата остается включенной. Тайм-аут запроса задает `CODE_RUNNER_REQUEST_TIMEOUT`.
|
||||
|
||||
Без URL все остальные `CODE_RUNNER_*` должны быть пустыми; практика сообщает недоступность. Неверная конфигурация останавливает запуск. `make -C backend test-code-runner-live` проверяет клиент на подготовленном TLS-исполнителе с `CODE_RUNNER_URL`, `CODE_RUNNER_TOKEN` и `CODE_RUNNER_CA_FILE` из окружения; это не заменяет A16.
|
||||
|
||||
### Очередь практики и лимиты отладочных прогонов
|
||||
|
||||
Backend уже подключает обработчик практики и очередь PostgreSQL при наличии `DATABASE_URL` и настроенного runner. Очередь допускает один активный и десять ожидающих прогонов; Redis ограничивает отладочные запросы кандидата. Настройки `PRACTICE_*` находятся в `backend/config/`, но не проброшены обычным Compose. Сбой инфраструктуры заканчивается без оценки, а не неверным ответом; очередь наблюдается через `assessment_practice_jobs`.
|
||||
|
||||
## Лаборатории и labd
|
||||
|
||||
labd работает systemd-сервисом на app-хосте и единолично управляет LXD. Используйте [юнит](../../deploy/labs/lincodex-labd.service) и [настройки](../../deploy/labs/labd.env.example): TLS, токен, разрешенные сети, файл состояния и бюджет памяти. Сохраняйте файл состояния вместе с LXD-объектами: он нужен для восстановления и удаления лабораторий.
|
||||
|
||||
Сейчас встроенный реестр шаблонов пуст, backend не подключает адаптер labd, WebSocket-консоль отвечает 501. Для рабочего сценария нужны подготовленные образы, шаблоны и интеграция. Перед включением проверяют L2-изоляцию, MAC/port filtering, cloud-init и подлинность узлов при проверке. `make -C labd test-live` создает и удаляет лабораторию на отдельном тестовом LXD с `LABD_LIVE_SOCKET` и `LABD_LIVE_SOURCE`; на production его не запускают.
|
||||
|
||||
## Манифест выпуска
|
||||
|
||||
Для воспроизводимого выпуска нужны чистое рабочее дерево и прошедшие проверки тех же образов:
|
||||
|
||||
```sh
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-manifest-check RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-up RELEASE_ID=demo-stage-1
|
||||
make -C deploy release-manifest-verify RELEASE_ID=demo-stage-1
|
||||
```
|
||||
|
||||
Манифест в `deploy/release/<id>/` фиксирует исходники, зависимости, Compose, image ID/digest и входные данные. Один ID неизменяем; новая поставка требует нового. Артефакты локальные и не коммитятся. `RELEASE_DATA_MANIFEST` добавляет версии банка, политики и seed; отсутствие принятого банка остается явным ограничением, а не готовностью продукта.
|
||||
|
||||
`release-up` требует локальных образов и соответствующих файлов, не собирает и не скачивает их. Для другого проекта используйте тот же `APP_PROJECT` и `RELEASE_VERIFY_PROJECT`. Демонстрация из выпуска: `demo-seed DEMO_MODE=isolated RELEASE_ID=<id>`. Остановка: `release-down` с тем же ID. `release-clean` удаляет только ссылки образов, не удерживаемые манифестами.
|
||||
|
||||
Манифест не делает резервные копии данных и не разворачивает edge, GPU-хост, runner или labd. До обновления сохраните данные и конфигурацию; откат образа не отменяет миграции. План восстановления PostgreSQL и объектов SeaweedFS проверяйте отдельно.
|
||||
|
||||
## Проверки
|
||||
|
||||
| Команда | Что проверяет |
|
||||
| --- | --- |
|
||||
| `make -C deploy check` | Compose и проверки инструментов без запуска стека |
|
||||
| `make -C deploy smoke` | Состояние зависимостей и сетевые границы одноразового стека |
|
||||
| `make -C frontend install`, затем `make -C deploy test-e2e` | Браузерные сценарии на одноразовом стеке |
|
||||
| `make -C deploy test-e2e-registration` | Сценарии с локальной почтовой фикстурой |
|
||||
| `make -C observability check` | Конфигурацию мониторинга и alert rules |
|
||||
|
||||
Охват тестов и требования окружения: [TESTING.md](TESTING.md). Успешный health check не подтверждает весь бизнес-сценарий.
|
||||
+89
-229
@@ -1,251 +1,111 @@
|
||||
# Разработка
|
||||
|
||||
Эта страница описывает реализованные компоненты и команды репозитория. Текущие бизнес-сценарии перечислены ниже; целевая архитектура находится в [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
[English](../en/DEVELOPMENT.md)
|
||||
|
||||
## Стек и источники версий
|
||||
Команды ниже выполняются из корня репозитория. Устройство сервисов описано в [ARCHITECTURE.md](ARCHITECTURE.md), запуск окружения - в [DEPLOYMENT.md](DEPLOYMENT.md), проверки - в [TESTING.md](TESTING.md).
|
||||
|
||||
| Компонент | Источник выбранной версии |
|
||||
## Инструменты
|
||||
|
||||
Версии берите из файлов, которые использует сборка:
|
||||
|
||||
| Инструмент | Источник |
|
||||
| --- | --- |
|
||||
| Go | точная версия 1.26.9 в backend/go.mod, toolchain и Go build image |
|
||||
| Node.js | frontend/.node-version |
|
||||
| Frontend dependencies | актуальные stable releases в package manifests и pnpm-lock.yaml |
|
||||
| Python и uv | версии ML toolchain и uv.lock |
|
||||
| Go | `backend/go.mod`, `runner/go.mod`, `labd/go.mod` и соответствующие Dockerfile |
|
||||
| Node.js | `frontend/.node-version` |
|
||||
| pnpm и frontend | `frontend/package.json`, `frontend/pnpm-lock.yaml` |
|
||||
| Python и uv | `ml/.python-version`, `ml/pyproject.toml`, `ml/uv.lock` |
|
||||
| Go-генераторы | Директивы `tool` и зависимости в Go-модулях |
|
||||
| Контейнеры | `deploy/docker/` и Dockerfile сервисов |
|
||||
|
||||
Frontend зависимости выбираются из актуальных stable releases; сохраняйте pnpm-lock.yaml для повторяемой установки. ML зависимости фиксируются в uv.lock, Go dependencies - в backend/go.mod. При обновлении меняйте соответствующий lock/config и запускайте checks области. Образы используют заданные moving `latest` или `alpine` tags; сверяйте ссылки в Compose/Dockerfiles и не считайте их стабильными номерами версии.
|
||||
Для контейнерных проверок нужны Docker с Compose plugin. Для race detector нужен поддерживаемый C toolchain. Сохраняйте lockfiles; при обновлении зависимости проверяйте ее потребителей. Moving tags `latest` и `alpine` могут менять содержимое образа; воспроизводимый выпуск фиксирует digest.
|
||||
|
||||
## Состояние реализации
|
||||
```sh
|
||||
make install
|
||||
make help
|
||||
```
|
||||
|
||||
Реализация MVP продолжается. Значения ниже взяты из указанных файлов; при обновлении зависимости меняйте ее источник и lockfile, затем обновляйте эту таблицу на обоих языках.
|
||||
`install` ставит зависимости API, frontend и ML и скачивает Go-модули backend, runner и labd. Он не запускает сервисы и не устанавливает Docker или системные компиляторы.
|
||||
|
||||
| Компонент | Закрепленная версия | Источник |
|
||||
| --- | --- | --- |
|
||||
| Go | 1.26.9 (директива `go`; отдельной строки `toolchain` нет) | backend/go.mod; build image `golang:1.26.9-alpine` в backend/Dockerfile |
|
||||
| Node.js | 26.11.1 | frontend/.node-version |
|
||||
| pnpm | 12.9.1 | `packageManager` в frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| React, React DOM | 19.3.0 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| React Router (`react-router-dom`) | 7.18.4 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| TanStack Query (`@tanstack/react-query`) | 5.104.1 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Zod | 4.6.5 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Vite | 8.3.2 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| TypeScript | 7.0.2 (`@typescript/native`, `tsc`); API 6.0.2 (`typescript` как alias `@typescript/typescript6`) для ESLint | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Vitest | 5.0.3 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Orval | 8.40.0 | frontend/package.json, frontend/pnpm-lock.yaml |
|
||||
| Python | 3.14.8 (`requires-python >=3.14,<3.15`) | ml/.python-version, ml/pyproject.toml |
|
||||
| uv | 0.12.22 | `[tool.uv] required-version` в ml/pyproject.toml; `setup-uv` в .github/workflows/ci.yml |
|
||||
| FastAPI | 0.142.2 | ml/pyproject.toml, ml/uv.lock |
|
||||
| Pydantic | 2.13.5 | ml/pyproject.toml, ml/uv.lock |
|
||||
| uvicorn | 0.54.0 | ml/pyproject.toml, ml/uv.lock |
|
||||
| ogen | v1.24.0 | backend/go.mod (`require` и `tool`) |
|
||||
| sqlc | v1.31.1 | backend/go.mod (`tool`) |
|
||||
| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` и `tool`) |
|
||||
| mockery | v3.8.0 | backend/go.mod (`tool`) |
|
||||
| golangci-lint | v2.14.0 | backend/go.mod (`tool`) |
|
||||
| goose | v3.28.0 | backend/go.mod (`require` и `tool`) |
|
||||
| chi | v5.3.2 | backend/go.mod |
|
||||
| pgx | v5.11.0 | backend/go.mod |
|
||||
| testcontainers-go | v0.44.0, включая modules/postgres | backend/go.mod |
|
||||
| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; producer relay outbox, участники consumer group обработчиков событий и integration tests | backend/go.mod |
|
||||
## Обычный цикл
|
||||
|
||||
Что есть сейчас:
|
||||
1. Найдите источник изменения: контракт, usecase, SQL, UI или конфигурацию.
|
||||
2. Измените исходники и добавьте проверку наблюдаемого поведения.
|
||||
3. Если затронуты входы генераторов, выполните `make generate`.
|
||||
4. Запустите проверки затронутой области; для общей сверки есть `make check`.
|
||||
5. Проверьте diff, обновите документацию на обоих языках и выполните `make docs-check`.
|
||||
|
||||
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
|
||||
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и `identity.Credentials` подключены для регистрации и подтверждения email. Generated Go client для ML контракта есть, но в bootstrap не подключен.
|
||||
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
|
||||
- OpenAPI контракты api/core/, api/ml/ и api/runner/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки.
|
||||
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает два продуктовых обработчика - доставки писем и inbox, а продуктовые сценарии пока не создают их события; см. [Обработчики событий](#обработчики-событий).
|
||||
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
|
||||
|
||||
API и SPA реализуют регистрацию, подтверждение email, вход, согласия, личный профиль и анкету кандидата, профиль компании, потребности и собственные обращения в поддержку. API также создает и возобновляет попытки оценки; прием ответов и расчет результата пока не подключены. Подбор, приглашения, раскрытие контактов и отправка продуктовых уведомлений остаются в разработке. Worker отправляет служебную почту identity через Resend; SMTP не реализован. Границы каждого сценария описаны в [backend README](../../backend/README.md) и [frontend README](../../frontend/README.md).
|
||||
|
||||
`make -C deploy test-e2e` проверяет техническую оболочку на одноразовом стеке. `make -C deploy test-e2e-registration` дополнительно проверяет бизнес-сценарии с изолированным локальным почтовым приемником и синтетическими данными; он не подтверждает доставку через реальный Resend. См. [TESTING.md](TESTING.md#браузерный-e2e-набор).
|
||||
|
||||
## Установка и цикл работы
|
||||
|
||||
Frontend проверяется компилятором TypeScript 7.0.2 (`tsc`). Пакет `@typescript/native` ссылается на него через npm alias, а `typescript` ссылается на совместимый API `@typescript/typescript6` для ESLint. Это [рекомендованная Microsoft схема совместного использования](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): текущий typescript-eslint еще не работает с API TS7. В проверку типов входят исходники, Vite config и TypeScript-файлы `codegen/`.
|
||||
|
||||
Orval создает `frontend/src/shared/api/endpoints/` и `schemas/` без дополнительного каталога `generated/`. `client.ts` и корневой `index.ts` в `shared/api/` поддерживаются вручную. Generated MSW handler проверяется вместе с generated client в Node-тесте. После Orval шаг `frontend/codegen/mock-patterns.ts` заменяет в MSW-моках `faker.helpers.fromRegExp` на `fakeFromPattern` с границами длины из контракта, а `mock-validity.test.ts` проверяет каждый мок ответа его Zod-схемой; подробнее в [frontend/README.md](../../frontend/README.md#генерация-api-клиента). Vitest пока сообщает peer warning об ожидаемом MSW 2; текущий Node-путь проверен с MSW 3, browser mode не используется.
|
||||
|
||||
Игноры находятся в `.gitignore` соответствующего компонента. Корневой файл содержит только правила для файлов самого корня. В CI pnpm устанавливается по `packageManager` из frontend/package.json; встроенный Corepack не требуется. Для локальной проверки ML с другой глобальной версией uv можно передать `UV='uv tool run --from uv==0.12.22 uv'` в Make.
|
||||
|
||||
В корне используйте make help для актуального списка. Основные targets:
|
||||
|
||||
- make install - поставить зависимости для api, frontend, ml и backend;
|
||||
- make generate - собрать оба OpenAPI bundle и обновить Go/TypeScript/Python generated output;
|
||||
- make fmt и make fmt-check - отформатировать или проверить форматирование;
|
||||
- make lint - запустить настроенные линтеры;
|
||||
- make test - unit/component/service tests для backend, frontend и ML;
|
||||
- make check - проверки api, backend, frontend, ML, deploy, observability и документации;
|
||||
- make verify - generation, drift checks, root check, api/backend проверки и технический Compose smoke;
|
||||
- make docs-check - проверить RU/EN документы, локальные ссылки, маршруты и импорты.
|
||||
|
||||
Локальный цикл для одной области описан Makefile этой области. Например, make -C backend help, make -C frontend help, make -C ml help, make -C api help, make -C deploy help, make -C observability help.
|
||||
|
||||
make check не является бизнес-E2E проверкой. make verify запускает deployment smoke с Docker и integration target backend. Для подробностей см. [TESTING.md](TESTING.md); для локального стенда см. [DEPLOY.md](DEPLOY.md).
|
||||
|
||||
У инструментов безопасности отдельный цикл установки и проверки: `make -C security install`, затем `make -C security check`. После изменения локальных правил или интеграции сканеров запускайте `make -C security test`; для сборки и сканирования образов сервисов - `make -C security images`. Эти проверки отделены от обычного корневого `make check`; требования, политика и отчеты описаны в [SECURITY.md](SECURITY.md).
|
||||
|
||||
### Сессии на локальном HTTP
|
||||
|
||||
Cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict` (см. [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Локальный стек отдает обычный HTTP. Chromium и Firefox считают `http://localhost` и `http://127.0.0.1` безопасным контекстом и сохраняют там `Secure` cookie; WebKit и Safari могут ее отклонить. Для локального входа используйте Chromium или Firefox либо локальный TLS-прокси. Проект не добавляет флаг, отключающий `Secure` или префикс `__Host-`, поэтому локальная cookie не отличается от production.
|
||||
|
||||
`ConfirmEmail` требует, чтобы Origin точно совпадал с `APP_PUBLIC_URL`; отсутствующий Origin, буквальное значение `null` или другое значение дают 403 `csrf_check_failed`. Та же проверка действует для остальных небезопасных identity-операций и защищенных запросов сессии; последние также требуют привязанный к сессии CSRF-токен. Сервер не использует Host для определения разрешенного Origin.
|
||||
|
||||
## Структура
|
||||
|
||||
В каждом каталоге первого уровня, кроме `.github/`, есть краткий `README.md` на русском и его перевод `README.en.md`. В `.github/` README и его перевод необязательны. Подробные руководства находятся в `docs/ru/` и `docs/en/`; README глубже первого уровня не добавляются. `make docs-check` проверяет языковые пары, ссылки и запускает тесты самого проверяющего скрипта.
|
||||
|
||||
| Каталог | Назначение |
|
||||
| Команда | Назначение |
|
||||
| --- | --- |
|
||||
| api/core/ | Публичный OpenAPI контракт браузер-Go |
|
||||
| api/ml/ | Внутренний OpenAPI контракт Go-ML |
|
||||
| api/runner/ | Внутренний OpenAPI контракт Go и исполнителя кода |
|
||||
| scripts/ | Общее объединение схем, generated drift и docs-check |
|
||||
| backend/ | Go HTTP service, adapters, bootstrap, SQL и codegen потребителя |
|
||||
| backend/config/ | Общая конфигурация Go вне internal |
|
||||
| frontend/ | Vite SPA, Orval config и generated TypeScript |
|
||||
| ml/ | Python service, lockfile и генератор Pydantic-моделей |
|
||||
| runner/ | Go-сервис исполнителя кода: nsjail, cgroup v2, judge, ogen-сервер и тесты изоляции |
|
||||
| deploy/ | Compose, Nginx и smoke |
|
||||
| observability/ | Prometheus, Loki, Alloy и provisioning/dashboard JSON |
|
||||
| security/ | Конфигурация сканеров, установка, Make targets и локальные отчеты |
|
||||
| .agents/ | Канонические проектные инструкции и рабочие стандарты |
|
||||
| docs/ru/, docs/en/ | Пользовательские документы на русском и английском |
|
||||
| `make fmt` | Изменить форматирование исходников |
|
||||
| `make fmt-check` | Проверить формат без исправлений |
|
||||
| `make test` | Unit- и компонентные тесты сервисов |
|
||||
| `make check` | Проверки кода, документации и конфигурации |
|
||||
| `make verify` | Генерация, drift, проверки, race, интеграционные тесты и smoke |
|
||||
|
||||
Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Go client исполнителя кода создается из backend/codegen/ogen-code-runner.yml в backend/internal/adapter/secondary/code_runner/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go.
|
||||
`verify` требует Docker и не включает Playwright, security-сканеры или проверку реальных ML-моделей. Их выбирают отдельно по изменению.
|
||||
|
||||
## Локальное окружение
|
||||
|
||||
Для полного приложения используйте Compose. `.env.example` описывает переменные; секреты хранятся в локальном `.env` и не попадают в Git или примеры команд.
|
||||
|
||||
`make -C backend run` читает окружение процесса, а не файл `.env`. Адреса PostgreSQL, Redis, SeaweedFS и Kafka из Compose не обязаны быть доступны процессу на хосте. Не отключайте нужные зависимости только ради успешного старта.
|
||||
|
||||
`make -C frontend dev` запускает Vite с прокси `/api` на `127.0.0.1:8080`. Авторизация проверяет публичный Origin, поэтому `APP_PUBLIC_URL` должен соответствовать адресу браузера. Для проверки полного cookie-сценария проще использовать приложение за Nginx.
|
||||
|
||||
Почта по умолчанию отключена. Для разработки регистрации используйте изолированный почтовый E2E-стенд либо настройте Resend; SMTP-транспорт пока не реализован. Готовые синтетические аккаунты есть на отдельном demo-стенде.
|
||||
|
||||
## Контракты и генерация
|
||||
|
||||
Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/, api/ml/ и api/runner/, затем bundles для каждого входа. Публичный и внутренние API не объединяются в одну спецификацию.
|
||||
Редактируйте тематические `routes/` и `components/` в `api/core/`, `api/ml/`, `api/runner/` или `api/labd/`. Общие правила HTTP собраны в [api/README.md](../../api/README.md).
|
||||
|
||||
Корневой make generate подготавливает API bundles один раз, затем запускает потребителей Go, TypeScript и Python. Merged schemas, bundles и generated clients являются отслеживаемыми derived files; меняйте исходники и пересоздавайте их генератором. После контракта перегенерируйте всех потребителей и запустите drift check. Отдельный Make target можно использовать для генерации одной части, если ее вход готов и shared contract owner согласовал его.
|
||||
|
||||
Целевое решение - OpenAPI 3.2.0, ogen для Go, Orval для TypeScript и datamodel-code-generator для Python/Pydantic v2. Проверяйте только реальные конструкции, которые использует проект, через pinned tools и runtime path. Название версии в заголовке не является подтверждением поддержки полной спецификации.
|
||||
|
||||
Python-генератор datamodel-code-generator 0.83.0 читает api/ml/openapi.bundle.yml и создает ml/src/lincodex_ml/api/models.py. Настройки хранятся в ml/codegen/pyproject.toml; это конфигурация инструмента, а зависимости остаются в ml/pyproject.toml и uv.lock. Health/readiness handlers импортируют сгенерированные модели вместо ручных копий схем. make -C ml generate сначала собирает API; при вызове из корневого make generate параметр API_PREPARED=1 использует уже собранный bundle. make -C ml check-generated сравнивает результат через --check без перезаписи файла. CI использует общий make generate, который включает Python-модели.
|
||||
|
||||
Ошибки, повторы, версии, пагинация и время следуют [соглашениям контракта](../../api/README.md#соглашения-контракта). Реализовано: любая ошибка публичного Go API и ML-сервиса - problem по RFC 9457 (`application/problem+json`) со стабильным `code`. Go-маппинг ошибок ogen находится в backend/internal/adapter/primary/http/problem/: валидация запроса дает 400, неизвестный маршрут под /api - 404, нереализованная операция - 501, остальные ошибки и panic - 500 без внутреннего текста; ошибки логируются на этой границе, panic - только типом и stack. Frontend API client бросает `ApiRequestError` для problem, сетевых сбоев (`network_error`) и некорректных 2xx-тел (`invalid_response`); отмена вызывающим пробрасывается без изменений. ML-сервис преобразует ошибки FastAPI в ml/src/lincodex_ml/api/problems.py и направляет логи uvicorn через свой JSON-формат без текста исключений. Хранение Idempotency-Key, проверки If-Match и пагинация запланированы: контракт определяет их компоненты, а реализует их первая бизнес-операция, которой они нужны.
|
||||
|
||||
## Код и слои
|
||||
|
||||
Зависимости SQL-линтера перечислены в `backend/requirements-quality.txt` рядом с `.sqlfluff`. Команда `make -C backend lint-sql` устанавливает их в локальное окружение `.venv-quality` и проверяет миграции и запросы. Для запуска Go-сервиса это окружение не требуется.
|
||||
|
||||
Go следует границам domain, usecase, port, adapter и bootstrap. HTTP adapter монтирует generated ogen handler в chi. SQL принадлежит backend/db/queries/, изменения схемы - backend/db/migrations/. sqlc output и wire_gen.go сгенерированы.
|
||||
|
||||
Общие backend параметры находятся в backend/config/. Используются go-logkit 0.6.0 через slog bridge и go-httpkit 0.7.0 для request ID и panic recovery. Журнал запросов - собственный `middleware.RequestLog`: logger из go-httpkit пишет исходный путь и каждое значение query вне своего фиксированного списка скрытия, поэтому адрес в пути или query попал бы в журналы. Собственный Prometheus middleware сохраняется: он ограничивает method labels и использует chi route patterns; go-httpkit/metrics принимает исходное имя метода как label.
|
||||
|
||||
Подключение к PostgreSQL создается через pgxpool.NewWithConfig, а generated SELECT 1 readiness query проверяет доступность БД. Pool constructor не должен ждать доступность БД при startup. go-pgkit 1.4.0 не используется: его constructor проверяет подключение и повторяет попытки до возврата pool, что связывало бы запуск сервиса с доступностью БД. Health handlers остаются явными: helper go-httpkit возвращает ok/degraded и детали проверок, а общий контракт использует ok/ready/not_ready. Не добавляйте pgkit, httpkit/metrics, JWT или WebSocket без конкретной потребности и проверки поведения закрепленной версии.
|
||||
|
||||
Redis подключен через outbound-порт кеша и `backend/internal/adapter/secondary/redis/`. Адаптер использует `go-cachekit` 0.7.0 для операций key/value поверх go-redis; детали библиотек не выходят за его границу. Bootstrap создает клиент без ожидания подключения и закрывает его при завершении; общий /readyz проверяет PostgreSQL, Redis и SeaweedFS. Используйте Get/Set/Del, положительный TTL и отличайте отсутствие ключа от ошибки Redis. Это технический адаптер, потребители продуктового кеша пока не добавлены. Настройки подключения описаны в [DEPLOY.md](DEPLOY.md).
|
||||
|
||||
S3-хранилище подключено через outbound-порт `ObjectStorage` и `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS - отдельный сервер, а AWS SDK for Go v2 - клиент Go внутри адаптера. Put/Get передают содержимое потоком; Put требует известный размер в байтах, а вызывающий код обязан закрыть тело, возвращенное Get. Таймаут Get действует до завершения чтения тела. Адаптер ограничивает время операций и отличает отсутствие объекта от ошибки сервиса. Bucket создается при запуске контейнера; Go проверяет его через HeadBucket, не создавая инфраструктуру при обработке запросов. Не добавляйте прямую выдачу приватных файлов Nginx или продуктовые upload/download endpoints без правил доступа.
|
||||
|
||||
Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы.
|
||||
|
||||
Реализованный каркас frontend: data router React Router с публичными маршрутами и отдельными оболочками кабинетов кандидата и работодателя, клиент TanStack Query поверх общего `apiRequest` того же origin, токены темной графитовой темы в CSS variables и общие примитивы состояний загрузки, пустого результата, ошибки, запрета доступа и сохранения. Шрифты JetBrains Mono, Inter и Unbounded (для словесного знака Lincodex) раздаются с нашего сервера вместе с лицензиями OFL. Вход, регистрация, подтверждение почты, поддержка и экраны кабинетов - заготовки; бизнес-экраны делаются отдельными задачами. /status - техническая страница доступности API, а не показатель готовности продукта. Vitest работает в окружении Node без DOM. Набор Playwright в `frontend/e2e/` открывает страницы в Chromium, но пока не проверяет взаимодействия, поэтому нажатия и фокус клавиатуры проверяются вручную в браузере, пока набор их не покрывает. Подробнее: [frontend/README.md](../../frontend/README.md). Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации.
|
||||
|
||||
ML - отдельный FastAPI процесс. Сейчас он предоставляет только operational health/readiness. Readiness остается 503 без модели. Не добавляйте placeholder inference, который выглядит как рабочий результат.
|
||||
|
||||
Все комментарии и docstrings в коде пишутся на английском. Инструкции для агентов в корне и .agents также ведутся в единой английской версии; документация команды поддерживается на русском и английском.
|
||||
|
||||
### Миграции базы данных
|
||||
|
||||
Миграции - SQL-файлы goose в `backend/db/migrations/` с именами `NNNNN_description.sql` и последовательными пятизначными версиями. В каждом файле есть секция `-- +goose Up` и работающая секция `-- +goose Down`. sqlc читает этот же каталог как схему, а `make -C backend lint-sql` проверяет его линтером. `backend/db/migrations.go` встраивает файлы в бинарник, поэтому он применяет ровно ту схему, с которой собран. `make -C backend check` загружает встроенный набор без базы данных и падает на неверном имени, отсутствующей секции Down или дублирующейся версии. Примененная на стенде миграция неизменна; схема меняется новым файлом. Две ветки с одинаковой версией должны перенумеровать файл перед слиянием. Чтобы создать файл со следующим номером, выполните `go tool goose -dir db/migrations -s create <name> sql` в `backend/`.
|
||||
|
||||
goose выполняет каждую миграцию в отдельной транзакции. Команде, которая не работает внутри транзакции, например `CREATE INDEX CONCURRENTLY`, нужен отдельный файл с аннотацией `-- +goose NO TRANSACTION`. Каждое соединение миграций устанавливает `lock_timeout` в 10 секунд, чтобы DDL падал, а не ждал за длинными транзакциями и не блокировал последующие запросы к таблице, и `statement_timeout` в 4 минуты.
|
||||
|
||||
При старте bootstrap применяет ожидающие миграции после проверки конфигурации и до открытия HTTP и metrics listeners. Runner в `backend/internal/adapter/secondary/postgres/migrator.go` использует Provider API goose v3 с драйвером pgx для database/sql и сессионный advisory lock PostgreSQL, поэтому одновременно стартующие экземпляры применяют миграции по очереди. Ожидание блокировки и сами миграции ограничены пятью минутами. Ошибка миграции останавливает запуск; текст ошибки не содержит строку подключения и пароль. Без `DATABASE_URL` шаг пропускается с предупреждением, а readiness, как и раньше, остается `not_ready`.
|
||||
|
||||
`DATABASE_MIGRATE_ON_START` принимает только `true` или `false` (без учета регистра, пробелы по краям игнорируются); по умолчанию `true`. Это опция для локальной разработки, например чтобы запустить сервис с базой, которую разработчик мигрирует вручную. Compose ее не передает, а в образе backend нет отдельной команды миграций, поэтому развернутый backend всегда мигрирует при старте, и его роли БД нужны права DDL на схему приложения. Отдельная роль и job миграций с минимальными правами runtime-роли - будущая работа.
|
||||
|
||||
Для локальной базы экспортируйте `DATABASE_URL` в shell и используйте цели:
|
||||
|
||||
- `make -C backend migrate-status` показывает каждую встроенную миграцию как примененную, со временем, или ожидающую.
|
||||
- `make -C backend migrate-up` применяет ожидающие миграции.
|
||||
- `make -C backend migrate-down-one` откатывает последнюю примененную миграцию.
|
||||
|
||||
Цели запускают `backend/cmd/migrate` с тем же runner, блокировкой и таймаутами, что и старт сервиса. Makefile не содержит строк подключения; не храните учетные данные в коммитах. Интеграционные тесты применяют все миграции к контейнеру PostgreSQL из общего bootstrap; см. [TESTING.md](TESTING.md).
|
||||
|
||||
### Хранение identity
|
||||
|
||||
Миграция `00002_create_identity_tables.sql` создает `users`, `email_tokens` и `sessions`; запросы лежат в `backend/db/queries/identity.sql`. Миграция 00014 добавляет к токенам хеш пароля, сценарий и шаг онбординга конкретной регистрации. Миграция 00016 связывает регистрационную C1 с версией регистрации аккаунта и заполняет прежние записи без использования живых токенов. Порты identity используются при регистрации, повторной отправке и подтверждении email; вход и principal сессии пока не реализованы.
|
||||
|
||||
База данных никогда не получает пароль, исходный email-токен или исходный токен сессии. Репозитории принимают `domain.PasswordHash` (строку PHC Argon2id v19) и `domain.SecretTokenHash` (SHA-256 от `domain.SecretToken`). Email-адреса пока принимаются только в ASCII; поддержка IDN и SMTPUTF8 - будущая работа, для которой нужен IDNA ToASCII для домена. `SecretToken`, `PasswordHash` и `EmailAddress` скрывают значение в выводе `fmt` и `slog`; `SecretToken.Reveal` и `EmailAddress.Address` возвращают настоящие значения там, где они нужны. Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, а PostgreSQL хранит микросекунды. Взаимная блокировка или ошибка сериализации сообщается как `outbound.ErrTransactionConflict`, и вызывающий код может повторить всю операцию. Схема и принятые решения описаны в [ARCHITECTURE.md](ARCHITECTURE.md#хранение-identity).
|
||||
|
||||
Пароль попадает в backend только как `domain.Password`: `domain.NewPassword` для нового пароля (от 15 до 128 кодовых точек после NFKC) и `domain.ParseLoginPassword` при входе (от 1 до 128). Исходный ввод длиннее 512 байт или с некорректным UTF-8 отклоняется до нормализации, и все проверки длины выполняются до хеширования. Адаптер `argon2id` реализует `outbound.PasswordHasher` с m=65536 KiB, t=3, p=4, бюджетом памяти на `PASSWORD_HASH_CONCURRENCY` вычислений (от 1 до 4; без значения - меньшее из 2 и GOMAXPROCS), `ErrPasswordMismatch` для неверного пароля, `ErrPasswordHashCorrupt` для некорректного или выходящего за границы сохраненного хеша, результатом `needsRehash` для старых параметров и `VerifyDummy` для неизвестных аккаунтов. Сохраненный хеш, не прошедший разбор или границы, оборачивает и `ErrPasswordHashCorrupt`, и `domain.ErrInvalidPasswordHash`. Unit-тесты используют дешевые параметры; эталонный вектор на 64 MiB пропускается с `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` в `backend/` измеряет один хеш с production-параметрами. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей).
|
||||
|
||||
### Хранилище продуктовой политики
|
||||
|
||||
Миграция `00003_create_policy_versions.sql` создает `policy_versions`, триггер, который ставит `created_at` по часам базы данных, и триггеры, отклоняющие UPDATE, DELETE и TRUNCATE; запросы лежат в `backend/db/queries/policy.sql`. `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`; `policy.Publisher` публикует версию под следующим свободным номером и выполняет начальное заполнение демонстрационной политики. Чтобы изменить значение, опубликуйте новую версию; сохраненная версия никогда не редактируется. `product` - единственное семейство политики.
|
||||
|
||||
При старте backend публикует `domain.DemoProductPolicyV1()` как версию 1 семейства `product`, если у этого семейства нет ни одной версии. Заполнение выполняется сразу после миграций при старте и только вместе с ними: нужно, чтобы `DATABASE_MIGRATE_ON_START` был равен true и был задан `DATABASE_URL`. Если миграции при старте отключены, политику никто не заполняет. Заполнение проверяет только наличие версий, никогда не меняет и не разбирает существующую версию и пишет в лог только ключ, номер, вид и ID. Демонстрационные значения - принятая начальная политика, а не калиброванные значения.
|
||||
|
||||
Запись, которая зависит от значений политики, добавляет `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, хранит использованную версию и читает ее обратно по ID; не пересчитывайте существующую запись через `GetEffective`. Тесты используют собственные значения и не подменяют демонстрационную политику. Поскольку `product` - единственное семейство, а таблица отклоняет TRUNCATE, интеграционные тесты дают каждому случаю отдельную базу данных. Новой структуре документа нужны новая `schema_version` и свой декодер; не меняйте golden-документ в `backend/internal/domain/policy_test.go`, чтобы принять измененную каноническую форму. См. [ARCHITECTURE.md](ARCHITECTURE.md#версии-продуктовой-политики).
|
||||
|
||||
### Банк заданий оценки
|
||||
|
||||
Миграция `00011_create_assessment_bank.sql` создает `assessment_families` (неизменяемые версии семейств) и `assessment_category_openings`; запросы лежат в `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` доступен через `UnitOfWork.AssessmentBank()` и через `postgres.AssessmentBankStore` вне транзакции; `assessment.Bank` импортирует `Bundle`, публикует версию от имени оператора (выводя из обращения опубликованную более старую), выводит ее из обращения, открывает категорию под действующей версией политики, сообщает живую доступность и генерирует вариант по seed. Чтобы изменить семейство, импортируйте новую версию; сохраненная версия не редактируется, а черновик `pending` одобряется импортом новой версии с рецензией. Новый алгоритм seed получает новое версионное имя в `domain/assessment_algorithms.go`, обязательные подстановки, тест решателя с посчитанными вручную случаями и golden-тест; зарегистрированный алгоритм не меняйте. Алгоритм с форматом ответа `choice` задает `generateChoice` вместо `generate` и возвращает правильное значение вместе с неверными значениями именованных моделей ошибок (пример - `lru_hits_choice.v1`); его тесты пересчитывают модели ошибок по условию. Семейство, варианты которого - фиксированные данные, использует табличный генератор вместо алгоритма: `seed_generator.table.rows` с `values`, `answer` и для `choice` еще `distractors`; при импорте таблица проверяется, ошибка называет индекс строки, а версия хранится со схемой хеша 2. Если ответ нужно вычислять, используйте алгоритм на Go. Схему 2 разрешает миграция `00047_allow_table_hash_scheme.sql`. Шаблоны условий - обычный текст только с подстановками `{{.name}}`. Демонстрационный пакет в `backend/testdata/assessment/` - непроверенный черновик ИИ: не заполняйте в нем рецензента, чтобы открыть категорию. См. [ARCHITECTURE.md](ARCHITECTURE.md#банк-заданий-оценки).
|
||||
|
||||
### Relay outbox
|
||||
|
||||
Relay переносит зафиксированные строки `outbox_events` в Kafka. Цикл находится в `backend/internal/worker/outboxrelay/`, а его backoff - в `backend/internal/worker/retry/`; он зависит от портов `outbound.OutboxRelayStore` и `outbound.EventPublisher` в `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` выполняет транзакцию захвата запросами `LockPendingOutboxEvents` и `MarkOutboxEventsPublished` из `backend/db/queries/outbox.sql`, а `kafka.Publisher` в `backend/internal/adapter/secondary/kafka/` собирает конверт записи, создает топик и публикует через franz-go. `bootstrap.newOutboxRelay` создает relay с собственным пулом PostgreSQL не больше чем на два соединения и собственным клиентом Kafka, а приложение запускает его, пока работают HTTP-серверы. Продуктовый код relay не вызывает: usecase только добавляет события через `UnitOfWork.Outbox()` в своей бизнес-транзакции.
|
||||
|
||||
Backend, запущенный напрямую с `DATABASE_URL`, запускает relay против `KAFKA_BROKERS` (по умолчанию `localhost:9092`). Без доступного брокера он продолжает писать предупреждения о повторах, а события остаются в ожидании; если публикация не нужна, задайте `RELAY_ENABLED=false`. Выбор строк, порядок, конверт и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#relay-outbox), настройки - в [DEPLOY.md](DEPLOY.md#relay-outbox), тесты - в [TESTING.md](TESTING.md#тесты-relay-outbox).
|
||||
|
||||
### Обработчики событий
|
||||
|
||||
Runtime обработчиков применяет события из Kafka к собственному состоянию сервиса, по одному разу на обработчик. Цикл находится в `backend/internal/worker/eventconsumer/`; он зависит от порта `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`) и портов `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` - участник группы на franz-go, который декодирует конверт и фиксирует offsets, а `postgres.EventConsumerStore` выполняет транзакцию дедупликации запросами из `backend/db/queries/event_consumer.sql`. Backoff общий с relay и находится в `backend/internal/worker/retry/`.
|
||||
|
||||
Зарегистрированы два продуктовых обработчика: `notification.DeliveryHandler` сохраняет доставки писем (см. [Доставки писем](#доставки-писем)), а `notification.InboxHandler` сохраняет ссылки inbox (см. [Внутренние уведомления](#внутренние-уведомления)). Чтобы добавить другой обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`.
|
||||
|
||||
Backend, запущенный напрямую с зарегистрированным обработчиком и `DATABASE_URL`, читает события из `KAFKA_BROKERS`; задайте `CONSUMER_ENABLED=false`, если это не нужно. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий); настройки, метрики и порядок работы с dead letters - в [DEPLOY.md](DEPLOY.md#обработчики-событий); тесты - в [TESTING.md](TESTING.md#тесты-обработчиков-событий).
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Чтобы отправить уведомление из usecase, вызовите `notification.MailRequester.RequestNotification(ctx, unit, request)` с `UnitOfWork` usecase, ID аккаунта получателя и `mailtemplate.NotificationData`; вызов возвращает ID доставки. Он сохраняет текст в `mail_requests` и добавляет событие, которое несет только ID запроса и вид, оба действия - в транзакции usecase. Затем обработчик `notification_delivery` сохраняет доставку с адресом, прочитанным из аккаунта, и сформированным содержимым и удаляет запрос; аккаунты с неподтвержденным адресом он пропускает. Никогда не кладите email, токен, текст уведомления или контакт другого человека в payload любого события и никогда не кладите токен или контакт другого человека в запрос. Письма подтверждения почты и сброса пароля содержат токен и не могут идти через событие: сценарии identity создают такие доставки через `domain.NewDelivery` и `UnitOfWork.Deliveries().Create` в транзакции, которая выпускает токен. Новая версия шаблона меняет только новые доставки; никогда не обновляйте содержимое сохраненной доставки. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем), эксплуатация - в [DEPLOY.md](DEPLOY.md#доставки-писем), тесты - в [TESTING.md](TESTING.md#тесты-доставки-писем).
|
||||
|
||||
Каждая отправка обязана пройти `notification.QuotaGate`: соберите его с настроенными аккаунтом и лимитами и окном идемпотентности транспорта (`resend.IdempotencyWindow` или ноль для SMTP); вызовите `PrepareSend` в транзакции, которая захватывает доставку, и зафиксируйте ее до вызова `MailSender.Send`; затем вызовите `SettleSend` в транзакции, которая записывает попытку, и для отказа `quota_exhausted` используйте возвращенный момент как `next_attempt_at` попытки. Для отказа по квоте транспорт заполняет `SendResult.QuotaPeriod` по собственному имени ошибки провайдера. Никогда не вызывайте транспорт без разрешения и не переключайтесь на другой транспорт или аккаунт, когда квота исчерпана. Чтобы показать аккаунту статус его писем, вызывайте `notification.DeliveryStatusReader.LatestForUser` только с ID аутентифицированного аккаунта. Правила описаны в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
|
||||
|
||||
### Внутренние уведомления
|
||||
|
||||
Чтобы положить уведомление в inbox получателя, добавьте событие через `unit.Outbox().Append` в собственной транзакции usecase. Тип должен быть разрешен (`domain.NotificationInboxSourceFor`), payload должен состоять ровно из `recipient_user_id` и `organization_id`, а агрегат - тот, который назван для типа (`invitation` для `invitation.delivered`). Никогда не кладите в payload текст или контакты. Обработчик `notification_inbox` сохраняет ссылку. Текст создается, когда получатель читает список, преобразователем, который вы регистрируете для своего типа источника в `notification.DefaultInboxSourceResolvers()`: `InboxSourceResolver` читает текущее состояние через `UnitOfWork`, применяет текущую видимость получателя и возвращает `ErrInboxContentUnavailable`, когда содержимое показывать нельзя. Для нового типа события добавьте пару в `domain.NotificationInboxSourceFor`, запись в `inboxProjections` в `usecase/notification/inbox_handler.go`, миграцию, расширяющую CHECK у `notification_inbox_events` (развернутую миграцию не правят), значение `NotificationKind` в контракт и отображение в `adapter/primary/http/v1/notifications.go`. Источнику письмо не нужно: почта запрашивается отдельно через `MailRequester`, а состояние inbox от нее не зависит. Путь можно проверить целиком синтетическим событием `notification.synthetic_delivered` (payload строит `notification.SyntheticNoticeEventPayload`); продуктового смысла у него нет, и обрабатывается он только при `NOTIFICATION_SYNTHETIC_ENABLED=true`. См. [Внутренние уведомления](ARCHITECTURE.md#внутренние-уведомления).
|
||||
|
||||
### Задания по сроку
|
||||
|
||||
Чтобы выполнить что-то в срок, например истечение или напоминание, запланируйте задание в собственной транзакции usecase: соберите его через `domain.NewScheduledJob` (вид, например `invitation.response_deadline`, ключ логического задания, например ID агрегата, срок по внедренным часам и payload только из идентификаторов) и вызовите `unit.ScheduledJobs().Schedule(ctx, job)`. Побеждает первое планирование вида и ключа, повтор игнорируется, поэтому для нового повторения используйте новый ключ, например `<id>:<version>`. Отменяйте через `unit.ScheduledJobs().Cancel(ctx, kind, key)` до блокировки продуктовых строк, которые трогает обработчик.
|
||||
|
||||
Затем реализуйте `inbound.JobHandler` в пакете usecase модуля: верните вид из `JobKind()` и пишите эффект в `Handle` только через полученный `UnitOfWork`, принимая решение по `job.DueAt` и текущему продуктовому состоянию, чтобы обработчик ничего не делал, если состояние уже изменилось. Обработчик может отменить собственное задание через unit, например из общего helper, который отменяет срок; тогда задание считается выполненным. Иначе менять собственное задание нельзя. Для задания, которое нельзя выполнить никогда, верните ошибку, оборачивающую `inbound.ErrJobRejected`; любая другая ошибка повторяется. Добавьте обработчик в `jobHandlers()` в `backend/internal/bootstrap/jobs.go`. Принимайте часы как `func() time.Time` и проверяйте сроки через `testutil.FakeClock` из `backend/pkg/testutil/` и `Worker.RunDue`, который один раз выполняет наступившие задания без опроса, как это делает `TestScheduledJobs`. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку); настройки, метрики и порядок работы с dead заданиями - в [DEPLOY.md](DEPLOY.md#задания-по-сроку); тесты - в [TESTING.md](TESTING.md#тесты-заданий-по-сроку).
|
||||
|
||||
## Читаемость Go-кода
|
||||
|
||||
- Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.
|
||||
- Неочевидные лимиты, таймауты, retry settings, границы протоколов и общие значения фикстур получают именованные константы в своем пакете. Размеры вычисляются через `len`, если зависят от данных. Одинаковые числа с разным смыслом получают разные имена. Очевидные нулевые значения, индексы и понятные входы тестов остаются на месте.
|
||||
- Параметры окружения задаются через config с именованными defaults и валидацией. Значение разбирается один раз; отсутствие переменной отличается от явно заданного неверного значения.
|
||||
- Функция решает одну понятную задачу. Используйте ранние возвраты, небольшую вложенность и именованные сложные условия. Не добавляйте универсальные helpers, интерфейсы и слои без потребителя.
|
||||
- Передавайте `context.Context` первым аргументом. Владение ресурсами и зависимости должны быть явными; cleanup регистрируется сразу после создания ресурса, в том числе при частичном startup. Helper не должен скрывать goroutine или глобальное изменяемое состояние.
|
||||
- Проверяйте ошибки. Неочевидное игнорирование результата объясняйте комментарием. Не сравнивайте тексты ошибок для управления программой и не передавайте внутренние ошибки в HTTP-ответы.
|
||||
- Комментарии на английском объясняют ограничения и решения. Форматирование выполняют gofmt/goimports. Рефакторинг сохраняет поведение; тесты проверяют существенные границы и крайние случаи, а не названия констант или устройство helpers.
|
||||
|
||||
## Формат ошибок
|
||||
|
||||
Ошибки в написанном вручную Go-коде имеют формат `Component.Method - operation: %w`, если есть вложенная ошибка, и `Component.Method - reason`, если ее нет. Для обычной функции вместо метода используйте `package.Function`. Например:
|
||||
|
||||
```go
|
||||
if err != nil {
|
||||
return fmt.Errorf("EmailUseCase.Send - read ctf_name: %w", err)
|
||||
}
|
||||
```sh
|
||||
make -C api check
|
||||
make generate
|
||||
make check-generated
|
||||
```
|
||||
|
||||
Статическая ошибка без причины создается через `errors.New("EmailUseCase.Send - ctf_name is empty")`. Префикс указывает реальный метод, описание пишется на английском без точки в конце. Сохраняйте `errors.Is/As` и идентичность sentinel errors; контекст добавляйте в месте возникновения ошибки. Не добавляйте одинаковые обертки при простом возврате ошибки. Сначала очищайте ошибки внешних SDK от секретов, URL и приватных ключей объектов, затем оборачивайте безопасную причину. Generated code не изменяйте. Логируйте ошибку в месте обработки, а не на каждом уровне.
|
||||
Генерация выполняется в порядке: bundle API, Go backend, runner, labd, frontend, Python ML. `make check-generated` сравнивает результат с Git и не запускает генераторы. При намеренном изменении контракта измененный output должен войти в тот же коммит; неожиданный diff нужно разобрать.
|
||||
|
||||
## Правила изменений
|
||||
- ogen пишет Go HTTP-код в `api/` нужного адаптера.
|
||||
- sqlc пишет запросы PostgreSQL в `backend/internal/adapter/secondary/postgres/sqlc/`.
|
||||
- wire собирает зависимости в `backend/internal/bootstrap/`.
|
||||
- mockery генерирует только интерфейсы, выбранные в `backend/codegen/mockery.yml`.
|
||||
- Orval пишет клиент, query hooks, Zod-схемы и MSW в `frontend/src/shared/api/endpoints/` и `schemas/`.
|
||||
- datamodel-code-generator создает Pydantic-модели из ML-контракта.
|
||||
|
||||
- Проверяйте текущий код и назначенный ownership перед правкой общего файла.
|
||||
- Сохраняйте существующие изменения других участников.
|
||||
- Изменения OpenAPI, миграций, shared Makefile, lockfile и генерации согласуются с одним владельцем общей поверхности.
|
||||
- Generated files обновляйте только через Make targets.
|
||||
- Документируйте разницу между работающим сейчас и целевым поведением.
|
||||
- Не добавляйте локальные пути, секреты и персональные настройки разработчика.
|
||||
Не редактируйте output вручную. Конфигурация генератора находится в `codegen/` потребителя; Go-клиент ML принадлежит backend, Python-модели - ML.
|
||||
|
||||
Для задач по backend, frontend, ML, API, базе и инфраструктуре используйте маршруты в корневом [AGENTS_ROUTING.md](../../AGENTS_ROUTING.md).
|
||||
## Backend и данные
|
||||
|
||||
Предметные типы лежат непосредственно в `internal/domain/`. Usecase зависит от портов, адаптеры реализуют доступ к HTTP, базе и внешним сервисам. `internal/bootstrap/` связывает зависимости и управляет жизненным циклом; `cmd/app/main.go` вызывает его.
|
||||
|
||||
- Добавляйте бизнес-правила в domain/usecase, а преобразование HTTP - в `adapter/primary/http/v1/`.
|
||||
- Для новой инфраструктуры сначала определите нужный порт и адаптер. Сервисы не обращаются к чужим таблицам напрямую.
|
||||
- Изменяйте SQL в `db/queries/`, затем запускайте `make -C backend gen-sqlc`.
|
||||
- Изменение схемы оформляйте новой миграцией в `db/migrations/`; проверяйте ее на отдельной базе. Не переписывайте уже примененные миграции.
|
||||
- Бизнес-изменение и outbox-событие сохраняйте в одной транзакции. Обработчики должны выдерживать повторную доставку.
|
||||
- Повторяющийся код выносите в небольшой helper; значения с предметным смыслом - в именованные константы или конфигурацию.
|
||||
|
||||
Ошибки содержат место и причину: `fmt.Errorf("ProfileUseCase.Update - save profile: %w", err)`. Для ошибки без причины используйте тот же формат без `%w`. HTTP-ответ содержит безопасный problem-код; внутренние ошибки и персональные данные клиенту не передаются.
|
||||
|
||||
Отдельные команды обслуживания перечислены в `make -C backend help`. Миграции, повтор отправки почты, публикация политики и backfill меняют состояние: выбирайте нужное окружение явно.
|
||||
|
||||
## Frontend
|
||||
|
||||
Слои FSD: `app`, `pages`, `widgets`, `features`, `entities`, `shared`. Импорт идет в нижний слой через публичный API слайса; соседние слайсы не связываются внутренними импортами. Общие компоненты и стили находятся в `shared/`, API-типы берутся из генерации.
|
||||
|
||||
Серверное состояние храните в TanStack Query, черновики форм - в состоянии формы. На конфликт версии сохраняйте введенные данные и предлагайте перечитать сервер. Для асинхронных экранов нужны состояния загрузки, пустого результата, ошибки и повторного запроса.
|
||||
|
||||
Проверяйте клавиатуру, фокус, подписи полей и небольшую ширину экрана. Vitest проверяет логику, Playwright - работу интерфейса в браузере.
|
||||
|
||||
## ML и дополнительные сервисы
|
||||
|
||||
ML-команды: `make -C ml help`. Обычные проверки используют Ruff, mypy и pytest; качество модели и реальный inference проверяются отдельно. Веса и данные оценки должны иметь фиксированную версию.
|
||||
|
||||
Runner и labd - отдельные Go-модули. Unit-тесты не заменяют проверку изоляции runner или работу labd на отдельном тестовом LXD-хосте. Их окружения описаны в [runner/](../../runner/README.md) и [labd/](../../labd/README.md).
|
||||
|
||||
## Документация и Git
|
||||
|
||||
README каталога объясняет назначение, запуск и основные команды. Подробности остаются в контракте, исходниках и тематическом руководстве. Не добавляйте в документацию историю выполнения задач или список всех частных тестов.
|
||||
|
||||
Комментарии в коде пишутся по-английски. Документация поддерживается парами RU/EN. Планы и их идентификаторы остаются в локальном `PRD/`; каталог не коммитится. Коммит описывает изменение одной короткой строкой, без авторства ассистента и coauthor trailers.
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
# MVP Lincodex: пакет сдачи
|
||||
|
||||
Проверенный коммит: `c9f029471ed78ce5ec4583009abdc5a4c8c3bd97` (ветка dev, 10.10.2026).
|
||||
|
||||
Выпуск: `mvp-2026-10-10`, собран из `392d117` (тот же код и этот документ). Манифест `deploy/release/mvp-2026-10-10/manifest.json` - локальный артефакт машины, на которой собраны образы (в Git не хранится, см. [манифест выпуска](DEPLOY.md#манифест-выпуска)); ядро `verified`, smoke и браузерный набор пройдены на образах выпуска, восстановление доступно.
|
||||
|
||||
Документ описывает, что входит в минимальный выпуск, как его запустить, чем ограничена демонстрационная категория, что не реализовано и чем выпуск проверен. Подробности вынесены в руководства: [ARCHITECTURE](ARCHITECTURE.md), [DEPLOY](DEPLOY.md), [TESTING](TESTING.md), [SECURITY](SECURITY.md), [COMPANY_QUOTAS](COMPANY_QUOTAS.md) и [frontend](../../frontend/README.md). Контракт HTTP API находится в [api/](../../api/README.md). Утверждения ниже выведены из кода, контракта и этих руководств; запланированное отделено от работающего.
|
||||
|
||||
## 1. Что реализовано
|
||||
|
||||
### Регистрация и вход
|
||||
|
||||
- Регистрация кандидата и работодателя с согласием C1. Адрес подтверждается ссылкой из письма или шестизначным кодом из того же письма; после подтверждения вход возвращает пользователя на сохраненный шаг. См. [регистрацию и подтверждение](ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
|
||||
- Письмо уходит только при `EMAIL_PROVIDER=resend`. При `disabled` регистрация принимается, но подтвердить адрес нечем, и вход отвечает 403 `email_not_verified`. Подготовленные аккаунты демонстрационного стенда подтверждены заранее. См. [почту](DEPLOY.md#2-почта-resend-или-disabled).
|
||||
|
||||
### Кандидат
|
||||
|
||||
- Согласия C1-C5 в настройках. C3 разрешает автоматическую категоризацию; без него доступен запрос ручной оценки через обращение в поддержку.
|
||||
- Профиль заполняется вручную по шагам, без резюме и без ФСП ID. Анкета содержит специализации и самооценку. Главная страница показывает следующий шаг. См. [профиль кандидата](ARCHITECTURE.md#профиль-кандидата).
|
||||
- Проверка навыков в двух режимах (см. [оценивание](ARCHITECTURE.md#оценивание-и-подтверждение-грейда)):
|
||||
- полный тест `demo_basic` Backend Junior с Go: 25 заданий из синтетического банка, срок 72 часа, две рабочие сессии, без практики. Результат сравнивается с порогом версии политики; на демонстрационном стенде пройденный тест получает категорию с основанием `synthetic_demo`, иначе результат `not_confirmed`;
|
||||
- экспресс-тест `demo_express`: три задания; он никогда не назначает грейд, категорию, перцентиль или доказательство и не попадает в историю результатов.
|
||||
- Результаты, история и доказательства навыка доступны кандидату; заявленный грейд всегда отделен от подтвержденного. См. [доказательства](ARCHITECTURE.md#доказательства-навыков).
|
||||
|
||||
### Публикация и видимость
|
||||
|
||||
- Анонимная карточка публикуется только после явного C2 и не содержит имени, контактов и суммы зарплаты. Кандидат видит предпросмотр, строящийся из того же ответа, что и карточка для организаций.
|
||||
- Статус поиска, скрытие отдельных организаций, история изменений и история просмотров карточки и чтений контактов. Карточка показывается организациям только в группе не менее пяти. См. [видимость](ARCHITECTURE.md#видимость-кандидата).
|
||||
|
||||
### Работодатель
|
||||
|
||||
- Организации (аккаунт может владеть несколькими), профиль компании и потребность по шагам с вилкой зарплаты. Потребность хранит версии требований; поиск по версии не меняется после правки. См. [организации](ARCHITECTURE.md#организации-и-членства).
|
||||
- Поиск кандидатов по потребности или по банку с фильтрами: специализация, подтвержденный и заявленный грейд, статус подтверждения, стек, формат работы и совместимость по зарплате. Результат разделен на группы `main`, `near`, `unconfirmed`, а объяснение (компоненты оценки и флаги неизвестного) строит сервер.
|
||||
- Базовый подбор работает без ML: смысловая близость равна нейтральным 0.5 и помечена флагом `ml_unavailable`; при когорте меньше 30 добавляется `cohort_below_30`. См. [подбор и объяснение](ARCHITECTURE.md#подбор-и-объяснение).
|
||||
|
||||
### Приглашения и контакты
|
||||
|
||||
- Организация создает черновик из результата поиска, меняет условия с версиями и отправляет приглашение с вилкой зарплаты в рублях. Отправка тратит место недельной квоты; на потребность действует предел ожидающих приглашений, после отказа действует пауза пары, а неотвеченное приглашение истекает по сроку. См. [черновики](ARCHITECTURE.md#черновики-приглашений), [отправку](ARCHITECTURE.md#отправка-приглашений) и [предел и истечение](ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение).
|
||||
- Доставленное приглашение попадает во входящие кандидата. Кандидат отмечает просмотр, отказывается или принимает его с согласием C4, выбрав поля контактов. См. [просмотр и отказ](ARCHITECTURE.md#просмотр-и-отказ-кандидата) и [принятие](ARCHITECTURE.md#принятие-кандидатом).
|
||||
- Принятие создает разрешение на контакты ровно для этой пары. Организация читает выбранные поля на странице приглашения, и каждое чтение заново проверяет разрешение и видимость. Отзыв C4, отзыв C2, закрытие публикации и скрытие организации закрывают чтение сразу; повторная публикация закрытое разрешение не открывает. См. [чтение и отзыв](ARCHITECTURE.md#чтение-контактов-и-отзыв).
|
||||
|
||||
### Изоляция компаний и холдинги
|
||||
|
||||
- Организационные операции отвечают на чужие идентификаторы тем же отказом, что и на случайный идентификатор. Поиск, приглашения и чтение контактов доступны только владельцу организации.
|
||||
- Организации одного аккаунта образуют холдинг: компании на уровне E0 делят общие квоты (в демонстрационной политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа). Число организаций на аккаунт не ограничено. См. [COMPANY_QUOTAS](COMPANY_QUOTAS.md#пул-холдинга).
|
||||
|
||||
### Уведомления и почта
|
||||
|
||||
- Inbox в обоих кабинетах; единственный продуктовый источник - доставленное приглашение. Запись появляется через outbox, relay и Kafka после фиксации, а не внутри транзакции отправки. См. [внутренние уведомления](ARCHITECTURE.md#внутренние-уведомления).
|
||||
- Письмо о приглашении проходит через outbox и обработчик доставки, а отправляет его отдельный цикл уведомлений (worker в процессе backend); перед каждой отправкой он заново проверяет права получателя и оставляет резерв квоты служебной почте. Тело письма нейтрально и не содержит контактов. См. [отправку продуктовых уведомлений](ARCHITECTURE.md#отправка-продуктовых-уведомлений).
|
||||
- Обращения в поддержку в обоих кабинетах.
|
||||
|
||||
### Гарантии приватности
|
||||
|
||||
- До записи C4 и разрешения организация не получает контакты; карточки, результаты поиска, списки приглашений и уведомления не содержат email, телефона и имени.
|
||||
- Логи сервера, payload outbox, строки inbox и запросы писем не содержат значений контактов и профиля (проверяет интеграционный тест изоляции, см. раздел 5).
|
||||
- Ответы организаций не содержат PDF и сохраненных снимков поиска: таких операций нет.
|
||||
|
||||
## 2. Как запустить
|
||||
|
||||
Все команды выполняются из корня репозитория. Требуются Docker с Compose, GNU make, python3 и openssl; GPU и внешние ключи не нужны. Полная инструкция: [быстрый старт](DEPLOY.md#запуск-mvp-быстрый-старт).
|
||||
|
||||
### Рабочий стенд
|
||||
|
||||
cp .env.example .env # замените каждое replace-this-... и задайте IDENTITY_KEY_SECRET
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl http://localhost:8080/api/v1/healthz
|
||||
|
||||
Открывайте http://localhost:8080 (значение `APP_PUBLIC_URL`). Для писем задайте `EMAIL_PROVIDER=resend`, `RESEND_API_KEY` и `EMAIL_FROM` в окружении сервера. Чистый стенд содержит миграции и стартовую политику; шаги оператора (нужен `DATABASE_URL`):
|
||||
|
||||
1. Опубликовать раздел подбора, без него поиск отвечает 500: `make -C backend policy-publish ARGS='matching --actor operator:<handle>'`. См. [политику подбора](DEPLOY.md#политика-подбора-на-стенде).
|
||||
2. Чтобы пройденный полный тест получал демонстрационную категорию, выставить `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, перезапустить backend и аттестовать открытие категории командой `make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'`. Публикация новой версии политики требует нового открытия и новой аттестации, поэтому выполняйте шаг 1 до начала попыток. См. [демонстрационные категории](DEPLOY.md#демонстрационные-категории-на-стенде).
|
||||
|
||||
Банк заданий на основном стенде не загружен, и руководство DEPLOY описывает его загрузку только в составе seed демонстрационного стенда, поэтому тест на основном стенде начать нельзя. Для показа полного пути используйте демонстрационный стенд.
|
||||
|
||||
### Демонстрационный стенд и маршрут жюри
|
||||
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
|
||||
Команда поднимает отдельный проект на http://localhost:8090, публикует политику с разделом подбора, загружает синтетический банк, аттестует категорию и создает аккаунты `candidate@`, `prepared-1@` - `prepared-6@`, `employer-alpha@` и `employer-beta@` в домене `demo.lincodex.test`; пароль берется из `deploy/demo/demo.env` или `demo.env.example`. Гид жюри открыт по адресу http://localhost:8090/demo; он восьмиминутный и есть только в сборке этого стенда. Маршрут: экспресс-тест и полный тест кандидата, подготовленные кандидаты с опубликованными карточками, потребность и поиск владельца "Альфа", приглашение, принятие с C4 и чтение контактов. См. [демонстрационный стенд](DEPLOY.md#3-демонстрационный-стенд), [маршрут](DEPLOY.md#4-маршрут-демонстрации) и [изолированный стенд](DEPLOY.md#изолированный-демонстрационный-стенд). Сброс: `make -C deploy demo-reset DEMO_MODE=isolated` (отказывает, если на стенде есть обычные аккаунты).
|
||||
|
||||
### Восстановление из манифеста выпуска
|
||||
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=<id>
|
||||
make -C deploy release-up RELEASE_ID=<id>
|
||||
make -C deploy release-manifest-verify RELEASE_ID=<id> RELEASE_VERIFY_PROJECT=<project>
|
||||
make -C deploy demo-seed DEMO_MODE=isolated RELEASE_ID=<id>
|
||||
|
||||
Манифест неизменяем: он фиксирует исходники, lockfiles, Compose-файлы и image ID образов, а `release-up` запускает их без сборки и скачивания и сверяет хеши. Манифест публикуется только для чистого дерева и после успешных smoke и E2E на этих образах. `release-manifest-verify` сравнивает запущенные контейнеры с манифестом. Демонстрационный стенд из манифеста не содержит гида `/demo`, потому что берет фронтенд основного выпуска. Банк оценки в манифесте не снимается (`product_data_status` равен `partial`). См. [манифест выпуска](DEPLOY.md#манифест-выпуска).
|
||||
|
||||
## 3. Ограничения демонстрационной категории
|
||||
|
||||
- Банк заданий небольшой и синтетический: 25 семейств для полного теста и три для экспресс-теста. Семейства проходят штатный конвейер публикации с метками автора и проверяющего, но предметной проверки содержание не проходило.
|
||||
- Пороги не откалиброваны, перцентиль не считается, а адаптивного теста нет. Результат показывает механику, а не измеренную квалификацию.
|
||||
- В API основание категории равно `synthetic_demo` и описано в контракте как демонстрационная категория, не являющаяся проверенным измерением. В интерфейсе по решению владельца продукта она показана как обычное подтверждение (подпись "Результат теста"). API и эта документация сохраняют основание.
|
||||
- Экспресс-тест не назначает грейд ни при каких настройках.
|
||||
- Тексты согласий C1-C5 публикуются миграциями как `demo`, без юридической проверки. Не регистрируйте на демонстрационном стенде реальных людей.
|
||||
|
||||
## 4. Что не реализовано
|
||||
|
||||
Следующее относится к полному продукту и не работает в этом выпуске:
|
||||
|
||||
- практика с кодом (песочница) и адаптивный тест;
|
||||
- финальный раунд торга и встречные предложения: состояние `counter` не создает ни одна операция, повышение зарплаты отвечает 501 `not_implemented`;
|
||||
- назначение интервью и напоминания;
|
||||
- отзыв приглашения организацией и отмена участия кандидатом: обе операции отвечают 501;
|
||||
- роли, кроме владельца, и назначения по потребностям: искать, приглашать и читать контакты может только владелец организации;
|
||||
- PDF-документы и сохраненные снимки выдачи поиска;
|
||||
- рекомендации категорий для потребности: ответ потребности сообщает состояние `pending` или `not_available` с пустым списком;
|
||||
- включенный ML inference: сервис ML запускается отдельно без модели, backend его не вызывает;
|
||||
- интеграция с ФСП: нет ни режима, ни fixture-провайдера, ни обращений к внешнему API;
|
||||
- транспорт SMTP: выбор `EMAIL_PROVIDER=smtp` останавливает backend при запуске;
|
||||
- интеграция с ATS;
|
||||
- сброс пароля, загрузка и разбор резюме, письма о событиях, кроме подтверждения и нового приглашения.
|
||||
|
||||
## 5. Как проверено
|
||||
|
||||
Итог приемки на проверенном коммите (10.10.2026): `make verify` прошел, включая 110 интеграционных тестов и технический smoke; `make -C deploy test-e2e-registration` - 95 passed, 1 skipped; `make -C deploy test-e2e` - 64 passed, 32 skipped; `make -C security install test check` и `make security-images` прошли без блокирующих находок (сканеры запускались в Linux-контейнере, как в CI, потому что их установщик поддерживает только Linux; исключение для CVE-2026-93687 действует до 19.10.2026). Границы каждой проверки описаны в [TESTING](TESTING.md#команды).
|
||||
|
||||
| Проверка | Что подтверждает |
|
||||
| --- | --- |
|
||||
| `make verify` | Генерацию контрактов без расхождений, форматирование, линтеры, типы, сборку, Compose, документацию, backend с race detector, интеграционные тесты на PostgreSQL, Redis, SeaweedFS и Kafka и технический smoke |
|
||||
| `make -C deploy smoke` | Запуск стека, готовность зависимостей и отказы зависимостей; бизнес-сценарий не проверяет |
|
||||
| `make -C deploy test-e2e` | Браузерный набор Playwright на одноразовом стеке с отключенной почтой, включая `mail-unavailable.spec.ts`: пользователь видит, что письмо может прийти позже, и не входит до подтверждения |
|
||||
| `make -C deploy test-e2e-registration` | Регистрацию, подтверждение ссылкой и кодом и вход через локальный Resend-совместимый inbox, а в нем `acceptance-path.spec.ts` |
|
||||
| `acceptance-path.spec.ts` | Минимальный путь на настоящем backend: пять кандидатов, полный тест с категорией `synthetic_demo`, публикация, потребность, поиск с объяснением и фильтром, приглашения, принятие с C4, чтение контактов, отказ, отзыв C2 и отсутствие дубликатов при обновлении и двойном принятии. См. [путь до контактов](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов) |
|
||||
| `TestCompanyIsolationAndRevocationOverHTTP` | Изоляцию компаний и кандидатов, мгновенное закрытие после скрытия, отзыва C4 и C2 и отсутствие контактов в логе, outbox, inbox и запросах писем. См. [тесты организаций](TESTING.md#тесты-организаций) |
|
||||
| `TestInvitationNoticesSurviveRelayAndConsumerRestarts` | Ровно одно уведомление и одно письмо на получателя после перезапусков relay и потребителей и потери offset |
|
||||
| `TestHoldings`, `TestCompanyQuota` | Общий пул квот E0 внутри холдинга и отсутствие превышения при параллельных резервированиях |
|
||||
| `make -C security check`, `make -C security images` | Уязвимости зависимостей, секреты, опасные конструкции и образы; см. [SECURITY](SECURITY.md) |
|
||||
| `make -C deploy check-demo`, `make docs-check` | Охранные проверки целей демонстрационного стенда и структуру документации |
|
||||
| `make -C deploy release-smoke`, `release-e2e` | Те же smoke и браузерный набор на образах выпуска; успешный прогон дает evidence для манифеста |
|
||||
|
||||
Что проверки не доказывают: калибровку оценки, точность подбора, доставку писем через настоящий Resend, работу за HTTPS и production-нагрузку.
|
||||
+27
-35
@@ -1,62 +1,54 @@
|
||||
# Проверки безопасности
|
||||
# Безопасность
|
||||
|
||||
В репозитории есть локальные и CI-проверки известных уязвимостей зависимостей, отдельных рисков конфигурации, секретов и опасных конструкций в исходниках. Они относятся к техническому каркасу. Они не подтверждают полную безопасность и не проверяют будущие сценарии авторизации и обработки персональных данных.
|
||||
Защита данных обеспечивается серверными проверками доступа и границами сервисов. Сканеры проверяют известные уязвимости и выбранные опасные конструкции; они не заменяют проверку бизнес-сценариев или аудит.
|
||||
|
||||
## Команды
|
||||
## Проверки
|
||||
|
||||
Запускайте из корня репозитория:
|
||||
Из корня репозитория:
|
||||
|
||||
```sh
|
||||
make -C security install
|
||||
make -C security check
|
||||
make -C security test
|
||||
make -C security test check
|
||||
make -C security images
|
||||
```
|
||||
|
||||
Для установки нужны Python, uv, Go и доступ к сети. Установщик бинарных файлов Trivy/Gitleaks поддерживает Linux amd64 и arm64. Инструменты размещаются в `security/.bin/`, `.tools/` и `.cache/`; глобальные установки не изменяются. Установщик выбирает текущие стабильные версии Trivy и Gitleaks и сверяет скачанные архивы с SHA256-суммами из upstream. govulncheck устанавливается через `go install ...@latest`. Semgrep использует отдельное окружение uv tool с Python 3.13; uv размещает управляемый Python в `security/.tools/python/`. При следующей установке версии могут измениться; для воспроизведения находки сверяйтесь с выводом установки.
|
||||
|
||||
| Цель | Область проверки |
|
||||
| Инструмент | Текущая область |
|
||||
| --- | --- |
|
||||
| `filesystem` | Trivy проверяет зависимости и конфигурацию репозитория по `trivy/filesystem.yml` |
|
||||
| `secrets` | Gitleaks проверяет отслеживаемые и неигнорируемые файлы, а также всю доступную историю Git по `gitleaks/gitleaks.toml` |
|
||||
| `go` | govulncheck анализирует использование известного уязвимого Go-кода в backend |
|
||||
| `semgrep` | Локальные правила `semgrep/frontend.yml` и `semgrep/python.yml` проверяют исходники frontend и ML |
|
||||
| `rule-test` | Фикстуры Semgrep проверяют ожидаемые срабатывания и допустимые примеры локальных правил |
|
||||
| `test` | Запускает фикстуры правил Semgrep и тесты установки, входов и отчетов Gitleaks, кода ошибки govulncheck и устаревших отчетов |
|
||||
| `check` | Запускает проверки файлов, секретов, Go и Semgrep; выполняет каждую и возвращает ошибку, если хотя бы одна не прошла |
|
||||
| `images` | Собирает образы backend, frontend и ML, затем проверяет каждый точный локальный ID образа через Trivy |
|
||||
| Trivy filesystem | Зависимости, lock-файлы и конфигурация репозитория |
|
||||
| Gitleaks | Отслеживаемые и неигнорируемые файлы, полная доступная история Git |
|
||||
| govulncheck | Использование уязвимого кода в `backend/` |
|
||||
| Semgrep | Локальные правила для `frontend/src/` и `ml/src/` |
|
||||
| Trivy images | Точные локальные ID образов backend, frontend и ML |
|
||||
|
||||
Gitleaks требует полный Git checkout. Отсутствие репозитория или неполная история завершают проверку ошибкой; история не пропускается молча. Текущая проверка файлов берет отслеживаемые Git файлы и неигнорируемые незакоммиченные файлы. Отслеживаемые файлы остаются во входах, даже если Git игнорирует их; игнорируемый локальный `.env` не включается. Удаленные отслеживаемые пути и символические ссылки не входят в текущую проверку; цели ссылок не открываются и не читаются. Проверка истории по-прежнему охватывает все ссылки и находит значения, закоммиченные до игнорирования или удаления файла. Gitleaks копирует текущие входы во временную директорию с доступом только для владельца и завершает проверку ошибкой, если сканер падает или JSON-отчет отсутствует либо поврежден. Значения найденных секретов скрываются в отчетах. Кеши инструментов и результаты сборки исключаются согласно конфигурации; lock-файлы зависимостей приложения остаются входами проверок. Trivy также распознает `requirements-*.txt`, включая `backend/requirements-quality.txt` и `scripts/requirements-codegen.txt`.
|
||||
Проверки не включают отдельные Go-модули и образы runner/labd. Go-линтер backend дополнительно запускает gosec. Для образов нужен Docker; установка требует сеть, Python, uv и Go. Инструменты ставятся локально, а текущие версии сохраняются с отчетами.
|
||||
|
||||
Для проверки образов нужен Docker. Контекст сборки backend - `backend/`, frontend и ML - корень репозитория. Образы получают теги `lincodex-security-<service>:local`; перед сканированием определяется ID каждого образа. Команда не запускает контейнеры и не публикует образы. Проверка зависимостей исходников frontend остается необходимой: итоговый Nginx-образ содержит собранные ресурсы, а не дерево зависимостей разработки.
|
||||
`HIGH`/`CRITICAL` Trivy, включая находки без исправления, блокируют проверку. Находки остальных сканеров и ошибки самих инструментов тоже дают ошибку. Неполная Git-история, пропавший или поврежденный отчет не считаются успехом. Отчеты в `security/reports/` локальные и содержат скрытые значения секретов; не публикуйте их без проверки.
|
||||
|
||||
## Находки и исключения
|
||||
CI вызывает те же Make-цели. Наличие workflow не доказывает успешный запуск на текущем коде; перед выпуском нужны результаты конкретного прогона. Образы проверяются вместе с исходными lock-файлами: статическая сборка frontend сама не содержит всех зависимостей разработки.
|
||||
|
||||
Находки Trivy с уровнем `HIGH` или `CRITICAL` завершают проверку ошибкой, включая уязвимости без опубликованного исправления, если для находки нет действующего адресного исключения. Находки Gitleaks, настроенных правил Semgrep, govulncheck и ошибки самих сканеров также завершают соответствующие цели ошибкой. В конфигурации Go-линтера остается gosec; новые проверки дополняют его.
|
||||
## Исключения
|
||||
|
||||
Перед изменением зависимостей или конфигурации проверьте указанный пакет, установленную версию, затронутый путь и доступное исправление. Отчеты хранятся локально: `security/reports/` исключен из Git. govulncheck использует текстовый вывод, чтобы сохранить собственный код завершения при находках. Trivy сохраняет JSON-отчеты и печатает их таблицы в лог проверки. Ошибка сканирования, отсутствие отчета или ошибка его преобразования сохраняют блокирующий результат.
|
||||
[Trivy ignore](../../security/trivy/ignore.yml) содержит адресное исключение `CVE-2026-93687` для `braces@3.0.3` в lock-файле frontend, до 2026-10-19. Оно согласовано при отсутствии исправления; сопровождающие должны удалить его после обновления или пересмотреть до истечения срока. Это не исключение для всех версий пакета или образов.
|
||||
|
||||
В [security/trivy/ignore.yml](../../security/trivy/ignore.yml) есть одно временное исключение, согласованное владельцем проекта 2026-10-05: `CVE-2026-93687` для `pkg:npm/braces@3.0.3` в `frontend/pnpm-lock.yaml`. На момент согласования исправленной версии не было; исключение разблокирует CI зависимостей до истечения срока 2026-10-19. Ответственные - сопровождающие проекта: исключение нужно удалить после появления исправления или пересмотреть до истечения срока. Trivy автоматически учитывает дату окончания. Файл исключений применяется только к проверке файлов; скрытые из блокирующего результата находки остаются видимыми в JSON-отчете. Проверка образов не изменяется.
|
||||
[Gitleaks allowlist](../../security/gitleaks/gitleaks.toml) ограничивает исключения точными тестовыми примерами, путями и правилами. Дата ручного пересмотра - 2026-11-07; Gitleaks ее не контролирует. Новое исключение требует конкретной находки, причины, ответственного и срока. Не отключайте сканеры и не скрывайте все неисправленные уязвимости ради зеленого CI.
|
||||
|
||||
Восемь исключений Gitleaks относятся только к точным примерам API, тестовым фикстурам, фикстуре release manifest и статическому префиксу ключа Redis rate limit. Для каждого должны совпасть правило, путь в репозитории и полный текст находки. Ответственные - сопровождающие проекта. Вручную пересмотрите исключения или удалите их до 2026-11-07; Gitleaks не проверяет эту дату пересмотра. Описание работы allowlist приведено в официальной [документации Gitleaks](https://github.com/gitleaks/gitleaks#configuration).
|
||||
## Данные и сетевые границы
|
||||
|
||||
Любое следующее исключение ограничивайте конкретной находкой и входными данными, указывайте причину, ответственного и срок действия, затем отдавайте изменение на ревью. Текущая интеграция не обеспечивает автоматический контроль срока одинаково для всех инструментов; там, где его нет, проверяйте срок вручную. Не отключайте сканер целиком и не скрывайте все уязвимости без исправлений ради успешной проверки.
|
||||
- Авторизация, членство компании, согласия, публикация и разрешения на контакты проверяются на сервере при каждом доступе. Кеш, snapshot или скрытая кнопка не заменяют проверку.
|
||||
- Пароли, session tokens, одноразовые коды, контакты, тексты резюме и тела запросов не попадают в логи и labels метрик. Письмо подтверждения передает код только его адресату; ошибки API не раскрывают внутренний текст ошибок.
|
||||
- SeaweedFS остается в отдельной внутренней сети; браузер не получает S3-ключи или прямой доступ к bucket. Не все его внутренние интерфейсы проверяют S3-аутентификацию, поэтому доступ к сети строго ограничен.
|
||||
- Секреты находятся в локальном окружении или secret-файлах, не в Git. Readiness, метрики и административные интерфейсы не публикуются через Nginx.
|
||||
|
||||
## Исходящие запросы и ML
|
||||
|
||||
- GitHub. Проверка репозиториев проектов обращается только к `https://api.github.com`: адрес в профиле принимается только в форме `https://github.com/<owner>/<repo>`, владелец и имя проверяются по шаблонам GitHub и экранируются в путь, базовый origin зашит в коде (тесты подменяют его только внутри пакета), прокси из окружения не используется, TLS 1.2+, таймауты соединения и ответа, редирект допускается только на тот же origin (не больше трех), ответы ограничены 1 MiB, README - 64 KiB. Поэтому пользовательский ввод не может направить сервер на другой хост (SSRF). Проверки выключены по умолчанию (`GITHUB_REPOSITORY_CHECKS_ENABLED`), повторная проверка ограничена на кандидата (`REPOSITORY_CHECK_INTERVAL`), лимит GitHub соблюдается по заголовкам.
|
||||
- Токен. `GITHUB_TOKEN` необязателен, нужен только для чтения публичных данных и отправляется только на `api.github.com`; он не попадает в логи, ошибки, задания и базу. Журнал проверки содержит id задания, попытку, состояние и класс ошибки, но не репозиторий; ключ и payload задания несут только дайджест репозитория.
|
||||
- Данные GitHub. Описание, темы, языки и текст README - недоверенные данные: README превращается в простой текст, хранится только для публичного репозитория, используется только для ранжирования и никогда не выводится, тем более как HTML. Адрес и владелец репозитория не попадают организации ни в карточке, ни в объяснении, ни после C4.
|
||||
- ML. Все маршруты сервиса, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>`: общий случайный токен не короче 32 печатных символов (`ML_SERVICE_TOKEN` у backend, `ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE` у сервиса) сравнивается за постоянное время и не попадает в логи, ответы и сообщения об ошибках; неверный или отсутствующий токен получает 401 `unauthenticated`, а запрос отклоняется до чтения тела. Без токена сервис отвечает только клиентам с loopback, а точка входа `python -m lincodex_ml.serve` отказывается слушать не-loopback адрес; backend без токена не включает семантический подбор. В Compose сервис доступен backend по сети `http://ml:8000`, порт на хосте - loopback; на GPU-хосте он слушает приватный адрес LAN без TLS, поэтому ограничьте порт адресом хоста приложения средствами хоста или сети. `/metrics` тоже требует токен. Backend передает в ML только тексты опубликованной карточки и потребности организации, без контактов и приватного профиля. Веса берутся по lock-файлам с SHA-256, удаленный код моделей не исполняется, pickle не загружается, сервис работает офлайн.
|
||||
GitHub-проверка выключена по умолчанию. Она принимает только публичные ссылки `https://github.com/<owner>/<repo>`, обращается к фиксированному `api.github.com`, ограничивает редиректы, время и объем ответа. Произвольный URL не становится сетевым назначением. README и метаданные остаются недоверенными данными, не исполняются и не отображаются как пользовательский HTML. Токен не сохраняется в заданиях и логах.
|
||||
|
||||
## CI и границы проверок
|
||||
Backend отправляет ML только разрешенную проекцию карточки и потребности, без контактов и приватного профиля. Все маршруты ML, кроме `/healthz` и `/readyz`, требуют bearer-токен; без него сервис допускает только loopback. `/metrics` защищен тем же токеном, но текущий Prometheus scrape ML еще не передает его. Между хостами доступ к порту ML нужно ограничить: токен не шифрует HTTP-трафик.
|
||||
|
||||
CI запускает `make -C security test check` для исходников и `make -C security images` для образов и включает обе проверки в обязательный общий результат. Отчеты загружаются как artifacts со сроком хранения 14 дней, в том числе при ошибке проверки. Gitleaks скрывает значения секретов, но отчеты могут раскрывать пути репозитория и сведения о зависимостях; доступ к artifacts должен это учитывать.
|
||||
|
||||
Локальные правила Semgrep покрывают ограниченный набор случаев для frontend и ML, а не полный аудит приложения. Результаты сканеров зависят от checkout, версий правил, баз уязвимостей, входов сборки и времени запуска. Наличие workflow в репозитории не подтверждает запуск в GitHub или отсутствие находок в текущих файлах. При подготовке релиза фиксируйте фактические результаты; другие границы валидации описаны в [TESTING.md](TESTING.md).
|
||||
Модельные файлы закреплены SHA-256, загружаются локально; удаленный код модели и pickle не исполняются. Ответ модели - данные, а не инструкция для команды, инструмента или изменения прав.
|
||||
|
||||
## VM исполнителя кода
|
||||
|
||||
Исполнитель запускает недоверенный код кандидатов, поэтому в production он работает только в VM LXD `lincodex-runner` (см. [DEPLOY.md](DEPLOY.md#production-vm-исполнителя)). У границы три слоя: nsjail с seccomp, пространствами имен, лимитами cgroup v2 и без сети для программы; отдельное гостевое ядро; ACL моста, который разрешает открыть TCP 8443 только сети приложения и стороне хоста и отбрасывает любое соединение, начатое гостем. В VM есть только ее собственная TLS-пара и токен API. Ключ CA и секреты базы данных, почты, хранилища и identity в нее не попадают, общих папок, сокета Docker и гостевого API (`security.devlxd=false`) у нее нет.
|
||||
В production runner размещается в отдельной VM. Внутри nsjail ограничивает программу через пространства имен, seccomp, cgroup v2 и отсутствие сети. VM не получает секреты базы, почты, хранилища или identity, общие каталоги и сокет Docker. TLS и токен защищают API; сетевые ACL ограничивают доступ к нему и исходящие соединения гостя.
|
||||
|
||||
`make -C deploy check-runner-vm` проверяет скрипт VM без LXD. На хосте приложения `make -C deploy runner-vm-check` проверяет работающую VM, а `make -C deploy runner-vm-a16` запускает в ней набор враждебных программ. Эти проверки не покрывают уязвимости ядра, QEMU, KVM, nsjail и LXD, побочные каналы и сам хост: группа `lxd` равносильна root на хосте, и ее участники могут открыть root-shell в госте через агент LXD. Токен - общий секрет без автоматической ротации: чтобы заменить его, удалите `api-token` из каталога секретов, запустите `runner-vm-secrets` и `runner-vm-install` и передайте backend новое значение. Мониторинга у VM пока нет.
|
||||
`make -C deploy check-runner-vm` проверяет конфигурацию без запуска VM. Проверки работающей VM и изоляции выполняются отдельно по [DEPLOYMENT.md](DEPLOYMENT.md) и [TESTING.md](TESTING.md). Они не доказывают отсутствие уязвимостей ядра, гипервизора или nsjail. Привилегированный dev-контейнер не является production-границей; автоматическая ротация токена и мониторинг VM пока не подключены.
|
||||
+93
-664
@@ -1,715 +1,144 @@
|
||||
# Проверки и оценка качества
|
||||
# Тестирование
|
||||
|
||||
Обычные проверки подтверждают отдельные свойства кода. Они не доказывают точность подбора, валидность грейдов, production latency или готовность продукта целиком.
|
||||
[English](../en/TESTING.md)
|
||||
|
||||
Выбирайте проверки по изменению. Unit-тест проверяет правило, интеграционный тест - реальные зависимости, браузерный E2E - действия пользователя. Команды выполняются из корня репозитория.
|
||||
|
||||
## Команды
|
||||
|
||||
Используйте Make targets из корня:
|
||||
|
||||
make test
|
||||
make check
|
||||
make verify
|
||||
make docs-check
|
||||
|
||||
make test запускает backend, frontend и ML тесты. make check также выполняет проверки API контрактов, форматирование, линтеры, типы, build, Compose, observability и docs-check. make verify последовательно генерирует контракты, проверяет generated drift, запускает root check, API toolchain/backend race и integration проверки, а затем изолированный deployment smoke. Он использует Docker.
|
||||
|
||||
Полезные узкие команды:
|
||||
|
||||
| Команда | Что проверяет |
|
||||
| --- | --- |
|
||||
| make -C api check | Объединение схем, bundles, OpenAPI lint и тесты merge script |
|
||||
| make -C backend test | Go unit suite с race detector |
|
||||
| make -C backend test-fast | Быстрый Go test без race instrumentation |
|
||||
| make -C backend test-int | Go integration tests с Testcontainers/PostgreSQL/Redis/SeaweedFS/Kafka |
|
||||
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries и build |
|
||||
| make -C ml check | Ruff, mypy, pytest и сборку wheel |
|
||||
| make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов |
|
||||
| make -C deploy config | Рендер Compose конфигураций без запуска |
|
||||
| make -C deploy check | Рендер Compose конфигураций, `check-workflows`, который падает, если job `aggregate` в workflow не зависит от всех остальных jobs или не имеет `if: always()`, и `check-release`; см. [Тесты манифеста выпуска](#тесты-манифеста-выпуска) |
|
||||
| make -C deploy smoke | Изолированный технический smoke по service health routes |
|
||||
| make -C deploy test-e2e | Браузерный набор Playwright на изолированном одноразовом стеке |
|
||||
| make -C deploy release-smoke, release-e2e | Тот же smoke и браузерный набор на образах выпуска; успешный прогон записывает evidence для манифеста выпуска |
|
||||
| make -C observability check | Проверку конфигурации и правил alerts Prometheus с их unit-тестами, Loki, Alloy и dashboard JSON |
|
||||
| make -C observability verify-product-metrics | Изолированные стенды core и monitoring: продуктовые метрики в Prometheus и Grafana, отсутствие fixture адреса в метриках и логах Loki; см. [Тесты продуктовых метрик](#тесты-продуктовых-метрик) |
|
||||
|
||||
make -C deploy test-e2e сейчас запускает технический браузерный набор, а не проверку бизнес-сценариев; см. [Браузерный E2E набор](#браузерный-e2e-набор).
|
||||
|
||||
make -C ml check-generated использует datamodel-code-generator --check: расхождение завершает проверку ошибкой, а файл моделей остается неизменным. Перед проверкой обновите bundle через make -C api bundle; для обновления Python-моделей используйте make -C ml generate. Сгенерированные модели не подтверждают наличие inference или поддержку всех возможностей OpenAPI 3.2.
|
||||
|
||||
Проверки безопасности запускаются отдельно: `make -C security check` проверяет исходники, зависимости и секреты, `make -C security test` проверяет фикстуры локальных правил Semgrep, целостность установки и обработку ошибок govulncheck, `make -C security images` собирает и сканирует образы трех сервисов. Сначала установите инструменты через `make -C security install`. Ошибка сканера означает неуспешную проверку, а не отсутствие находок. Требования к Git/Docker, блокирующие находки и отчеты CI описаны в [SECURITY.md](SECURITY.md).
|
||||
|
||||
## Что покрывает текущий каркас
|
||||
|
||||
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, закрытому файловому слою и контролю доступа SeaweedFS (см. [Тесты закрытого файлового хранилища](#тесты-закрытого-файлового-хранилища)), тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), доставкам писем (см. [Тесты доставки писем](#тесты-доставки-писем)), метрикам, API client, ML schema и доступности текущих endpoint. Регистрация и подтверждение email проверяются API integration-тестами; вход, тестирование, поиск, приглашения и работа с файлами пока не реализованы. Подтверждение записывает событие в transactional outbox, но для него нет зарегистрированного продуктового обработчика; обработчик доставки писем проверяется отдельно. Реального model inference как бизнес-результата нет.
|
||||
|
||||
TestEmailVerificationOverHTTP получает токен из Resend fixture после регистрации. Тест проверяет подтверждение candidate и employer, отсутствие сессии и cookie, неизменность состояния при неизвестном, истекшем, замененном или погашенном токене, неверном пароле и отсутствии отложенных данных. Он также проверяет привязку C1 к версии регистрации, отсутствующий, null и чужой Origin, а также лимиты, истечение срока после ожидания блокировки, откат после сбоя outbox и одно событие при параллельном подтверждении. Тест охватывает только API; внешний почтовый провайдер не вызывается. Frontend проверяет отдельный локальный браузерный поток регистрации.
|
||||
|
||||
TestEmailVerificationCodeOverHTTP (`backend/integration_test/email_code_test.go`) берет код и ссылку из одного сообщения фикстуры. Он проверяет, что код подтверждает регистрацию так же, как ссылка; что пять неверных кодов аннулируют токен, после чего правильный код и ссылка не работают; что восемь параллельных неверных кодов засчитываются ровно как пять попыток; что неверный пароль засчитывается; что истекший код не отменяет ссылку; что ссылка и код погашают один токен в любом порядке; что повторная отправка заменяет код; что регистрация, замененная другой регистрацией, не подтверждается своим кодом; что неизвестный адрес и неверный код дают один и тот же отказ; что лимит адреса отвечает 429 после десяти запросов. Тест origin отклоняет чужой Origin до запуска usecase.
|
||||
|
||||
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
|
||||
|
||||
Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket, изоляцию SeaweedFS от frontend (по имени и по адресу в сети хранилища), отказ HTTP API filer, master и volume на запросы не изнутри контейнера SeaweedFS и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. В smoke-стеке relay backend подключается к Kafka, но smoke не проверяет, что он публикует события. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
|
||||
|
||||
## Браузерный E2E набор
|
||||
|
||||
`make -C deploy test-e2e` запускает набор Playwright из `frontend/e2e/` в Chromium на настоящих образах frontend и backend. Нужны Docker и зависимости frontend, установленные через `make -C frontend install`; браузер на хост не ставится. `deploy/scripts/e2e.sh` делает следующее:
|
||||
|
||||
- Читает точную версию `@playwright/test` из `frontend/package.json`, проверяет, что установлена та же версия, и запускает набор в официальном образе `mcr.microsoft.com/playwright:v<version>-noble`, где `frontend/` смонтирован только для чтения.
|
||||
- Поднимает основной стек под уникальным проектом `lincodex-e2e-<random>` со свежими томами и сгенерированным одноразовым env-файлом: случайные пароли, `EMAIL_PROVIDER=disabled`, без настроек почтового транспорта. Переменные оболочки, кроме настроек Docker-клиента, в Compose не попадают. Запуск отказывается переиспользовать существующие проект, сеть или том.
|
||||
- Не публикует host-порт. Контейнер браузера разделяет сетевое пространство контейнера frontend и открывает `http://localhost:8080`, тот же loopback origin, что и `APP_PUBLIC_URL`. Конфигурация Playwright отклоняет base URL вне loopback-хоста.
|
||||
- Запускает Playwright с UID/GID хоста в rootful Docker; в rootless Docker использует container UID 0, который соответствует владельцу каталога артефактов на хосте. Runner удаляет все capabilities, исходники смонтированы только для чтения.
|
||||
- Ждет готовности backend, запускает набор без повторов и возвращает его код завершения; make сообщает о любой ошибке кодом 2.
|
||||
- При любом завершении, включая ошибку и прерывание, удаляет контейнеры, тома, сеть, локально собранные образы и env-файл. Остаются только закешированный образ Playwright и кеш сборки.
|
||||
|
||||
Все браузеры одного прогона обращаются к стенду с одного клиентского адреса: контейнер браузера разделяет сетевое пространство контейнера frontend, и app Nginx видит все запросы с loopback. Поэтому лимит на адрес для `/api/v1/` (20 запросов в секунду с burst 60, `deploy/nginx/nginx.conf` и `deploy/nginx/conf.d/app.conf`) общий для всего набора. 429 от этого лимита означает сбой стенда, а не результат проверяемого сценария; продуктивные лимиты не меняются, их по-прежнему проверяет `deploy/scripts/test_perimeter.py`. Набор укладывается в бюджет по замыслу. `frontend/playwright.config.ts` запускает один воркер. `frontend/e2e/assessment.spec.ts` делает паузу 250 мс после каждого сохраненного ответа полной попытки, потому что кандидат читает каждый пункт. Поиск по реальному банку в `frontend/e2e/match-search.spec.ts` идет первым, в собственном проекте: нефильтрованный поиск по банку возвращает десять записей на группу, поэтому кандидаты, опубликованные более ранними спецификациями, определили бы, какие записи увидит тест. На стенде воспроизведение этого лимита по access-логу дало пик примерно в две трети burst при одном воркере и около десяти запросов до порога при двух.
|
||||
|
||||
Артефакты последнего прогона лежат в `frontend/test-results/e2e/`, который игнорируется Git; путь печатается в конце. В `report/` лежит HTML-отчет (`pnpm exec playwright show-report test-results/e2e/report` из `frontend/`). Для каждого упавшего теста `results/` сохраняет `trace.zip` и снимок экрана (`pnpm exec playwright show-trace <trace.zip>` требует локального браузера; trace.playwright.dev открывает файл без него). После неуспешного прогона `stand.log` содержит логи стека. `E2E_SPEC_DIR=<dir>` запускает спецификации из другого каталога, например из временной копии, на таком же изолированном стеке.
|
||||
|
||||
## Локальный браузерный тест регистрации с почтовым fixture
|
||||
|
||||
`make -C deploy test-e2e-registration` запускает тот же одноразовый браузерный стек с дополнительным `docker-compose.e2e-mail.yml` overlay. Только этот режим собирает backend с Go build tag `e2e`: его Resend-конструктор использует фиксированный адрес `http://mail-fixture:8025/emails`, а Compose передает ему синтетический ключ. Перед Playwright runner отправляет через Compose network одно синтетическое письмо, повторяет запрос с тем же idempotency key и проверяет сообщение в аутентифицированном inbox. Сервис `mail-fixture` принимает Resend-совместимые запросы, поддерживает дедупликацию по ключу и хранит в памяти не более 64 сообщений и 256 запросов размером до 32 KiB каждый. Его inbox требует bearer-аутентификацию, отдает только письма для запрошенного `to` и доступен изнутри стека. Сеть регистрации помечена internal, fixture не подключен к сети хранилища, а опубликованных host-портов нет; запросы не могут уйти во внешний почтовый сервис. Очистка удаляет контейнеры и inbox.
|
||||
|
||||
Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8025/__e2e/inbox` и синтетический `E2E_MAILBOX_TOKEN=local-e2e-mailbox-token`. Тест запрашивает `GET $E2E_MAILBOX_URL?to=<urlencoded email>` с `Authorization: Bearer $E2E_MAILBOX_TOKEN`; ответ содержит `messages` с полями `id`, `to`, `subject`, `text` и `html`. Registration-only tests должны пропускаться без `E2E_MAIL_FIXTURE=1`, поскольку стандартный `test-e2e` и `release-e2e` его не задают. Тесты не должны выводить содержимое письма или ссылку с одноразовым токеном. В этом режиме runner отключает трассировку Playwright. Обычный `test-e2e` по-прежнему задает `EMAIL_PROVIDER=disabled`, а `release-e2e` использует release-образы без fixture и не пишет evidence для mail-fixture образа. Режим отказывается запускаться с `LINCODEX_RELEASE_TAG`.
|
||||
|
||||
Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Бизнес-тесты используют синтетические данные в свежем стеке каждого прогона: регистрацию через публичный API и отдельно описанный тестовый fixture для scope согласий. Реальные данные не используются.
|
||||
|
||||
`frontend/e2e/mail-unavailable.spec.ts` выполняется только в обычном `test-e2e`, стенд которого задает `EMAIL_PROVIDER=disabled`, и пропускается при `E2E_MAIL_FIXTURE=1`. На настоящем backend он регистрирует кандидата (202 `accepted`) и проверяет, что шаг ждет письмо ("Запрос принят", "Письмо может прийти не сразу") и нигде не говорит, что письмо отправлено или доставлено. Подобранный код и поддельная ссылка получают 400 `verification_token_invalid`; верный пароль получает 403 `email_not_verified` с сообщением в форме; после этого `GET /api/v1/identity/sessions/current` и `GET /api/v1/me/profile` отвечают 401, а `/candidate` показывает страницу входа. Строку доставки браузер не видит: то, что она остается `pending` без попыток, пока транспорт выключен, проверяет подтест `EMAIL_PROVIDER=disabled` в `TestServiceMailSending`.
|
||||
|
||||
Обычный технический набор не проверяет сценарии кандидата и работодателя, кроме неподтвержденной регистрации в `mail-unavailable.spec.ts`, успешный вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium и программы чтения с экрана. Его проверки заглушками основного пути (состояния, фокус и переполнение) описаны в разделе [Состояния и доступность основного пути](#состояния-и-доступность-основного-пути). CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-<n>` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate.
|
||||
|
||||
Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись.
|
||||
|
||||
С появлением шага кода тот же набор проверяет подтверждение каждой регистрации кандидата и работодателя шестизначным кодом из письма: сначала неверный код, затем перезагрузка страницы, на которой пароль запрашивается снова, и проверка, что браузерное хранилище не содержит пароль. Отдельный тест оставляет ссылку запасным путем: истекшая ссылка ведет на шаг кода, который отправляет новое письмо, и ссылка из этого письма подтверждает регистрацию.
|
||||
|
||||
В этом же режиме runner перед браузером запускает `/consent-fixture` из тестового backend-образа. Команда доступна только с Go build tag `e2e`, требует `E2E_CONSENT_FIXTURE=1` и через домен и транзакционные порты создает синтетического подтвержденного кандидата, C1/C2 и два C4 для разных компаний. Совпадение тестового адреса с существующим аккаунтом останавливает запуск. Обычный и release-образы не содержат команду и не включают этот флаг. Сценарий `frontend/e2e/consent-management.spec.ts` использует обычный вход и реальные API согласий: отдельную выдачу C3, отзыв C2 и одного C4, сохранение другого scope, перезагрузку и C1 request со статусом из ответа. Отказ сервера для проверки UI задается управляемым 403; успешные изменения идут в PostgreSQL. Синтетические invitation IDs в fixture не доказывают реализацию принятия приглашений. Трассы и автоматические снимки отключены; явный снимок показывает только синтетические данные.
|
||||
|
||||
Та же команда создает второго синтетического кандидата для `frontend/e2e/privacy-visibility.spec.ts`: действующие C1 и C2, один C4 для первой из двух новых компаний и три записанных чтения карточки (просмотр карточки и чтение контактов первой компанией, просмотр карточки второй). Чтения вставлены через порт приватности, потому что путь чтения организацией требует результатов поиска, которых еще нет; они не доказывают этот путь. На настоящем backend набор подтверждает статус поиска без публикации, публикует после явного шага C2, сверяет предпросмотр владельца с ответом API, скрывает одну компанию и возвращает ее, отзывает C2 и проверяет объяснение закрытия, снова выдает C2 без открытия карточки и публикует заново только с клавиатуры; в режиме с почтовой фикстурой свежезарегистрированный кандидат с двумя заявленными специализациями и без теста публикуется и видит "Грейд не подтвержден" для каждой. Группа с подменой API показывает подтвержденный Backend рядом с неподтвержденными специализациями, подписи основы и калибровки доказательств, пустые истории, неудачное сохранение с сохранением черновика и отозванный C2. Ни один тест не читает карточку как работодатель, поэтому немедленная потеря доступа скрытого работодателя в браузере не проверяется.
|
||||
|
||||
`frontend/e2e/profile-edit.spec.ts` проходит шаги ручного профиля на 360 px после реальной регистрации (переход "Далее" с фокусом на заголовке, блокировка шага без подтверждения пересечения, "Назад" без потери данных), подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля.
|
||||
|
||||
`frontend/e2e/candidate-home.spec.ts` состоит из двух частей. В режиме с почтовой фикстурой кандидат проходит регистрацию, профиль только с именем (без привязки ФСП ID), анкету и повторный вход: главная ведет к профилю, затем к анкете, затем к тесту, показывает заявленный уровень отдельно от пустой подтвержденной категории и совпадает с ответом `GET /me/assessment-availability` после обновления страницы. Сохраненный шаг при этом остается "Согласия": сервер переводит его дальше только из соответствующего шага. Вторая часть работает и в обычном `test-e2e`: она подменяет ответы API (`page.route`) и проверяет только отображение состояний главной - категория и ссылки на результат и приватность, открытая карточка и статус поиска, отсутствие категории и пустая история, неудачная попытка, ошибка чтения с повтором, отказ в доступе, сбой чтения приватности, истекшая сессия. Она не доказывает поведение backend и не заменяет проверку присвоения категории на реальном стенде, которую эта спецификация не выполняет. Скриншоты для просмотра (360 и 1280 px) содержат только синтетические данные.
|
||||
|
||||
`frontend/e2e/company-management.spec.ts` создает компанию, повторяет запрос после потери ответа с тем же ключом и телом, изменяет профиль и сравнивает предпросмотр с API. Управляемые ответы проверяют восстановление после CSRF-ошибки, конфликт версии и задержанный ответ. Реальный отзыв выполняет отдельный `company-fixture`: Go build tag `e2e`, явный флаг, случайный bearer token на каждый прогон, без опубликованного порта и только во внутренней сети. Утилита проверяет два синтетических подтвержденных employer-аккаунта, добавляет владельца-преемника и отзывает исходного владельца в одной транзакции, сохраняя ограничение обязательного владельца. Браузер с прежней cookie проверяет отказ реального API и исчезновение компании из своей директории. Контрольный endpoint отсутствует в обычном backend и release-образе; его URL и токен передаются только тестовому процессу через `E2E_COMPANY_FIXTURE_URL` и `E2E_COMPANY_FIXTURE_TOKEN`.
|
||||
|
||||
## Состояния и доступность основного пути
|
||||
|
||||
`frontend/e2e/minimal-path-a11y.spec.ts` проверяет состояния, путь с клавиатуры и привязку ошибок на экранах входа, начала проверки знаний, профиля кандидата, входящих приглашений и отдельного приглашения кандидата. Отказы создаются перехватом запросов, поэтому на стенде не нужны данные: ответы HTTP 500 и 403, обрыв соединения, пустые и запрещенные ответы. Каждый экран с заглушками проверяется при 360, 768 и 1280 px на горизонтальное переполнение; проверка с настоящим backend покрывает 360 и 768 px. Каждый элемент, до которого доходит Tab, должен соответствовать `:focus-visible` и рисовать контур фокуса. Часть с перехватом запускается и в `make -C deploy test-e2e`, и в `make -C deploy test-e2e-registration`. Один тест с настоящим backend запускается только в режиме регистрации, потому что ему нужны почтовый и анкетный fixture.
|
||||
|
||||
Остальные экраны основного пути покрыты существующими спецификациями: поиск кандидатов и список совпадений работодателя (`match-search.spec.ts`: неуспешный поиск с повтором, отказ в поиске, пустой результат, подтвержденный и заявленный грейд текстом, достижение элементов с клавиатуры при каждой ширине), составление приглашения (`invitation-compose.spec.ts`: ошибки, привязанные к полям, потерянный ответ на отправку с повтором под тем же ключом, переполнение при 360, 768 и 1280 px), регистрация и подтверждение (`auth-registration.spec.ts`), профиль и анкета (`profile-edit.spec.ts`, `questionnaire.spec.ts`).
|
||||
|
||||
Чек-лист основного пути. Каждый пункт проверяет спецификация, указанная в скобках; результат - итог последнего прогона этой спецификации.
|
||||
|
||||
- Вход [`minimal-path-a11y.spec.ts`]: Tab доходит до обоих полей и кнопки отправки с видимым контуром при 360, 768 и 1280 px. Пустая отправка помечает оба поля `aria-invalid` и связывает каждое поле с его текстом через `aria-describedby`. Неуспешный ответ сохраняет введенную почту и оставляет фокус в форме. Пока ответ ожидается, поле пароля остается в фокусе и только для чтения; оно не отключается, потому что отключенное поле теряет фокус.
|
||||
- Профиль кандидата [`minimal-path-a11y.spec.ts`]: текст загрузки, пока профиль загружается; сообщение с кнопкой повтора после неуспешной загрузки; без повтора после отказа в доступе.
|
||||
- Начало пробной проверки кандидата [`minimal-path-a11y.spec.ts`]: сообщение с кнопкой повтора после неуспешного чтения доступности; кандидат без специализации видит пустое состояние со ссылкой на анкету.
|
||||
- Входящие приглашения кандидата [`minimal-path-a11y.spec.ts`]: текст загрузки; ошибка сервера или обрыв соединения дают сообщение с кнопкой повтора, которая работает с клавиатуры; пустое состояние; без повтора после отказа в доступе; каждая карточка называет компанию, роль и состояние текстом.
|
||||
- Приглашение кандидата [`minimal-path-a11y.spec.ts`]: сообщение с кнопкой повтора после неуспешной загрузки; неуспешный отказ сохраняет выбранную причину и комментарий и переводит фокус на сообщение; состояние "отклонено" показано текстом.
|
||||
- Проверка на телефоне с настоящим backend [`minimal-path-a11y.spec.ts`, режим регистрации]: неотправленный числовой ответ переживает перезагрузку при 360 px, а сохраненная копия удаляется, когда ответ принят.
|
||||
- Список совпадений работодателя и составление приглашения: см. спецификации выше; страница составления дополнительно проверяется при 768 px.
|
||||
- Эти проверки не покрывают: вывод для программ чтения с экрана, контраст контура фокуса и масштаб выше 200 процентов. В этом проходе они вручную не проверялись.
|
||||
|
||||
Неотправленный ответ хранится в `sessionStorage` той же вкладки браузера под ключом, который называет попытку и задание. На сервер он не отправляется. Перезагрузка восстанавливает его, только если значение подходит заданию; сохраненное значение больше 64 KiB не сохраняется; заблокированное или переполненное хранилище оставляет ответ только в форме. Принятый ответ удаляет сохраненную копию. Ответы, принятые сервером, после перезагрузки берутся с сервера.
|
||||
|
||||
## Тесты манифеста выпуска
|
||||
|
||||
`make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile или backend/Dockerfile.demo-seed перестают закреплять Go 1.26.9 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что:
|
||||
|
||||
- манифест не копирует значения окружения, labels и локальные пути, а две генерации различаются только `generated_at`;
|
||||
- evidence засчитывается только для того же тега, коммита и отпечатка рабочего дерева, а evidence и записи сборки с неверной структурой не используются;
|
||||
- компонент получает `verified` только при evidence для его точного image ID, ML, monitoring и отсутствующие компоненты никогда не проверены, а выпуск остается непроверенным без smoke и E2E на текущих образах, на грязном дереве, при скачанном core-образе без registry digest, отсутствующем lockfile или Dockerfile, другой версии Go в бинарнике или другой версии Node в образе сборки;
|
||||
- `release-build` не пишет запись сборки, если коммит или рабочее дерево изменились во время сборки;
|
||||
- отпечаток рабочего дерева временного Git-репозитория не зависит от настроек diff и переводов строк, учитывает неотслеживаемые файлы, пропускает игнорируемые и не меняет настоящий индекс;
|
||||
- поиск секретов находит блоки ключей, токены, учетные данные в URL, локальные пути, имена пользователя и хоста и значения переменных, похожих на секреты, в том числе как подстроки и в base64, не печатая их;
|
||||
- сравнение с запущенными контейнерами сообщает о другом digest, незапущенном и неизвестном сервисе;
|
||||
- образ demo seed собирается с закрепленными базовыми образами под своим профилем, записывается, но никогда не считается проверенным, и удерживается по image ID; его отсутствие блокирует только восстановление демонстрационного стенда, другая версия Go в его бинарнике оставляет выпуск непроверенным, а demo override закрепляет core-сервисы и seed за точными image ID и digest и отказывает при отсутствующем образе, измененном демонстрационном overlay или манифесте без записи восстановления стенда;
|
||||
- запись `seed` хеширует исходники demo seed без тестов, и ее версия меняется вместе с ними, но не с тестовым файлом.
|
||||
|
||||
Тест не собирает образы и не запускает контейнеры. Полный путь: `release-build`, `release-smoke` и `release-e2e`, `release-manifest`, `release-up`, `release-manifest-verify` и `release-manifest-check`; см. [DEPLOY.md](DEPLOY.md#манифест-выпуска).
|
||||
|
||||
## Bootstrap интеграционных тестов
|
||||
|
||||
Общий helper находится в `backend/integration_test/bootstrap_test.go`. Вызов `env := bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, дожидается готовности адаптеров и возвращает окружение с конфигурацией и клиентами. Для проверки одного адаптера используйте `bootstrap(t, postgresService)`, `bootstrap(t, redisService)` или `bootstrap(t, seaweedfsService)`. Можно передать несколько сервисов.
|
||||
|
||||
Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой. Если `DOCKER_HOST` недоступен, Testcontainers пробует также Docker context и стандартные сокеты, поэтому одного неверного `DOCKER_HOST` недостаточно, чтобы смоделировать отсутствие Docker.
|
||||
|
||||
Bootstrap делает максимум три попытки запуска контейнера всего и только при точной ошибке настройки сети rootless Docker для host-порта, оканчивающейся на `bind: address already in use` (`EADDRINUSE`). Перед повтором он завершает частичный контейнер, возвращенный неудачным запуском; ошибка очистки прекращает повторы. Прочие ошибки запуска или готовности, а также ошибки проверок самого теста не повторяются. Повтор касается только подготовки тестов и не меняет настройки Docker или сети хоста.
|
||||
|
||||
Bootstrap поднимает инфраструктуру и клиенты. Если выбран PostgreSQL, он применяет все встроенные миграции тем же runner, что и старт сервиса. `postgres_helpers_test.go` добавляет `env.newPool` для пула к этой базе, `env.createIsolatedDatabase` для отдельной базы в том же контейнере, когда тест меняет всю схему (например up, down и повторный up), `env.newPoolWithMaxConns` для тестов конкурентности, которым нужно одно соединение на транзакцию, и `truncateTables` для сброса общих таблиц между последовательными подтестами. Тесты получают транзакцию из unit of work только через `postgres.TransactionForIntegrationTest`, который компилируется только с build tag `integration`. Тестовые агрегаты живут в собственной схеме, которую создает тест, а не в продуктовых миграциях. HTTP-сервер приложения, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS.
|
||||
|
||||
Kafka не входит в `bootstrap(t)` и запускается только для тестов, которые выбирают `bootstrap(t, kafkaService)`. Используется тот же образ `apache/kafka:latest`, что и в Compose, с теми же настройками KRaft, включая `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. Клиентский listener объявляется на динамическом порту хоста, трафик между брокерами и контроллером остается на loopback контейнера, а данные и объявленные в образе volume размещаются в tmpfs, поэтому тестовый брокер не оставляет volume. Bootstrap заполняет `env.Config.KafkaBrokers` и создает `env.KafkaAdmin` на основе `kadm` из franz-go.
|
||||
|
||||
Helpers находятся в `kafka_helpers_test.go`. `env.createKafkaTopic(ctx, t, partitions)` создает топик с уникальным случайным именем и до создания регистрирует его удаление в `t.Cleanup`, поэтому топик удаляется и после падения теста. Брокер не создает топики по запросу: тест сам создает каждый нужный ему топик. `env.newKafkaClient(t, options...)` возвращает клиент `kgo`, который закрывается по завершении `t`. У `produceKafkaRecords` и `env.consumeKafkaRecords` ограниченные таймауты; consumer читает партиции с начала без consumer group, поэтому смещения группы не остаются. Контейнер останавливается и удаляется в cleanup теста, который вызвал bootstrap, в том числе после падения. `env.pauseKafka(ctx, t)` замораживает брокер через `docker pause` и возвращает функцию, которая его возобновляет; cleanup тоже возобновляет брокер. Приостановленный брокер сохраняет порт и принимает соединения, но не отвечает, что моделирует зависший брокер. Остановленный и снова запущенный контейнер получил бы новый порт на хосте, за которым не следуют ни объявленный listener, ни клиенты, а его топики в tmpfs пропали бы.
|
||||
|
||||
## Тесты закрытого файлового хранилища
|
||||
|
||||
Unit-тесты в `backend/internal/usecase/files/` используют хранилище в памяти, которое, как HTTP-хранилище объектов, фиксирует объект, как только получило заявленное число байтов. Они покрывают проверку политики, формат ключа и отказ для ключей другого namespace или сформированных клиентом, очистку имени файла, лимит заявленного размера, источник длиннее или короче заявленного (хранилище не получает полное тело, ключ удаляется), очистку после отмены контекста вызывающим и после потерянного ответа, сообщение об ошибке очистки, SHA-256, сохраненное тело, которое отличается от своего размера, идемпотентное удаление, закрытие ответа при каждом отказе `Open` и уникальность и корректность объявленных namespace. Тесты адаптера в `backend/internal/adapter/secondary/seaweedfs/` проверяют, что загрузка и скачивание дольше `SEAWEEDFS_TIMEOUT` завершаются, а зависшие заголовки ответа и недоступный endpoint по-прежнему дают ошибку в пределах этого ограничения.
|
||||
|
||||
Bootstrap SeaweedFS использует тот же entrypoint и флаги, что и Compose, и дополнительно публикует порты filer, master и volume, чтобы тесты могли их проверить. Сеть хранилища Compose он не моделирует; эту границу проверяет smoke. `TestPrivateFileStoreAgainstSeaweedFS` в `backend/integration_test/files_store_test.go` использует `bootstrap(t, seaweedfsService)` и реальный адаптер:
|
||||
|
||||
- записывает и читает синтетический объект и пустой объект, проверяя содержимое, размер, тип и digest;
|
||||
- отправляет неподписанные запросы и ожидает 403 от S3 для чтения объекта (в том числе с query, похожим на presigned), перечисления bucket, загрузки и удаления, а также 401 от filer для чтения объекта, перечисления и загрузки и от master для назначения volume и удаления collection; после этого объект по-прежнему читается;
|
||||
- получает file ID внутри контейнера и ожидает 401 от volume на чтение без токена и на запись с подписанным токеном, который вернул master;
|
||||
- проверяет, что неверный secret не открывает, не загружает и не удаляет файлы и не выдается за отсутствие объекта;
|
||||
- открывает, частично читает и закрывает объект больше раз, чем допускает лимит соединений адаптера, с долгим timeout хранилища, поэтому незакрытое тело ответа заблокировало бы цикл;
|
||||
- отклоняет загрузки больше лимита, длиннее или короче заявленного размера и перечисляет namespace отдельным подписанным клиентом, чтобы показать отсутствие частичных объектов;
|
||||
- удаляет объект дважды и затем получает `files.ErrNotFound`.
|
||||
|
||||
Проверки идут с хоста через опубликованные порты, поэтому запросы приходят не изнутри контейнера SeaweedFS, как от другого участника сети хранилища. gRPC- и admin-порты не проверяются; оставшийся риск описан в [ARCHITECTURE.md](ARCHITECTURE.md#закрытое-файловое-хранилище).
|
||||
|
||||
## Тесты relay outbox
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают конверт записи, ключ и заголовки, а также ошибку для некорректного payload без его цитирования (`internal/adapter/secondary/kafka/`), публикацию и создание топика, которые завершаются ошибкой в пределах таймаута публикации плюс 2 секунды запаса на планирование, когда брокер недоступен (тесты проверяют затраченное время), преобразование неизвестного топика в `ErrEventDestinationMissing`, сравнение существующего топика с настроенной раскладкой, общее расписание backoff с jitter и без него (`internal/worker/retry/`), проходы relay, которые отмечают только подтвержденные события, повторы после неудачных `Prepare` и проходов, отсутствие backoff после прохода, который опубликовал часть пачки, пока ядовитое событие стоит первым в каждой пачке, повторный `Prepare` после отсутствующего назначения, не больше одного чтения размера очереди за интервал, проход в работе, который завершается после отмены, проход, отмененный таймаутом остановки, остановку во время backoff (`internal/worker/outboxrelay/`), настройки relay и топика, включая фактор репликации и `min.insync.replicas` по умолчанию брокера (`config/`), ошибки базы только с SQLSTATE и таймауты, которые округлились бы до отсутствия ограничения (`internal/adapter/secondary/postgres/`), счетчик relay и gauge-метрики очереди и приложение, которое запускает relay вместе с серверами и останавливает его вместе с ними (`internal/bootstrap/`).
|
||||
|
||||
`TestOutboxRelay` в `backend/integration_test/outbox_relay_test.go` использует `bootstrap(t, postgresService, kafkaService)`, пишет события через transactor с тестовым агрегатом и последовательно выполняет случаи, у каждого свой топик:
|
||||
|
||||
- Зафиксированное событие публикуется в документированном конверте с ключом и заголовками, и заполняется `published_at`.
|
||||
- Сбой Kafka: при приостановленном брокере бизнес-транзакция все равно фиксируется, проход relay завершается ошибкой в пределах таймаута публикации, оба события остаются в ожидании, бизнес-строки не тронуты. После возобновления брокера relay публикует оба события, и потребитель получает их с их `event_id`.
|
||||
- Сбой между публикацией и отметкой: обертка publisher действительно публикует, а затем отменяет проход, как при убитом процессе; строка остается в ожидании, новый relay публикует ее снова, и в топике две записи с одним `event_id`.
|
||||
- Конкурирующий захват: пока один захват держит самые ранние события двух агрегатов, второй захват через пул с `lock_timeout` 500 ms получает только третий агрегат, не ожидая блокировок и без версии 2 первого агрегата; следующий проход получает версию 2.
|
||||
- Два relay работают, пока 12 параллельных writer фиксируют по 8 версий своего агрегата. Публикуются все события, каждый агрегат остается в одной партиции, а первая доставка каждой версии идет в порядке `aggregate_version`. Обертка publisher добавляет 10 ms к каждой публикации, чтобы проходы relay пересекались; тест пишет в лог, сколько событий опубликовал каждый relay.
|
||||
- Остановка при приостановленном брокере и таймауте публикации 30 секунд: relay останавливается не раньше таймаута остановки в 1 секунду и не позже 5 секунд после него, поэтому проход мог завершить только таймаут остановки; его событие остается в ожидании, и ни одно соединение не остается занятым.
|
||||
- Таймаут простоя: захват, callback публикации которого 2 секунды игнорирует свой контекст, при `idle_in_transaction_session_timeout` 300 ms завершается ошибкой SQLSTATE 25P03; событие остается в ожидании, и ни одно соединение не остается занятым.
|
||||
- `Backlog` возвращает ноль для пустого outbox и два ожидающих события с положительным возрастом после двух записей.
|
||||
- `Prepare` создает топик с настроенным числом партиций, фактором репликации брокера по умолчанию и `min.insync.replicas` на уровне топика и повторно принимает существующий топик.
|
||||
|
||||
Набор работает с одним брокером и одним PostgreSQL. Он не измеряет пропускную способность и задержку, и не покрывает переключение брокеров и репликацию. Обработчики событий описаны в разделе [Тесты обработчиков событий](#тесты-обработчиков-событий).
|
||||
|
||||
## Тесты обработчиков событий
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают runtime обработчиков с поддельными источником, хранилищем и обработчиком (`internal/worker/eventconsumer/`): записи `applied`, `duplicate` и `ignored`, зафиксированные в порядке получения; сбои хранилища, которые повторяются сверх лимита попыток без dead letter, а offset фиксируется только после успеха хранилища; обработчик, который все время падает, повторяется ровно `MaxAttempts` раз не чаще минимального backoff, а затем уходит в dead letters с ID и типом события, размером значения и SHA-256, пока следующая запись применяется; `ErrEventRejected` и panic, которые уходят в dead letters после одной попытки без цитирования значения panic; невалидную запись, которая уходит в dead letters без вызова обработчика, причем commit ждет, пока две неудачные записи dead letter не пройдут; остановку, которая бросает зависший обработчик после grace без фиксации его и всего после него; запись, которая завершается в пределах grace и фиксируется, тогда как следующая не начинается; отсутствие повторов и dead letters во время остановки; backoff после неудачных чтений; commit, который PostgreSQL отвергает после того, как обработчик проглотил ошибку, считается попыткой и заканчивается `retries_exhausted`; конфликт сериализации при commit повторяется как попытка; panic в `Handles` уходит в dead letters без цитирования значения; начало пачки фиксируется сразу после dead letter, до начала следующей записи; счетчики сбоев `poll` и `commit`; очистку причины. Тесты адаптера PostgreSQL проверяют классификацию отвергнутого, конфликтного и сетевого сбоя commit и то, что ошибки обработчика сохраняют идентичность без сообщения PostgreSQL. Они же покрывают декодирование конверта и его согласованность с producer, каждое отвергнутое правило конверта без цитирования значения и учет commit участника группы, включая отказ для завершенных записей, которые не являются для каждой партиции началом последнего чтения без пропусков (`internal/adapter/secondary/kafka/`), настройки обработчиков и бюджет ребалансировки, включая описанное в документации значение по умолчанию 42,5 секунды (`config/`), счетчики обработчиков (`internal/adapter/secondary/prometheus/`), а в `internal/bootstrap/` - случаи пропуска, один обработчик на handler, отказ для повторяющихся и недопустимых имен, зарегистрированный обработчик доставки, значения меток, совпадающие с подготовленными метриками, и приложение, которое запускает обработчик вместе с серверами и возвращается только после того, как он перестал читать.
|
||||
|
||||
`TestEventConsumer` в `backend/integration_test/event_consumer_test.go` использует `bootstrap(t, postgresService, kafkaService)`. Его обработчик существует только в тесте: он пишет одну строку на примененное событие в `consumer_test.effects`, таблицу без уникального ключа, которую создает тест, поэтому второй эффект остался бы виден. Последовательные случаи, каждый со своими топиком и группой:
|
||||
|
||||
- Один ID события доставлен трижды, дважды в партицию 0 и один раз в партицию 1, рядом с другим событием: группа фиксирует обе партиции, у каждого события ровно одна строка эффекта и один маркер, а счетчики показывают 2 `applied` и 2 `duplicate`.
|
||||
- Два обработчика соревнуются за одно событие без Kafka: каждый читает одну и ту же запись из источника в памяти. Первый держит незафиксированный маркер внутри обработчика, пока тест не увидит в `pg_stat_activity`, что вставка маркера второго ждет блокировку; затем первый фиксируется. Итог: один эффект, `applied` у первого и `duplicate` у второго, причем второй не вызывает обработчик.
|
||||
- Та же гонка, в которой обработчик первого падает после того, как второй начал ждать: первый откатывается, второй применяет событие, а повтор первого находит маркер. Одна строка эффекта.
|
||||
- Перезапуск до commit: обработчик пишет эффект и блокируется дольше grace остановки в 300 ms, как процесс, убитый до commit. После остановки нет ни строки эффекта, ни маркера, ни зафиксированного offset группы. Новый обработчик в той же группе получает запись, применяет ее один раз и фиксирует offset 1.
|
||||
- Падение после commit в базе, но до commit offset: эффект и маркер фиксируются напрямую, затем запись читается. Она становится `duplicate`, обработчик не вызывается, offset фиксируется.
|
||||
- Невалидная запись, за которой в той же партиции идет валидная: одна строка dead letter с offset 0, ID события из заголовка, классом `invalid_record`, нулем попыток, размером значения и SHA-256 и причиной, которая не цитирует значение; валидное событие применяется; фиксируется offset 2; счетчик `dead_lettered` равен 1; за 500 ms новых dead letters не появляется.
|
||||
- Обработчик, который всегда падает на одном событии, с 3 попытками и backoff 200 ms: ровно 3 попытки не чаще чем через 100 ms и в пределах 5 секунд, dead letter `retries_exhausted` с ID и типом события и ошибкой обработчика, ни одной строки эффекта этого события, потому что каждая попытка откатилась, следующее событие применяется, фиксируется offset 2, счетчик сбоев обработчика равен 3, и за 500 ms новых попыток нет.
|
||||
- Жесткое падение до commit: обработчик пишет эффект, читает PID своего backend и завершает его через `pg_terminate_backend`, как это сделали бы упавший процесс или оборванное соединение. Backend исчезает из `pg_stat_activity`, не остается ни строки эффекта, ни маркера, ни зафиксированного offset, а новый участник группы применяет событие один раз.
|
||||
- Обработчик, который выполняет `SELECT 1 / 0`, игнорирует ошибку и возвращает nil: PostgreSQL отвергает каждый commit, обработчик насчитывает 3 попытки обработчика и ни одного сбоя хранилища, пишет dead letter `retries_exhausted`, фиксирует offset 1 и не оставляет ни эффекта, ни маркера.
|
||||
- Повторная запись dead letter: одна и та же запись, записанная дважды, оставляет одну строку со вторым исходом; другое значение на той же позиции получает свою строку.
|
||||
- Передача партиции между двумя участниками одной группы: commit первого участника всегда падает, и он держит запись, пока присоединяется второй; тест ждет состояния группы `PreparingRebalance`, отпускает запись и ждет, пока группа не станет стабильной с одной партицией у каждого участника. У каждого из четырех событий ровно один эффект, первый участник обработал оба события первого раунда до ребалансировки, второй не получил ничего из первого раунда переданной партиции (ее позиция зафиксирована при отзыве, единственным оставшимся путем commit) и не насчитал дубликатов, первый участник после потери партиции не пытался ни фиксировать, ни обрабатывать ее записи, а после выхода первого участника offsets группы равны 2 в обеих партициях, то есть переданная партиция не перемотана назад.
|
||||
- Событие, добавленное в outbox через transactor, опубликованное relay и прочитанное обработчиком: декодированное событие совпадает со строкой outbox, значит producer и consumer одинаково понимают конверт.
|
||||
|
||||
`TestPostgresMigrations` дополнительно проверяет, что миграция 00005 создает и удаляет обе таблицы обработчиков. Набор использует один брокер, один PostgreSQL и тестовые обработчики. Он не измеряет пропускную способность, не покрывает ребалансировку под нагрузкой или с более чем двумя участниками, переключение брокеров, исключение участника после rebalance timeout и не проверяет доставку alerts; у продуктового обработчика свои [тесты доставки писем](#тесты-доставки-писем).
|
||||
|
||||
## Тесты доставки писем
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают модель доставки и путь ее создания:
|
||||
|
||||
- `internal/domain/`: content hash учитывает версию, тему, обе части и границы между частями; содержимое, которое не отправит ни один транспорт или которое относится к другому виду, отклоняется; измененное сохраненное тело не проходит проверку целостности; новая доставка начинается в `pending` со сроком в момент создания, версией 1, ключом `delivery/<id>` и необязательным исходным событием; каждый исход попытки, примененный к `pending`, `waiting_quota` и `unknown`, дает описанный статус, номер попытки, версию, время и ID провайдера, в том числе `waiting_quota` без известного сброса, а `accepted` и `rejected` отклоняют любую следующую попытку; несогласованные результаты попытки отклоняются; `WaitForQuota` переводит `pending` и `waiting_quota` в ожидание с известным или неизвестным сбросом без попытки, отклоняет `unknown`, конечные доставки и время раньше последнего изменения, а следующая попытка не может быть раньше него; `Rebind` до первой попытки меняет только аккаунт провайдера и версию, а после нее отклоняется; сохраненные строки, нарушающие инвариант, отклоняются; запрос письма принимает только вид уведомления и текст, который можно сохранить; вывод `fmt` и `slog` доставки, ее содержимого и запроса письма никогда не показывает адрес, тему, тело, текст запроса или токен.
|
||||
- `internal/usecase/notification/`: запрос сохраняет текст под ID агрегата события, а payload события содержит только `mail_request_id` и `kind`; некорректные запросы ничего не записывают; обработчик сохраняет одну доставку под ID запроса с исходным событием, адресом аккаунта, сформированным содержимым, настроенным аккаунтом провайдера и временем часов и удаляет запрос; то же событие повторно не находит запрос; существующая доставка под ID запроса принимается для того же получателя и вида и отклоняется в остальных случаях; сломанные события (другая версия схемы или агрегат, некорректный payload, данные после объекта, ID запроса, не равный ID агрегата, вид письма с токеном) и текст, который отклоняет шаблон, отклоняются без цитирования payload; исчезнувший запрос, исчезнувший аккаунт и неподтвержденный адрес пропускаются со строкой лога, которая называет только ID доставки и события; ошибки хранилища, включая аккаунт, удаленный между чтением и вставкой, остаются повторяемыми и сохраняют запрос; ни одна ошибка и строка лога не содержит адрес, тему или тело.
|
||||
- `internal/adapter/secondary/postgres/`: ошибки ограничений доставок и запросов писем переводятся в свои sentinel (`deliveries_content_immutable` и `delivery_attempts_immutable` - в `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` - в `ErrDeliveryProviderPinned`, внешние ключи на пользователей - в `ErrUserNotFound`), а любая другая ошибка PostgreSQL, например нарушение CHECK, сохраняет только SQLSTATE и имя ограничения без message и detail.
|
||||
- `internal/usecase/notification/mailtemplate/`: результат рендеринга переводится в сохраняемое содержимое с тем же видом, версией, частями и hash.
|
||||
- `config/` и `internal/bootstrap/`: `EMAIL_ACCOUNT` по умолчанию равен `default`, принимает метки до 64 символов и отклоняет пустые, со смешанным регистром, похожие на ключ и слишком длинные значения, не повторяя их; bootstrap регистрирует ровно обработчики `notification_delivery` и `notification_inbox` и отклоняет некорректную метку аккаунта.
|
||||
|
||||
`TestMailDelivery` в `backend/integration_test/delivery_test.go` использует `bootstrap(t, postgresService, kafkaService)` и настоящие usecase запроса, обработчик, relay, runtime обработчиков и хранилища. Последовательные случаи:
|
||||
|
||||
- Одно событие обрабатывается дважды: запрос для подтвержденного аккаунта записывается в бизнес-транзакции, relay публикует его событие, строка снова помечается неопубликованной, как после сбоя до фиксации `published_at`, и relay публикует ее второй раз с тем же ID события. Обработчик фиксирует offset 2 и считает одну запись `applied` и одну `duplicate`; в базе ровно одна доставка: адресована аккаунту, сформирована версией `notification.v1`, закреплена за настроенным аккаунтом провайдера, называет событие своим источником и находится в `pending` без попыток, а запросов писем не остается.
|
||||
- Изменение шаблона после создания: первый запрос сохраняется с `notification.v2`. Обработчик с тестовым renderer, изображающим более позднюю версию `notification.v3`, сохраняет второй запрос с новой версией, а повтор первого запроса под другим именем обработчика находит запрос уже обработанным и ничего не сохраняет. Первая доставка, прочитанная через новый пул, сохраняет тему, части и hash `notification.v2`, а прямой `UPDATE` ее тела завершается ошибкой `deliveries_content_immutable`.
|
||||
- Сохранение после перезапуска: один пул записывает попытку `unknown` с кодом провайдера и подсказкой ожидания с долями миллисекунды, проигрывает повторную запись той же попытки с `ErrDeliveryVersionConflict`, записывает попытку `accepted` с ID письма у провайдера и закрывается. Новый пул и хранилище читают доставку как `accepted` с этим ID, двумя попытками и версией 3, а обе строки попыток - ровно в записанном виде, подсказку ожидания до наносекунды; следующая попытка отклоняется, а `UPDATE` попытки завершается ошибкой `delivery_attempts_immutable`.
|
||||
- Перенос и ожидание квоты: доставка без попыток переносится на другой аккаунт провайдера и переводится в `waiting_quota` с неизвестным сбросом, повторная запись по устаревшей версии получает конфликт версии, строк попыток нет; после попытки `Rebind` отклоняется domain, а прямой `UPDATE` аккаунта провайдера завершается ошибкой `deliveries_provider_pinned`.
|
||||
- Уведомление на неподтвержденный адрес не сохраняет доставку, удаляет свой запрос и записывает в лог ID доставки.
|
||||
- Запрос, аккаунт которого удален, теряет строку запроса вместе с аккаунтом; затем обработчик не сохраняет доставку и записывает в лог ID доставки.
|
||||
- Очистка неподтвержденных аккаунтов пропускает аккаунт, строку доставки которого держит другая транзакция, удаляет его после снятия блокировки, и вместе с ним удаляются его ожидающий запрос и доставка, созданная прямо через репозиторий, как будут создаваться письма с токеном.
|
||||
|
||||
Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. `TestMailDelivery` не отправляет почту и проверяет обработчик продуктовых уведомлений. `TestEmailVerificationOverHTTP` проверяет письмо подтверждения и подтверждение адреса через Resend fixture, но не обращается к внешнему провайдеру. Для сброса пароля нет теста доставки, потому что этот сценарий пока не реализован.
|
||||
|
||||
## Тесты квот почты
|
||||
|
||||
Unit-тесты (`make -C backend test`) проверяют правила квот без базы:
|
||||
|
||||
- `internal/domain/`: окна суток и месяца для момента времени - календарные периоды UTC независимо от его часового пояса: полночь UTC относится к новым суткам, а наносекунда до нее - к старым, местное время после местной полуночи может еще относиться к предыдущим UTC-суткам, сброс суток 28 февраля обычного года и 29 февраля високосного приходится на 1 марта, а декабрь сбрасывается в январь следующего года; лимиты отклоняют ноль, отрицательные значения и суточный лимит больше месячного.
|
||||
- `config/` и `internal/bootstrap/`: `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по умолчанию равны 100 и 3000 для `resend` и `disabled`; `smtp` без любого из них не запускается и принимает явно заданные значения; сниженное значение принимается как настроено для любого провайдера; пустое значение считается незаданным; ноль, отрицательные, нецелые значения, значения вне диапазона и суточный лимит больше месячного отклоняются без вывода секретов; bootstrap не запускается с нулевой квотой.
|
||||
- `internal/adapter/secondary/mail/resend/`: 429 `daily_quota_exceeded` дает `QuotaPeriod` `day` с ожиданием до полуночи, а `monthly_quota_exceeded` дает `month` без ожидания.
|
||||
- `internal/usecase/notification/`, со счетчиком и журналом в памяти и поддельными часами:
|
||||
- `QuotaGate.PrepareSend` допускает отправки до суточного лимита, а следующую переводит в `waiting_quota` до 00:00 UTC и не считает ее; после полуночи допускает ее. При заполненном месяце (с 31 декабря на 1 января) и при заполнении обоих окон ждет начала месяца.
|
||||
- Доставку, которую последним изменил экземпляр с часами на 5 мс впереди, уже после полуночи, откладывает с этим временем изменения и без ошибки.
|
||||
- Применяет сниженный лимит к `smtp` так же, как к любому транспорту; отклоняет доставку, закрепленную за аккаунтом без квоты, и ничего для нее не резервирует.
|
||||
- Возвращает доставку `unknown` без изменений с моментом сброса и отклоняет конечную доставку.
|
||||
- Повтор в пределах 24 часов повторно использует открытое резервирование, даже когда сутки иначе заполнены; отказ этого повтора резервирование сохраняет; после окна повтор считается заново. Шлюз `smtp`, у которого нет дедупликации провайдера, считает каждый повтор.
|
||||
- `SettleSend` оставляет резервирование для `accepted` и `unknown` и возвращает его при ошибке `Send` и любом исходе `rejected`. Повторный расчет возвращает резервирование один раз.
|
||||
- Ответ о суточной квоте отмечает сутки и возвращает полночь, о месячной - отмечает месяц и возвращает его конец. Ответ без окна откладывает только доставку по подсказке или без времени, а окно, которое провайдер назвал заполненным, возврат не открывает.
|
||||
- Отмечается окно, текущее на момент расчета: суточный отказ 31 октября отмечает только сутки и оставляет ноябрь открытым; резервирование в 23:59:59, рассчитанное через 5 мс после полуночи, отмечает новые сутки; подсказка, вычисленная по часам провайдера на 5 мс впереди, все равно дает ровно полночь.
|
||||
- `ReportQuotaUsage` пишет расход и лимиты и предупреждает о других метках аккаунта.
|
||||
- `DeliveryStatusReader.LatestForUser` возвращает вид, статус и время изменения, а `WaitingUntil` только для `waiting_quota`. Он спрашивает только про указанный аккаунт, без доставки ничего не возвращает и отклоняет нулевой аккаунт и неизвестный вид.
|
||||
- Журналы не содержат адреса, темы или тела.
|
||||
|
||||
`TestMailQuota` в `backend/integration_test/mail_quota_test.go` использует `bootstrap(t, postgresService)`, настоящие transactor, хранилище доставок и репозиторий квот и поддельные часы. Каждый случай начинается с пустых таблиц:
|
||||
|
||||
- Конкурентность: 12 отправителей, каждый со своим соединением и транзакцией, одновременно вызывают `PrepareSend`. На окнах без строк (создание строк тоже конкурирует) при суточном лимите 10 разрешение получают ровно 10; после 7 последовательных отправок из следующих 12 разрешение получают ровно 3. Каждая остальная доставка сохраняется в `waiting_quota` с `next_attempt_at` на ближайшие 00:00 UTC, а оба счетчика заканчивают на 10. Без блокировки строк случай падает: допускаются все 12.
|
||||
- Полночь и граница месяца: при лимитах 2 в сутки и 3 в месяц с 30 октября 22:00 UTC третья отправка ждет до 31 октября 00:00 UTC, за секунду до этого все еще ждет, а в полночь проходит; четвертая ждет 1 ноября, потому что месяц заполнен, и тогда проходит. Строки суток и месяца содержат 2, 1, 1 и 3, 1.
|
||||
- Сниженный лимит и SMTP: шлюзы собираются из `config.LoadFromEnv`. После 4 отправок через Resend с лимитом по умолчанию лимит, сниженный до 3, откладывает следующую отправку до полуночи. `smtp` без настроек квот не загружается; с 2 и 2 он допускает две отправки через relay и откладывает третью до начала месяца, а доставка Resend под шлюзом `smtp` завершается ошибкой `ErrQuotaNotConfigured` и не меняет счетчиков.
|
||||
- Уточнение по провайдеру: отказ `temporary` возвращает свое резервирование. Отказ `daily_quota_exceeded` при локальном счете 1 из 100 сохраняет доставку в `waiting_quota` до полуночи с одной попыткой, поднимает строку суток до 100 с `provider_exhausted_at`, после чего шлюз сам откладывает следующую доставку. После полуночи отказ `monthly_quota_exceeded` поднимает строку месяца до 3000 и откладывает доставки до 1 ноября.
|
||||
- Удаление аккаунта: три принятые отправки дают 3 из 3; удаление аккаунта каскадно удаляет его доставки и попытки, счетчики сохраняют 3, а доставка другому аккаунту в тот же день ждет до полуночи.
|
||||
- Порядок блокировок, детерминированно: строка месяца лежит в heap раньше строки суток, а запись идет в сессиях с `enable_indexscan=off`, поэтому сканирование следует порядку heap, как в воспроизведенной взаимоблокировке. Третья транзакция держит строку суток; резервирование и возврат встают за ней в очередь в обоих порядках, затем блокировка снимается. Ни один не получает ошибку взаимоблокировки, а расход сходится. Если убрать упорядоченную блокировку из `Settle`, случай падает с SQLSTATE 40P01.
|
||||
- Порядок блокировок, ограниченная нагрузка: 60 раундов, в каждом одновременно стартуют возврат вторых суток, возврат первых суток с отметкой вторых через полночь и два резервирования вторых суток в сессиях с порядком heap. Ни один раунд не возвращает ошибку.
|
||||
- Журнал: ошибка транспорта, рассчитанная дважды, возвращается один раз. Резервирование неизвестной попытки повторно используется повтором через час и не используется после 24-часового окна. В журнале остаются 2 открытые строки, 1 возвращенная и 2 с исходом.
|
||||
- Статус для пользователя: аккаунт без писем ничего не получает; после одного допущенного и одного отложенного уведомления он видит `waiting_quota` до полуночи; другой аккаунт и другой вид ничего не получают.
|
||||
- Отчет при запуске: при расходе под меткой `old-label` и под настроенной меткой отчет через `postgres.MailQuotaStore` пишет расход настроенного аккаунта и предупреждает об `old-label`.
|
||||
- База отклоняет неизвестный вид периода, месяц, который начинается не с первого числа, отрицательный расход, неверную метку аккаунта, резервирование, у которого сутки вне его месяца, и неизвестный исход.
|
||||
|
||||
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор квот не вызывает транспорт; worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, покрыт тестами отправки служебной почты ниже.
|
||||
|
||||
## Тесты отправки служебной почты
|
||||
|
||||
Модульные тесты (`make -C backend test`) покрывают:
|
||||
|
||||
- `domain`: `Delivery.CheckServiceMail` называет первое нарушенное правило (нет токена, назначение, владелец, использован, отозван, истек ровно в свой срок, регистрация сдвинулась, адрес подтвержден, адрес изменен) и оставляет актуальное письмо подтверждения или сброса отправляемым; `Delivery.Cancel` работает из `pending` и `waiting_quota`, отклоняет `unknown` и конечные статусы, не оставляет попытки и переживает восстановление; уведомление не может нести ID токена; названия статусов не содержат утверждения о доставке человеку.
|
||||
- `usecase/notification`: `ServiceMailSender` против хранилищ в памяти с правилом версии и lease хранилища PostgreSQL, квоты шлюза в памяти и транспорта по сценарию. Каждый результат транспорта дает правильное состояние доставки, срок и эффект на квоту (принято, постоянный отказ и отказ запроса, временный отказ после первой паузы, более длинная подсказка провайдера, ответ провайдера о дневной квоте до полуночи UTC, ответ о квоте без сброса, unknown, транспорт, ответивший без исхода, нет транспорта, прерванный вызов, неверное сообщение); каждая причина отмены достигается без вызова транспорта и резервирования; заполненная локальная квота откладывает доставку без вызова и отправляет ее при сбросе; результат, который не удалось сохранить, сохраняет lease, повторяется три раза, а затем его подхватывает замена с тем же ключом без двойного подсчета; попытка, потерянная за пределами окна идемпотентности или у транспорта без дедупликации, записывается как unknown и не повторяется; доставка, чей хеш содержимого не совпадает, отменяется как `content_invalid` и сообщается без вызова транспорта; строка, которая сбоит по собственной вине (нечитаемая по причине, отличной от несовпадения хеша, нарушенное правило домена при чтении состояния), считается, отодвигается расписанием повторов, чтобы доставка за ней отправилась, и после трех сбоев отменяется как `processing_failed`; временные ошибки (тайм-аут, отмена, deadlock, сеть, EOF, отсутствие настройки квоты) возвращаются worker и никогда не считаются и не отменяют строку, сколько бы ни повторялись; ошибка `Send` без ответа отодвигает строку без счета; приостановленный счет отодвигает строки без счета; успешный проход очищает счетчик; сбой не записывается для строки, которую держит другой worker; окно идемпотентности считается от первого запроса при повторных потерях worker и с часовым запасом; отзыв между захватом и вызовом учитывается; результат отбрасывается, если lease потерян во время вызова; вызов ограничен lease за вычетом бюджета расчета; jitter ограничен и подменяем; письма, сохраненные, пока транспорта не было, переносятся на настроенный аккаунт, а доставка другого аккаунта остается нетронутой; журнал никогда не содержит адрес, токен или ссылку. `ServiceMailer` сохраняет доставку, привязанную к токену, с ID токена, токеном во fragment ссылки и без `?token=`, безвредно повторяется и отклоняет токен не того назначения до рендеринга. `RetryPolicy` удваивает паузу до максимума и учитывает более длинную подсказку.
|
||||
- `worker/mailsender`: отмененные доставки считаются по причине; предохранитель приостанавливает счет сбоев, когда подряд падают три разные строки, и возобновляет после успеха, а повторный сбой одной строки его не включает; сбойная строка заставляет цикл ждать по backoff; gauge равен true только пока работает цикл, холостой проход ждет интервал опроса, за обработанной доставкой сразу идет следующий проход, а отсутствие транспорта, прерванный вызов и сбой базы вызывают паузу вместо вращения вхолостую.
|
||||
- `adapter/secondary/postgres`: только классы SQLSTATE 22 и 23 совпадают с `ErrRowFault`; deadlock, serialization, соединение, ресурсы, остановка и внутренние ошибки - нет.
|
||||
- `adapter/secondary/prometheus`: у `lincodex_mail_sender_cancelled_total` каждая причина существует с нулем, а произвольный label отклоняется; `lincodex_mail_sender_running` существует со значением 0 и следует за `SetMailSenderRunning`; каждый статус доставки, включая `cancelled`, существует с нулем.
|
||||
- `adapter/secondary/mail/resend`: loopback-конструктор принимает только http URL на loopback-хосте, поэтому ключ и письма развертывания нельзя направить через него на другой хост; `resendfixture` отвечает как Resend (принимает, повторяет исходное сообщение для повторного ключа и тела, отклоняет другое тело под тем же ключом, проигрывает заданные ошибки).
|
||||
- `bootstrap`: нет worker без транспорта или базы; цикл запускается и останавливается вместе с приложением, а gauge следует за ним.
|
||||
- `observability/prometheus/tests`: `LincodexMailDeliveriesOverdue` молчит без gauge, пока он равен 0 и для очереди из одних уведомлений (возраст 0), и срабатывает, пока какой-либо экземпляр сообщает 1; `LincodexMailCancelledBroken` срабатывает на `content_invalid` и `processing_failed` и молчит для причин от действий пользователя (`make -C observability check`).
|
||||
|
||||
`TestServiceMailSending` в `backend/integration_test/mail_sender_test.go` использует `bootstrap(t, postgresService)`, настоящие транзакционный слой, хранилища, шлюз квот и usecase отправки, настоящий транспорт Resend, направленный на локальную имитацию, и фиктивные часы. Подтесты делят базу и начинают с пустых таблиц:
|
||||
|
||||
- Служебное письмо для синтетического аккаунта без записи согласия любого назначения ставится вместе с токеном в одной транзакции и принимается имитацией: один вызов провайдера с ключом `delivery/<id>`, адресом и ссылкой с токеном во fragment; доставка `accepted` с ID сообщения провайдера, одной принятой попыткой, одним посчитанным получателем и без оставшегося lease, аккаунт видит статус `accepted`, а второй проход ничего не делает. Журнал не содержит ни адреса, ни токена.
|
||||
- Письмо сброса пароля для синтетического аккаунта без C2 принимается имитацией: один вызов с ключом `delivery/<id>`, адресом и ссылкой `/reset-password` с токеном во fragment; журнал не содержит адреса и токена.
|
||||
- Письмо подтверждения уходит, даже если C2 выдан и отозван, пока письмо ждет worker: проверка читает только токен и аккаунт, а имитация получает ровно один вызов.
|
||||
- Worker, который держит доставку, не пускает к ней другого: имитация отвечает медленно, проход второго worker холостой, пока запрос первого в пути, и имитация получает ровно один вызов, а база - одну попытку.
|
||||
- Четыре worker одновременно разбирают очередь из восьми доставок: восемь вызовов провайдера под восемью разными ключами, ни один не повторен, восемь принятых доставок по одной попытке, восемь посчитанных получателей.
|
||||
- Worker, остановившийся после отправки (база отказывает при сохранении ответа), заменяется после истечения его lease: два вызова под одним ключом, второй - повтор, одно сообщение у провайдера, одна попытка, открытое резервирование использовано повторно, поэтому получатель считается один раз. За пределами 24-часового окна замена записывает попытку unknown и не вызывает провайдера.
|
||||
- Доставка с хешем содержимого, испорченным ручной правкой, отменяется как `content_invalid` на версии 2 без вызова провайдера, а следующая за ней доставка отправляется в следующем проходе.
|
||||
- Строка, которая сбоит по своей причине (тема с переводом строки нарушает правила домена, поэтому строку нельзя восстановить, хотя хеш цел), считается и отодвигается на минуту, пока доставка за ней отправляется, сбоит снова в каждый срок и отменяется как `processing_failed` на третьем сбое с очищенными телами; ошибка транспорта без ответа отодвигает строку на минуту без счета, с возвращенным резервированием и доставкой в `pending`.
|
||||
- Сбой, записанный worker, чей захват откатился, не трогает строку, которую держит другой worker, а несчитаемый сбой оставляет `failure_count` равным 0.
|
||||
- Три потерянных подряд worker не скрывают возраст первого запроса: доставка становится `unknown`, когда `first_send_started_at` старше 24 часов, и провайдер в четвертый раз не вызывается.
|
||||
- Lease - несколько секунд по часам базы; чужой worker не может записать попытку или заблокировать строку; `RecordClaimedAttempt` проходит для владельца.
|
||||
- При 5000 просроченных строк уведомлений план захвата использует `deliveries_due_idx` и не использует последовательное сканирование (`EXPLAIN`).
|
||||
- Очередь из одних уведомлений не создает возраст самой ранней ожидающей доставки; служебное письмо создает.
|
||||
- Тела письма с токеном очищаются, когда оно принято или отменено, и токен больше не встречается ни в одной строке; ожидающее письмо вручную очистить нельзя; очищенная строка не может получить тело обратно или потерять метку; аккаунт по-прежнему видит свой статус.
|
||||
- Токен, отозванный повторной отправкой, уже использованный токен, истекший токен, повторно зарегистрированный аккаунт, уже подтвержденный адрес, измененный адрес и токен другого назначения завершают доставку как `cancelled` с соответствующей причиной, без попытки, без lease, без следующей попытки, без резервирования и без вызова провайдера; аккаунт видит `cancelled`; следующий проход холостой. Удаленный аккаунт уносит свою доставку.
|
||||
- Письмо подтверждения, отозванное до отправки, отменяется как `token_revoked` без вызова провайдера и без попытки; аккаунт провайдера доставки не меняется, тело очищается, а журнал не содержит адреса, токена, ссылки и ID аккаунта.
|
||||
- Ответы провайдера: 503 `service_unavailable` оставляет доставку в `pending` со сроком через минуту, проход до срока холостой, повтор в срок использует тот же ключ и принимается; 500 дает `unknown` без следующей попытки и без повтора через сутки; 403 `validation_error` дает `rejected`.
|
||||
- Квота: локальный лимит один в сутки переводит вторую доставку в `waiting_quota` до полуночи UTC без вызова провайдера, аккаунт видит ожидание и его конец, а доставка отправляется при сбросе; ответ провайдера `daily_quota_exceeded` откладывает доставку до следующей полуночи.
|
||||
- Служебный worker никогда не берет продуктовое уведомление; его отправляет полоса уведомлений (`TestProductNoticeIsSentOnceByItsOwnWorker`).
|
||||
- `EMAIL_PROVIDER=disabled`: с транспортом disabled проход сообщает, что канал недоступен, доставка остается нетронутой на версии 1, lease и резервирование освобождены, до имитации ничего не доходит, цикл с ним делает не больше четырех проходов меньше чем за секунду, а gauge равен 1, пока он работает, и 0 после; с транспортом то же письмо переносится на настроенный аккаунт и принимается.
|
||||
- Схема отклоняет отмененную доставку без причины, причину у другого статуса, половину lease, lease у конечной доставки, уведомление, привязанное к токену, смену привязки токена и удаление токена, на который ссылается доставка; удаление аккаунта убирает оба.
|
||||
|
||||
`TestDeliverySendingMigration` откатывает и заново применяет миграцию 00012 поверх отмененной и очищенной доставки сброса пароля: прежняя схема хранит ее как `rejected` с заглушкой в теле, удаляет токены сброса и новые столбцы, а миграция применяется снова. `TestPostgresMigrations` покрывает общий путь вверх, вниз и снова вверх.
|
||||
|
||||
`make -C backend lint` также запрещает импорт `resendfixture` и вызов `resend.NewLoopbackSender` вне файлов `_test.go` (depguard и forbidigo в `backend/.golangci.yml`).
|
||||
|
||||
Ни одна проверка не вызывает настоящий API Resend: единственный провайдер - имитация, поэтому эти тесты доказывают протокол, на котором говорит транспорт, и правила доставки, но не поведение Resend, доставляемость и реальную квоту аккаунта.
|
||||
|
||||
## Тесты продуктовых уведомлений
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают:
|
||||
|
||||
- `domain`: `Delivery.CheckInvitationNotice` решает в описанном порядке (нет получателя или адрес не подтвержден, адрес изменился, приглашение отсутствует или принадлежит другой организации, на приглашение ответили, оно истекло или прошло срок ответа, организация скрыта, публикация отозвана, уведомление без субъекта), и решает первое нарушенное правило, поэтому неподтвержденный адрес важнее скрытой организации; `MailSubject` принимает только известные виды с полными ID и не печатает идентификаторов; субъект может быть только у уведомления; `MailQuotaLimits.WithReserve` сохраняет долю каждого окна и отказывает в резерве, который не оставляет места; три причины прав разбираются и есть в наборе метрик с нулем.
|
||||
- `config`: резерв служебной почты по умолчанию равен пятой части каждого лимита квоты (20 и 600 на тарифе Resend Free), явный ноль сохраняется, а резерв отрицательный или достигающий своего лимита отклоняется с сообщением, которое называет настройку.
|
||||
- `adapter/secondary/prometheus`: `lincodex_notification_sender_running` есть со значением 0, следует за `SetNotificationSenderRunning` и не сдвигает gauge служебного цикла; причины прав есть со значением 0 в `lincodex_mail_sender_cancelled_total`.
|
||||
- `bootstrap`: нет worker уведомлений без транспорта или базы данных, а цикл уведомлений запускается и останавливается вместе с приложением, и его gauge следует за ним.
|
||||
- `observability/prometheus/tests`: `LincodexMailCancelledBroken` молчит на `rights_revoked`, `recipient_ineligible` и `source_closed` (`make -C observability check`).
|
||||
|
||||
`TestProductNotice*` в `backend/integration_test/product_notification_test.go` используют `bootstrap(t, postgresService)`, изолированную базу с настоящей отправкой приглашения и настоящим notifier, обработчик `DeliveryHandler`, запущенный над сохраненным запросом, настоящий отправитель уведомлений с фикстурой Resend в качестве транспорта и фальшивые часы. Каждая верхнеуровневая функция работает в своей изолированной базе, поэтому счетчики квоты не смешиваются; подтесты правил прав делят одну базу:
|
||||
|
||||
- `TestProductNoticeIsSentOnceByItsOwnWorker`: уведомление о доставленном приглашении отправляет полоса уведомлений один раз, с нейтральным текстом, который не называет ни организацию, ни кандидата и ведет во входящие; служебный worker ничего не берет (пустой проход, без вызова провайдера); второй проход пуст; в логах нет ни адреса, ни ID кандидата, ни handle карточки.
|
||||
- `TestProductNoticeRightsAreCheckedBeforeEverySend`: кандидат, который скрыл организацию между отправкой и worker, письма не получает, уведомление отменяется как `rights_revoked` без вызова провайдера, тела очищаются, следующий проход пуст, адреса в логах нет; адрес, который больше не подтвержден, отменяется как `recipient_ineligible`; уведомление без субъекта отменяется как `source_closed` с очищенным телом; приглашение, прошедшее срок ответа, отменяется как `rights_revoked`. Подтест со сроком сдвигает часы, поэтому идет последним.
|
||||
- `TestProductNoticeReserveLeavesServiceQuotaToServiceMail`: при дневном лимите 10 и резерве 8 полоса уведомлений отправляет два уведомления и паркует третье в `waiting_quota` до следующей полуночи UTC, без вызова провайдера и без цикла впустую; затем письмо подтверждения уходит под полным лимитом, и за день учтены три получателя.
|
||||
- `TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers`: четыре отправителя одновременно разбирают шесть уведомлений; провайдер получает шесть вызовов, и каждое уведомление принято после одной попытки.
|
||||
- `TestProductNoticeClaimReadsItsOwnDueIndex`: при 5000 строках служебной почты план захвата уведомлений использует `deliveries_product_due_idx` и не делает последовательного чтения (`EXPLAIN`).
|
||||
|
||||
Эти тесты доказывают правила прав и механику полосы на локальной фикстуре. Они не решают продуктовые вопросы из раздела [Отправка продуктовых уведомлений](ARCHITECTURE.md#отправка-продуктовых-уведомлений), например, должна ли отозванная публикация отменять ожидающее уведомление.
|
||||
|
||||
`TestInvitationNoticesSurviveRelayAndConsumerRestarts` в `backend/integration_test/notification_restart_test.go` использует `bootstrap(t, postgresService, kafkaService)` с той же фикстурой и проводит две настоящие отправки приглашений через outbox, relay, топик Kafka с одной партицией и потребители `notification_inbox` и `notification_delivery`, собранные так же, как в bootstrap. Relay публикует все четыре события и погибает до фиксации отметки; потребители их применяют. Затем перезапущенный relay публикует те же event ID повторно, и перезапущенные потребители в тех же группах считают каждую повторную запись дубликатом; потребители в новых группах, как после потери offset, тоже перечитывают весь топик как дубликаты. После каждого этапа у каждого получателя ровно одна строка в `notification_inbox_events` и одна доставка уведомления, dead letter нет; после этого полоса уведомлений отправляет каждому получателю одно письмо.
|
||||
|
||||
## Тесты заданий по сроку
|
||||
|
||||
Unit-тесты (`make -C backend test`) проверяют runtime заданий с хранилищем в памяти, которое повторяет правила захвата, проверки lease и освобождения хранилища PostgreSQL, и с fake clock из `backend/pkg/testutil/` (`internal/worker/jobrunner/`): выполняются только наступившие задания зарегистрированных видов в порядке срока, а задание со сроком через два дня выполняется ровно тогда, когда часы его достигают; неудачное задание повторяется после backoff по часам, не захватывается раньше и после последней попытки становится dead с записью в журнал уровня error и метриками; `ErrJobRejected` и panic завершают задание после одной попытки, а значение panic не попадает в журнал; обработчик, переживший свой lease, падает как `timeout`; задание, которое другой worker захватил до начала, пропускается без вызова обработчика; задание с истекшим lease последней начатой попытки становится dead без выполнения; медленное первое задание пачки не тратит единственную попытку следующего и не убивает его, а другой worker выполняет задание, которое занятый worker захватил, но не начал, на той же попытке; сбой базы данных вне обработчика освобождает задание и остаток пачки без учета попыток; неудачные захваты ждут backoff, а не крутятся в цикле; при остановке задание в работе завершается внутри grace, задание, которое его переживает, отменяется и освобождается без эффекта и без учтенной попытки, а захваченные, но не начатые задания освобождаются; panic во время остановки все равно делает задание dead; backlog всех видов попадает в метрики. Остальные unit-тесты покрывают правила задания (`internal/domain/`: вид, ключ, плоский payload, лимит размера, срок в UTC с точностью до микросекунд), настройки (`config/`), счетчики и gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), а в `internal/bootstrap/` - случаи без запуска с их строками журнала, пустой реестр видов, повторный вид и приложение, которое запускает worker против недоступной базы и все равно останавливается.
|
||||
|
||||
`TestScheduledJobs` в `backend/integration_test/scheduled_jobs_test.go` использует `bootstrap(t, postgresService)`. Его обработчик существует только в тесте: он пишет одну строку в `job_test.effects`, таблицу без уникального ключа, в транзакции, которая завершает задание, поэтому второй эффект остался бы виден. У каждого имитируемого процесса свой пул, хранилище и worker; создание нового означает перезапуск. Все решения о сроках и lease принимаются по одному `FakeClock`. Последовательные случаи:
|
||||
|
||||
- Задания на разные даты: два задания запланированы через `UnitOfWork.ScheduledJobs()` на завтра и через три дня, а повторное планирование игнорируется и не сдвигает срок. В начале ничего не выполняется; после перезапуска и одного дня выполняется первое задание; после еще одного перезапуска второе не выполняется за микросекунду до срока и выполняется в свой срок; через месяц снова ничего не выполняется. Эффектов по одному на задание, в порядке сроков.
|
||||
- Два worker с собственными пулами одновременно крутят свои циклы над 40 наступившими заданиями: все задания выполнены, эффектов ровно 40 для 40 разных заданий.
|
||||
- Обработчик, переживший lease по часам, по-прежнему держит блокировку строки задания, поэтому захват другого worker пропускает задание; затем первый worker завершает его с одним эффектом.
|
||||
- Истекший lease: worker A захватывает и запускает задание и останавливается внутри него. Worker B не может захватить его за микросекунду до истечения lease и выполняет его в момент истечения, с двумя учтенными попытками и записанным `lease_expired`. Поздний запуск worker A отклоняется, его поздний `Run` возвращает `ErrJobLeaseLost` без вызова обработчика, а поздняя запись сбоя и освобождение отклоняются; эффект остается один.
|
||||
- Начатая попытка задания с лимитом в одну попытку, lease которой истек: следующий захват делает задание dead с одной попыткой и `lease_expired` без вызова обработчика.
|
||||
- Захват, который так и не начался, с лимитом в одну попытку: после истечения lease другой worker выполняет задание на той же попытке без класса ошибки.
|
||||
- Медленное первое задание пачки работает дольше lease захвата: следующее задание с лимитом в одну попытку освобождается с сохраненной попыткой и выполняется в следующем проходе. С двумя worker, пока медленное задание держит свою строку, другой worker захватывает только ожидающее задание и выполняет его на единственной попытке; занятый worker затем считает его `lease_lost`.
|
||||
- Обработчик, который отменяет собственное задание через unit: его эффект фиксируется, задание остается `cancelled`, а следующее задание прохода выполняется. Обработчик, который меняет собственное задание иначе, переводит его в dead с `completion_conflict` и не оставляет эффекта.
|
||||
- Корректная остановка: обработчик пишет эффект и переживает grace в 200 ms. После остановки эффект откачен, задание в `pending` без попыток и без lease, а новый процесс сразу выполняет его, не дожидаясь lease.
|
||||
- Неудачное задание с собственным лимитом в две попытки: первая попытка сдвигает на backoff только `available_at` и сохраняет `due_at`, задание не захватывается до окончания backoff, вторая попытка делает его dead, обработчик оба раза видел исходный срок, эффектов нет, backlog показывает одно dead задание, а счетчики - один `retry` и один `dead`.
|
||||
- Отмена: отмененное задание никогда не захватывается, повторная отмена и новое планирование того же ключа ничего не делают, наступивших заданий нет.
|
||||
- Отмена во время выполнения: пока обработчик держит задание, отмена в другой транзакции видна в `pg_stat_activity` как ожидание блокировки строки; после фиксации обработчика задание выполнено, а отмена возвращает false.
|
||||
|
||||
`TestPostgresMigrations` также проверяет, что миграция 00008 создает и удаляет `scheduled_jobs`. Набор использует один PostgreSQL и тестовый вид задания. Он не измеряет пропускную способность, не покрывает расхождение часов между экземплярами, переключение базы данных и продуктовый обработчик и не проверяет доставку alerts.
|
||||
|
||||
## Тесты продуктовых метрик
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают продуктовые метрики. В `internal/adapter/primary/http/` запросы через настоящий router и настоящий collector получают шаблон маршрута своей операции (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) и никогда не получают параметр пути, адрес в пути или query string; неизвестные пути и методы сохраняют `/api/v1/*`, `/api/*` или `unmatched`; ответы problem считаются по коду (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), а обычный 404 вне `/api` - нет; в выдаче нет значений, похожих на email или UUID; каждый код problem контракта сохраняет свой label. Тест журнала запросов отправляет адрес и UUID в путях и query через тот же router и проверяет, что JSON-журнал называет только шаблоны маршрутов, статусы, коды problem и число параметров query, пропускает `/healthz` и `/readyz` и не содержит ни одного из значений. `internal/adapter/primary/http/middleware/` проверяет middleware журнала и метрик на простом router chi: общий маршрут и код problem, отсутствие problem для ответа, который в итоге успешен, уровень error для 5xx, неизвестный метод в журнале как `OTHER` и collector без учета problem. В `internal/adapter/secondary/prometheus/`: задержка по классу статуса, каждая пара вида и статуса доставки с нулем и сбросом, когда статус опустел, gauges квот без label аккаунта, hook сохранения ответов, который превращает неизвестные значения в `other` и не создает серий до первого вызова, и проверка всей выдачи после вызова каждого hook с fixture email и UUID. `internal/worker/deliverymetrics/` покрывает просрочку самой ранней доставки в `pending` (ноль, пока срок не наступил), текущие окна квоты, неудачное чтение, которое не отменяет второе, и жизненный цикл цикла чтения; `internal/bootstrap/` - пропуск без базы, квоты только для активного транспорта и приложение, которое запускает sampler против недоступной базы и все равно останавливается. `pkg/testutil/` проверяет сам поиск идентификаторов.
|
||||
|
||||
`TestDeliveryStatistics` в `backend/integration_test/delivery_statistics_test.go` проверяет запрос sqlc `GetDeliveryStatistics` на PostgreSQL: пустая таблица, затем доставки трех видов во всех пяти статусах, выставленных в рамках ограничений таблицы, дают точные числа по виду и статусу, а самый ранний срок берется только из доставок, которые еще в `pending`.
|
||||
|
||||
`make -C observability check` проверяет правила alerts через `promtool check config` и запускает `promtool test rules` для `observability/prometheus/tests/lincodex_rules_test.yml`: каждый alert срабатывает в положительном случае (backend недоступен, доля 5xx, отставание outbox, dead letter, застрявший обработчик, мертвые и опаздывающие задания, неизвестный исход доставки, учтенный один раз для двух экземпляров, просроченные доставки, устаревшие gauges почты, исчерпанная квота по счету и по отказу провайдера), а ограничения молчат: тихий трафик только из ошибочных запросов, просроченные доставки без `lincodex_mail_sender_running`, sampler, который продолжает успешно читать, и месячное окно с запасом.
|
||||
|
||||
`make -C observability verify-product-metrics` - сквозная проверка, описанная в [DEPLOY.md](DEPLOY.md#отдельный-monitoring-compose). Ей нужны Docker и свободные host ports 18085 и 13085; она собирает образы core и идет несколько минут. Она отправляет fixture адрес в query через Nginx и в пути напрямую в backend и вызывает по нему нарушение уникальности в PostgreSQL. Она доказывает, что метрики доходят до Prometheus, а запросы продуктового dashboard выполняются в Grafana, что PostgreSQL пишет ошибки кратко и что fixture адреса нет в выдаче метрик, во всех сериях и значениях labels, в federate и в логах Loki сервисов core в этом прогоне. Она не проверяет доставку alerts, production retention, нагрузку и целевую задержку и не отправляет почту.
|
||||
|
||||
## Шардирование интеграционных тестов
|
||||
|
||||
`make -C backend test-int` запускает полный набор через `backend/scripts/run-integration-suite.py`. Runner автоматически обнаруживает все верхнеуровневые `Test*` в `./integration_test/...`, сортирует их по пакету и имени, затем распределяет по шардам по кругу. Каждый тест попадает ровно в один шард вместе со всеми своими подтестами. Изменение набора тестов может изменить распределение; балансировка по длительности пока не используется.
|
||||
| Область | Команда | Требования |
|
||||
| --- | --- | --- |
|
||||
| Backend, быстрые тесты | `make -C backend test-fast` | Go |
|
||||
| Backend, race | `make -C backend test` | Go и C toolchain |
|
||||
| Backend, интеграционные | `make -C backend test-int` | Go, Python 3, Docker |
|
||||
| Frontend | `make -C frontend check` | Node.js, pnpm, установленные зависимости |
|
||||
| ML API | `make -C ml verify` | Python, uv, установленные зависимости |
|
||||
| Контракты | `make -C api check` | Установленные API-инструменты |
|
||||
| Генераторы OpenAPI 3.2 | `make -C api check-toolchain` | Go, frontend и ML toolchains |
|
||||
| Технический smoke | `make -C deploy smoke` | Docker Compose |
|
||||
| Браузерный E2E | `make -C deploy test-e2e` | Docker Compose, frontend dependencies |
|
||||
| E2E с почтой | `make -C deploy test-e2e-registration` | Те же зависимости |
|
||||
| Документация | `make docs-check` | Python 3 |
|
||||
|
||||
`make test` запускает тесты сервисов. `make check` добавляет форматирование, lint, типы, сборки и проверки конфигурации. `make verify` также генерирует код, проверяет drift, OpenAPI toolchain, backend race, интеграционные тесты и smoke.
|
||||
|
||||
Playwright, security-сканеры, реальные ML-модели и runner sandbox запускаются отдельно. Прошедший `verify` не заменяет их.
|
||||
|
||||
## Backend: unit и race
|
||||
|
||||
Тесты рядом с кодом проверяют domain/usecase и адаптеры без внешней инфраструктуры. Для портов используйте настроенные mockery-моки или небольшие fake-реализации с нужным поведением.
|
||||
|
||||
```sh
|
||||
make -C backend test-int-list
|
||||
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
make -C backend mocks
|
||||
make -C backend test-fast
|
||||
make -C backend test-race
|
||||
```
|
||||
|
||||
Индексы начинаются с 1. Обе переменные задаются вместе; неверные параметры, пустой набор, лишние шарды и ошибки обнаружения завершают команду ошибкой. `test-int-list` компилирует тестовый пакет и выводит выбранные тесты без запуска контейнеров. `make -C backend test-scripts` проверяет для каждого числа шардов, что каждый тест выполняется ровно в одном шарде, что список шарда совпадает с тестами, которые шард запускает, выбор родительских тестов и передачу ошибок runner. Он входит в `make -C backend check`.
|
||||
При изменении сценария проверяйте успешный путь, предметный отказ и сбой зависимости. Для конкурентных операций нужны проверки версии, повторов и отмены. Сравнивайте результат и сохраненные эффекты, а не внутренний порядок вызовов без причины.
|
||||
|
||||
CI запускает отдельную matrix из двух integration jobs с `GOFLAGS=-race` и `fail-fast: false`. Результат всех шардов обязателен для aggregate и deployment smoke. `GOFLAGS='-race -shuffle=on' make -C backend test-int` позволяет локально проверить гонки и независимость порядка. Шарды используют свои контейнеры; общие БД и брокер между runner не создаются, поэтому тест Kafka проходит в любом шарде, куда он попал. CI берет `TEST_SHARD_TOTAL` из размера matrix (`strategy.job-total`), поэтому, когда длительность suite оправдывает дополнительные runner, достаточно добавить индекс шарда в matrix; индекс больше общего числа шардов завершает job ошибкой. Таймаут `go test` делит бюджет всего набора в 30 минут между шардами, но не меньше 10 минут на шард: локальный запуск без шардов получает 30 минут, каждый из двух шардов CI - по 15.
|
||||
## Интеграционные тесты
|
||||
|
||||
## Тесты журнала согласий
|
||||
Тесты находятся в `backend/integration_test/` под build tag `integration`. Они используют Testcontainers с настоящими PostgreSQL, Redis, SeaweedFS и, при явном выборе, Kafka.
|
||||
|
||||
Unit-тесты (`make -C backend test`) проверяют правила журнала без базы:
|
||||
```sh
|
||||
make -C backend test-int-compile
|
||||
make -C backend test-int-list
|
||||
make -C backend test-int
|
||||
```
|
||||
|
||||
- `internal/domain/` (`consent_test.go`): целями считаются только `c1`-`c5`, и только C4 привязано к организации; версия текста следует шаблону контракта из 1-64 символов; хэш текста обязан иметь 32 байта и не быть нулевым; отклоняются сохраненный текст, который больше не совпадает со своим хэшем, текст C4 без плейсхолдера `{organization}` и другой текст с ним; показанный текст C4 дает разный хэш для разных организаций и отличается от хэша шаблона, а пустое, окруженное пробелами или многострочное название организации отклоняется. `NewConsentGrant` отклоняет C4, пустую или неверную версию, отсутствие хэша, субъекта или времени и источник, который цель не допускает; `NewContactConsentGrant` требует текст C4, организацию с допустимым названием, набор полей, приглашение и положительную версию условий и хэширует текст в том виде, в каком он показан с этим названием. Выдачи и отзывы не выводят в печать и логи субъекта, организацию, название или поля. Набор полей каноничен при любом порядке входа и отклоняет пустой, повторный, неизвестный набор и больше четырех полей. `RestoreConsentRecord` отклоняет то же, что отклоняет база, а запись в выводе и логах показывает только ID, цель и состояние.
|
||||
- `internal/adapter/secondary/postgres/` (`consents_test.go`): ошибки ограничений журнала превращаются в sentinel-ошибки по SQLSTATE и имени ограничения без деталей строки, ограничивающий ключ согласий в очистке превращается в `ErrTransactionConflict`, неверный вход отклоняется до запросов, каждый сгенерированный тип строки приводится к одной структуре записи, а сохраняемый набор полей идет в порядке, который принимает база.
|
||||
- `internal/usecase/consent/` (`service_test.go`, с in-memory репозиторием текстов, журналом, transactor и управляемыми часами): выдача C1, C2, C3 и C5 записывает актуальную версию и хэш текста, источник своей точки входа (`GrantAtRegistration` фиксирует C1 и `registration`, `GrantInSettings` фиксирует `consent_settings`) и время внедренных часов, но не любое другое время; выдача со старой, неизвестной или запланированной версией завершается `ErrStaleConsentText`, называет актуальную версию и не доходит до журнала; выдача версии один, публикация версии два и повтор версии один дают устаревшую версию и одну запись; `CheckTextVersion` возвращает актуальный текст, завершается устаревшей версией для старой, неизвестной и запланированной версии, отклоняет неизвестную цель и неверную версию и никогда не обращается к журналу; C4 на общем пути завершается `ErrScopedConsentRequired` до чтения любого репозитория; неверная или пустая версия, неизвестная цель и нулевой субъект отклоняются; повтор возвращает существующую запись с `Created` false и ее первым временем, а в журнале остается одна запись; ошибки репозиториев (нет опубликованного текста, неизвестный субъект) сохраняют свой sentinel, а отсутствие текста не выдается за устаревшую версию; у субъекта, не давшего C3, остальные цели имеют собственные записи, а записи C3 нет; `GrantContact` записывает scope, источник `invitation_acceptance` и хэш показанного текста, возвращает существующую запись при повторе, сообщает, что приглашение занято другим субъектом, и отклоняет устаревшую версию C4, название с пробелами по краям и отсутствие полей, организации, приглашения, субъекта или версии условий; `GrantInSettingsInNewTransaction` повторяет конфликт транзакции после паузы, останавливается после трех попыток, не повторяет другую ошибку и отмененный контекст и откатывает устаревшую выдачу; `NewService` паникует при нулевом transactor или часах.
|
||||
- `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` с сессией после валидации отвечает 501, а на неизвестное состояние, limit больше 100 и неверный cursor - 400 с указателем на параметр запроса; при `DenyAllSecurity` отвечает 401 с cookie, без нее и с параметром `subject_id`; DTO не содержат хэша, субъекта или контактов, параметры - только состояние и страница, а пример контракта декодируется и проходит валидацию.
|
||||
- `frontend/src/shared/api/consent-contract.test.ts`: сгенерированные Zod-схемы принимают запись C4 со scope и отозванную запись без scope, отклоняют неизвестную цель, состояние или источник, пустую или неверную версию, пустой или слишком большой набор полей, неизвестный вид контакта и версию условий меньше 1, требуют каждое nullable-поле и отбрасывают хэш или субъекта; операция принимает только состояние и параметры страницы.
|
||||
`test-int-compile` компилирует тесты без контейнеров; `test-int-list` показывает выбранные верхнеуровневые тесты. Ни одна из этих команд не подтверждает успешное выполнение сценариев. Для `test-int` нужен работающий Docker; его отсутствие считается ошибкой.
|
||||
|
||||
`TestConsentLedger` в `backend/integration_test/consent_ledger_test.go` использует `bootstrap(t, postgresService)` с примененными миграциями, публикует второй текст C1 так, как это сделала бы миграция, и очищает журнал между случаями:
|
||||
### Общий bootstrap
|
||||
|
||||
- Миграция публикует по одному демо-тексту на цель с совпадающим хэшем; актуальный текст C1 зависит от времени; неизвестная версия и версия другой цели не находятся.
|
||||
- Версии и цели: C1 при регистрации, C2 и новая версия C1 дают три строки; старая строка C1 остается побайтно прежней и показывается как `superseded`, актуальным C1 становится новая версия, повторная выдача старой версии возвращает существующую строку без новой, а отзыв C2 не меняет C1.
|
||||
- Отзыв ставится один раз: повторный отзыв ничего не находит и сохраняет первое время, актуального C3 больше нет, а новая выдача - новая строка рядом с отозванной. Отзыв C1 закрывает и его строку `superseded`.
|
||||
- C4: домен отклоняет общую выдачу и scoped-выдачу без организации и полей; выдача сохраняет организацию, канонический набор полей, приглашение и версию условий с хэшем показанного текста, а не шаблона; повтор возвращает ту же строку; согласие по приглашению другого субъекта дает `ErrConsentInvitationTaken`; отзыв C4 для организации A не затрагивает организацию B, а отозванное согласие по приглашению не возвращается.
|
||||
- Проверки repository: неизвестный субъект, пустая или неверная версия, пустой хэш, придуманная версия, версия другой цели, хэш другого текста и выдача до публикации отклоняются и ничего не сохраняют. Другой субъект не видит и не отзывает согласие владельца.
|
||||
- Ограничения базы через прямой SQL: пустая версия, пустой или короткий хэш, C4 без scope или с пустым, повторным или неизвестным полем, C2 со scope или из регистрации, отзыв без источника и хэш другого текста отклоняются с именем ограничения; изменение выданной строки, отзыв с одновременным сдвигом выдачи, повторная отметка отзыва, изменение или удаление опубликованного текста и удаление аккаунта с историей согласий отклоняются.
|
||||
- Модель чтения: страницы по три записи возвращают ровно четыре записи владельца от новых к старым и никогда не возвращают записи другого субъекта; фильтр состояния возвращает активные и отозванные записи.
|
||||
- Бизнес-транзакция: выдача C4 откатывается вместе с упавшим принятием, ошибка запроса после выдачи откатывает всю транзакцию, а зафиксированное принятие видно после фиксации и в своей транзакции до нее.
|
||||
- Очистка неподтвержденных аккаунтов удаляет устаревший аккаунт вместе со строкой C1 и сохраняет подтвержденный аккаунт и его запись.
|
||||
- Снимок C4: строки, чей хэш относится к другому названию организации, к названию, отличному от сохраненного, или к шаблону, отклоняются (`consent_records_c4_text_hash`), C4 без названия и C1 с названием отклоняются (`consent_records_c4_scope`); после переименования два принятия сохраняют свои названия, и хэш каждого по-прежнему доказывает текст, показанный с его снимком.
|
||||
- Отзыв со временем на час раньше выдачи записывается временем выдачи.
|
||||
- Удаление строки согласия подтвержденного аккаунта отклоняется (`consent_records_retained`); строку неподтвержденного аккаунта удалить можно.
|
||||
- Повторная регистрация: `UpdateRegistration` и новая выдача C1 в одной транзакции оставляют только новое C1; устаревшая повторная регистрация и попытка для подтвержденного аккаунта ничего не меняют и не удаляют.
|
||||
- Восемь одновременных выдач одной версии на своих соединениях сохраняют одну запись, и все возвращают ее, причем `created` ровно у одной.
|
||||
- Двадцать раундов гонки выдачи и отзыва не дают ошибок, кроме `ErrTransactionConflict`, и никогда не оставляют больше одной неотозванной записи версии.
|
||||
- Когда заблокирована только строка согласия устаревшего аккаунта, очистка в сессии с lock timeout 200 ms пропускает аккаунт без ожидания и удаляет его после снятия блокировки.
|
||||
В `bootstrap_test.go` функция `bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, применяет миграции и возвращает настройки и клиенты. Для узкой проверки выбирайте сервисы: `bootstrap(t, postgresService)` или `bootstrap(t, postgresService, kafkaService)`.
|
||||
|
||||
`TestConsentGrants` в `backend/integration_test/consent_usecase_test.go` запускает usecase на базе bootstrap с фиксированными часами приложения, вторым текстом C1 и текстом C5, запланированным после часов:
|
||||
Каждый вызов владеет своими контейнерами и динамическими портами. Ресурсы освобождаются через `t.Cleanup`, в том числе при ошибке запуска. Вызывайте bootstrap в родительском тесте и переиспользуйте окружение в его подтестах; данные соседних тестов должны быть изолированы.
|
||||
|
||||
- Регистрация: `UserRepository.Create` и `GrantAtRegistration` для C1 выполняются в одной транзакции `Transactor` без сессии (таблица сессий остается пустой) и фиксируют один аккаунт и одно C1 со временем приложения и актуальной версией текста. C2 и C5 следуют отдельными операциями, у каждой своя активная запись; C3 не дано, записи C3 нет, пока остальные действуют; C3, выданное позже и отозванное, оставляет C1, C2 и C5 активными.
|
||||
- Атомарность: транзакция, упавшая после записи аккаунта и C1, не оставляет ни того, ни другого, а выдача для субъекта без аккаунта завершается `ErrUserNotFound` и ничего не записывает.
|
||||
- Идемпотентность и версии: повтор в собственной транзакции и в бизнес-транзакции возвращает первую запись и ее время и не добавляет строк, а бизнес-транзакция не прерывается. Устаревшая версия C1, запланированная версия C5 и неизвестная версия C3 завершаются ошибкой устаревшей версии с названием актуальной и ничего не записывают; актуальная версия C1 проходит, а устаревшая остается отклоненной. Выдача после отзыва - новая строка. Восемь одновременных повторов создают ровно одну строку.
|
||||
- Повторная публикация: после выдачи версии один C3 и публикации версии два повтор версии один считается устаревшим, называет версию два и оставляет одну строку и первую запись как текущее C3.
|
||||
- Повторная регистрация: `UpdateRegistration` и затем `GrantAtRegistration` в одной транзакции возвращают `created` true с новой записью и оставляют ровно одно C1. Обратный порядок показан как риск: выдача находит C1 прежнего регистранта и возвращает его с `created` false, затем обновление удаляет его, и аккаунт остается без C1.
|
||||
- C4: общий путь отклоняет его и ничего не записывает; `GrantContact` в транзакции сохраняет организацию, название, поля, приглашение и источник `invitation_acceptance`; повтор возвращает ту же запись, устаревшая версия C4 отклоняется, а C4 не создает C2.
|
||||
- Перезапуск: после закрытия pool новый pool, хранилище и usecase перечисляют те же четыре записи по порядку с их состояниями, отметкой и источником отзыва и исходными временами выдачи, а повторная выдача через новый экземпляр ничего не записывает.
|
||||
Общие helpers создают пулы, отдельные базы и Kafka-топики. Используйте их вместо копирования настройки контейнеров. HTTP-сервер и предметные фикстуры подключайте для конкретного сценария.
|
||||
|
||||
`TestRegistrationConsentMigration` применяет миграцию 00016 в изолированной базе, проверяет привязку старой C1, отсутствие привязки у согласий из настроек, вставку C1 через старую форму записи, отказ для переданной несовпадающей версии, защиту версии от изменения при отзыве и повторный down/up. Отдельный случай проверяет, что устаревшая регистрационная C1 останавливает миграцию без частичных изменений. `TestPostgresMigrations` продолжает проверять миграцию 00009. Интеграционные тесты регистрации и подтверждения email проверяют вызов consent service в API потоке; `TestConsentGrants` проверяет usecase отдельно от HTTP. Отзыв и принятие приглашения с C4 пока не покрыты как бизнес-потоки. Гонка очистки с SQLSTATE 23001 покрыта только unit-тестом преобразования, потому что ее окно нельзя воспроизвести детерминированно.
|
||||
Для SQL проверяйте реальные транзакции, ограничения и миграции. Для outbox и событий - повторную доставку и восстановление после сбоя. Для доступа к данным - разрешенный запрос, другой аккаунт/организацию и отзыв разрешения.
|
||||
|
||||
## Тесты организаций
|
||||
`TestCompanyQuota`, `TestHoldings` и тест миграции холдингов проверяют реальные квоты PostgreSQL: границы окон, повторы, общий пул E0, конкуренцию, изменение политики и защищенный откат. HTTP-набор отдельно проверяет отправку приглашений, изоляцию компаний и немедленное закрытие контактов после отзыва доступа.
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила организаций без базы данных:
|
||||
### Шарды
|
||||
|
||||
- `internal/domain/` (`organization_test.go`, `membership_test.go`): профиль принимает только название и полную карточку; каждое правило называет поле, которое его нарушает, указателем JSON Pointer (`/name`, `/contacts/website`, `/representatives/1/name`), не цитируя значение: пустое, с пробелами по краям, многострочное, слишком длинное или не UTF-8 название, описание или сфера с переводом строки или управляющим символом, сайт не по `https`, с учетными данными, портом, IP-адресом, числовым или шестнадцатеричным хостом или без точки, email без точки в домене, телефон вне E.164, имя Telegram без `@` и одиннадцать представителей. CRLF в описании сохраняется как LF. `NewOrganization` начинает с версии 1, UUIDv7 и уровня `e0` на основании `confirmed_email`, как бы ни выглядел профиль; `ApplyProfile` сохраняет идентификатор, версию и проверку и никогда не двигает время обновления назад; уровень сочетается только со своими основаниями; `e0`-`e2` сопоставляются ступеням квот политики, а у `e3` ступени нет; сохраненная строка, измененная вне приложения, не восстанавливается. Карточка содержит только профиль и уровень. Представитель скрыт в выводе `fmt` и `slog`, в том числе внутри объемлющей структуры, а организация логирует только идентификатор, версию и уровень. Компанией управляет только владелец, доступ дает только `active` членство, четыре роли и четыре состояния совпадают со значениями контракта, а `NewMembership` отказывает на nil-идентификатор, неизвестную роль и нулевое время.
|
||||
- `internal/adapter/secondary/postgres/` (`organizations_test.go`): ошибки ограничений организаций сопоставляются своим sentinel по SQLSTATE и имени ограничения без строки с ошибкой, в которой лежат имена представителей; остальные ошибки хранят только SQLSTATE и ограничение; взаимная блокировка сопоставляется `ErrTransactionConflict`; некорректный ввод отвергается до любого оператора; управляющие роли, передаваемые в SQL, берутся из доменного правила.
|
||||
- `internal/adapter/primary/http/` (`organization_test.go`): при наличии сессии операции отвечают 501 после валидации и 400 с указателем на каждое правило схемы (название длиннее 200 символов или с переводом строки, отсутствующий `expected_version`, контакты без одного поля, сайт по http или с учетными данными, телефон вне E.164, имя Telegram без `@`, одиннадцать представителей, представитель с контактом, null в `name`, `contacts` или `representatives`, лимит больше 100, идентификатор не UUID); представители карточки кандидата могут отсутствовать, быть null или пустыми, а карточка без контактов отвергается. Каждое из одиннадцати полей, которые несли бы право или уровень доверия (`role`, `owner_id`, `verification_level`, `verification`, `verification_basis`, `members`, `membership`, `candidate_card`, `id`, `version`, `created_at`), отвергается по отдельности при создании и обновлении с указателем на все тело. Под `DenyAllSecurity` все четыре операции отвечают 401 с cookie и без и с параметром `user_id`. DTO запросов содержат ровно поля профиля и не содержат поля роли, владельца, участника или проверки, в карточке нет членства, роли, основания и времени, список принимает только страницу, в `OrganizationUpdate` отсутствующий список отличается от пустого, каждый документированный пример декодируется и проходит валидацию, а в bundle запросы - закрытые объекты, обе записи требуют схему CSRF, создание требует Idempotency-Key, обновление объявляет 412, и нет операции, которая задает уровень или роль.
|
||||
- `frontend/src/shared/api/organization-contract.test.ts`: сгенерированные схемы Zod принимают только название и полную карточку для создания и обновления, требуют `expected_version`, допускают null только для `description` и `sphere`, отвергают те же пределы, что и контракт, отбрасывают роль или уровень проверки, добавленные клиентом, перечисляют четыре уровня, роли и состояния и, на уровне типов, не дают запросам полей роли, владельца, участника, проверки или идентичности, карточке - членства и основания, а членству - аккаунта.
|
||||
`backend/scripts/run-integration-suite.py` обнаруживает тесты и распределяет их по отсортированному списку. Верхнеуровневый тест со всеми подтестами остается в одном шарде. Индексы начинаются с 1; обе переменные обязательны вместе.
|
||||
|
||||
`TestOrganizationsAndMemberships` в `backend/integration_test/organizations_test.go` использует `bootstrap(t, postgresService)` с мигрированной схемой и между случаями очищает таблицы организаций вместе с `users`:
|
||||
```sh
|
||||
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int-list
|
||||
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
|
||||
make -C backend test-scripts
|
||||
```
|
||||
|
||||
- Хранение: организация сохраняется с владельцем и читается с профилем, представителями по порядку, версией 1, уровнем `e0` и активным членством владельца; незаданные поля равны NULL.
|
||||
- Уникальность членства: повторное членство того же аккаунта в той же организации, в каждой из четырех ролей и после выхода участника, завершается `ErrMembershipExists` с именем `memberships_user_id_organization_id_key`, прямая вставка завершается SQLSTATE 23505, и остается одна строка; другой аккаунт или другая организация - другая пара.
|
||||
- Атомарное создание: неизвестный аккаунт владельца откатывает организацию, представителей и членство; последующий сбой той же транзакции тоже; членство владельца, которое является рекрутером, относится к другой организации или нулевое, отвергается до любой записи.
|
||||
- Владелец при фиксации: транзакция, вставляющая только организацию, только с рекрутером, только с приостановленным владельцем или с владельцем, которого она переводит в `removed` до фиксации, падает при фиксации с SQLSTATE 23514 на `organizations_owner_required` и ничего не оставляет; организация и активный владелец, вставленные в одной транзакции, фиксируются.
|
||||
- Список в своей области: организации одного аккаунта включают те, где он рекрутер, и исключают те, где его членство приостановлено, завершено выходом или удалено, и все организации другого аккаунта; страницы по две следуют одному порядку без пропуска и повтора; членства, созданные в один момент, упорядочиваются по идентификатору организации; некорректные запросы, в том числе позиция без идентификатора организации, отвергаются; организация без представителей читается с пустым списком.
|
||||
- Доступ: аккаунт без членства, неизвестный аккаунт, неизвестная организация и участник в состоянии `suspended`, `removed` или `left` получают `ErrOrganizationNotFound`, восстановленный участник снова читает, а `Memberships().Get` возвращает сохраненное состояние в любом состоянии.
|
||||
- Обновление: владелец заменяет профиль, список представителей и контакты, версия растет до 2, время обновления меняется, очищенные поля становятся NULL, а уровень проверки, который процесс выставил в `e1`, остается `e1` после следующего обновления профиля. Рекрутер получает `ErrOrganizationManagerRequired`, приостановленный владелец, посторонний и неизвестный аккаунт получают `ErrOrganizationNotFound` даже с устаревшей версией, устаревшая версия получает `ErrOrganizationVersionConflict`, и ничто из этого не меняет сохраненную организацию.
|
||||
- Отзыв во время обновления: транзакция, отзывающая второго владельца, остается открытой, обновление этого владельца встает в очередь за блокировкой его членства (видно в `pg_stat_activity`), а когда отзыв фиксируется, обновление возвращает `ErrOrganizationNotFound` и ничего не пишет. Без `FOR SHARE` на членстве исполнителя тест падает.
|
||||
- Конкуренция: восемь обновлений от одной версии на своих соединениях дают ровно один успех и семь конфликтов, а сохраненные название и представитель принадлежат одному победителю.
|
||||
- Ограничения через прямой SQL: пустое, с пробелами по краям, многострочное или слишком длинное название, неизвестный уровень, основание другого уровня, версия ноль, описание с пробелом на конце или управляющим символом, сфера с переводом строки, сайт по http или с учетными данными, email с пробелом, телефон без `+`, имя Telegram без `@`, обновление раньше создания, пары уровня и основания для `e1`, `e2` и `e3` (верные принимаются, неверные отвергаются), составной внешний ключ на `(organization_id, id)` членств (принимается для организации самого участника, отвергается для чужой), неизвестная роль (включая `manager`), неизвестное состояние (включая `invited`), одиннадцатый представитель и должность с пробелом по краю отвергаются по имени ограничения; в таблице организаций нет столбца роли, владельца, участника или пользователя.
|
||||
- Удаление: аккаунт с членством и организацию с участником удалить нельзя (SQLSTATE 23001); когда членства удалены, организация забирает представителей с собой.
|
||||
Без переменных выполняется весь набор. CI использует два шарда. `test-scripts` проверяет покрытие распределения, выбор тестов и передачу кода ошибки. Распределение детерминированное, но не учитывает длительность отдельных тестов.
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00010 вместе с остальными, проверяет, что три ее таблицы и функция исчезают, а таблицы identity остаются, и проверяет их снова после второго применения. Тесты, очищающие `users`, называют `usersDependentTables` (таблицы identity, доставок, согласий и организаций) - единственный список, который нужно расширять, когда миграция добавляет таблицу со ссылкой на users. Этот набор хранения не покрывает usecase и HTTP; отдельные проверки ниже используют реальную сессию и CSRF. Атомарность чтения организации с представителями одним оператором тестом не доказана, потому что окно между двумя операторами нельзя воспроизвести детерминированно.
|
||||
## Frontend
|
||||
|
||||
`TestOrganizationCreationAndOwnerEditingOverHTTP` и `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяют создание и изменение организации, идемпотентный повтор, свою постраничную директорию, owner-only действия, чужие организации и прекращенное членство через настоящий HTTP и PostgreSQL. Отзыв второго владельца закрывает профиль и tenant-операции для той же cookie, не закрывая доступ другого владельца. Проверки middleware перечисляют все tenant operations контракта.
|
||||
Vitest работает в Node и проверяет логику, преобразования данных и компоненты в доступном ему окружении. Браузерные spec-файлы из `frontend/e2e/` исключены из этого запуска.
|
||||
|
||||
`TestCompanyIsolationAndRevocationOverHTTP` (`backend/integration_test/company_isolation_http_test.go`) проверяет изоляцию компаний и отзыв на минимальном пути через настоящий HTTP и PostgreSQL. Компания A проходит потребность, поиск, карточку с доказательствами, приглашение, принятое с C4, чтение контактов и уведомление. Затем компания B и вторая компания того же владельца A в том же холдинге вызывают каждую операцию в контексте организации с действующей сессией: по пути A и по своему пути с идентификаторами из ответов A. Каждый вызов должен отвечать документированным отказом, таким же, как для случайного идентификатора, а объекты A должны остаться без изменений. Ту же проверку получает кандидат с приглашением и уведомлением другого кандидата. Тест также проверяет, что скрытие организации, отзыв C4 и отзыв C2 закрывают следующее же чтение через handle прежней выдачи, страницу приглашения и чтение контактов. Новое C2 или новая публикация не должны возвращать разрешение, закрытое отзывом C4. MVP не должен отдавать PDF, snapshot выдачи или сохраненный результат поиска, а лог сервера, payload outbox, строки входящих уведомлений и сохраненные запросы писем не должны содержать контактов, имени и значений профиля. Kafka, браузер и роли, кроме владельца, он не покрывает.
|
||||
```sh
|
||||
make -C frontend test
|
||||
make -C frontend typecheck
|
||||
make -C frontend check
|
||||
```
|
||||
|
||||
## Тесты профиля кандидата
|
||||
`check` включает форматирование, ESLint, Stylelint, типы, Vitest, границы FSD и production build. MSW и подмена ответов API проверяют frontend-поведение; они не доказывают серверную авторизацию или сохранение данных.
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила профиля без базы данных:
|
||||
## Браузерный E2E-набор
|
||||
|
||||
- `internal/domain/candidate_test.go`: ручные значения получают источник `manual`, уровень доверия 0 и время сохранения; поле, посланное как null, удаляется, а список заменяется; предложение импорта остается неподтвержденным при `extracted` с тем же значением, подтверждается при `confirmed` с сохранением источника и цитаты, становится ручным при другом значении, а `extracted` для значения, которого нет среди предложений, и возврат подтвержденного значения в предложение отклоняются с указателем `/stack/1/status`; таблица значений называет поле, которое нарушило правило (телефон вне E.164, Telegram без `@`, имя с пробелами, зарплата не кратна 1000, неизвестные специализация и грейд, повтор тега без учета регистра, повтор специализации роли, месяц не в формате `YYYY-MM`, период, который кончается раньше начала или лежит в будущем, слишком много элементов); ошибка не содержит присланного значения; тело без изменений не меняет профиль и время подтверждения; строки хранилища (`StoredClaims`) восстанавливаются в то же содержимое в любом порядке, а строка с неизвестным видом, уровнем доверия выше 0, цитатой у ручного значения, значением чужого типа, лишним ключом `confirmed_grade`, пропуском в списке или повтором отклоняется; типы профиля не имеют полей подтвержденного грейда, категории или уровня доверия; значения скрыты в выводе `fmt` и `slog`.
|
||||
- `internal/adapter/primary/http/candidate_profile_contract_test.go`: по бандлу контракта операции следуют соглашениям (сессия и CSRF для сохранения, версия в теле, нет Idempotency-Key и If-Match, 412 вместо 409, `no-store`); запрос не несет подтвержденную категорию, источник, уровень доверия и время подтверждения, а все схемы профиля закрывают объекты; каждое заявление несет `status` и `source`, а `trust_level` ограничен нулем; имя использует `ContactFullName`; **ни одна схема вне семейства профиля, ни одна операция организации не достигает схемы профиля по ссылкам, и профиль не ссылается на схемы организации, приглашения или потребности**; через сгенерированный сервер схема отклоняет присланную клиентом категорию, источник и неизвестные поля до реализации, а допустимый профиль отвечает 501, при отклоненной сессии - 401.
|
||||
- `frontend/src/shared/api/profile-contract.test.ts`: сгенерированные схемы Zod принимают полный профиль и профиль без единого значения (то есть без файла и ФСП), требуют `expected_version`, отклоняют каждый нарушенный формат и лишние элементы списков, не пропускают в разобранное тело подтвержденный грейд, категорию и источник, требуют у каждого заявления источник с уровнем доверия 0, а типы запросов не имеют этих полей; сгенерированные файлы организации, приглашения и потребности не содержат ключей профиля, и наоборот.
|
||||
```sh
|
||||
make -C frontend install
|
||||
make -C deploy test-e2e
|
||||
make -C deploy test-e2e-registration
|
||||
```
|
||||
|
||||
`TestCandidateProfileStorage` в `backend/integration_test/candidate_profile_test.go` использует `bootstrap(t, postgresService)` с мигрированной схемой; `candidateProfileTables` входят в `usersDependentTables`, поэтому остальные тесты очищают их вместе с `users`:
|
||||
Обе команды создают одноразовый Compose-проект с собственными секретами и volumes. Браузер обращается к приложению через Nginx. Скрипт убирает тестовые контейнеры и volumes при завершении; результаты остаются в `frontend/test-results/e2e/`.
|
||||
|
||||
- Сохранение без файла, ML и ФСП: профиль только с именем, а также строка профиля без единого заявления сохраняются и читаются, а полный профиль возвращается с тем же содержимым и источником через `StoredClaims` и `RestoreCandidateProfile`; сохраненное предложение импорта читается с цитатой, версией извлечения и уровнем 0.
|
||||
- Схема: столбцы двух таблиц равны ожидаемому списку (без файла, ФСП, подтвержденного грейда и категории), а единственные внешние ключи ведут на аккаунт и на строку профиля.
|
||||
- Ограничения через прямой SQL: каждое правило отказывает строке с собственным ограничением (уровень доверия выше 0, неизвестные вид, статус и источник, одиночное поле с позицией, список за пределом, подтверждение без времени, ручное значение с цитатой, импорт без версии извлечения, неверные значения тега, телефона, Telegram, переезда, зарплаты, роли с ключом `confirmed_grade` и опыта); повтор тега, навыка и специализации роли, профиль без аккаунта, версия 0 и заявление без профиля тоже отклоняются, а такая же корректная строка принимается.
|
||||
- Удаление аккаунта удаляет профиль и заявления; два аккаунта хранят профили независимо.
|
||||
- Версия: проигравшее второе первое сохранение и устаревшая версия не возвращают строку, восемь продвижений от одной версии и восемь параллельных первых сохранений на своих соединениях дают ровно один успех, а продвижение с более ранним временем приложения сохраняет время обновления и не нарушает CHECK. Чтение идет одним запросом `ReadCandidateProfile`.
|
||||
Обычный `test-e2e` использует отключенную почту. Он выполняет технические и доступные UI-сценарии; тесты, которым нужны почта и специальные фикстуры, пропускаются. `test-e2e-registration` включает локальный Resend-совместимый приемник и синтетические данные для регистрации и бизнес-сценариев. Он не отправляет письма через реальный Resend.
|
||||
|
||||
`TestCandidateProfileMigrationRollsBack` откатывает миграцию 00013 на изолированной базе, проверяет, что обе таблицы исчезают, а `users` остается.
|
||||
В наборе есть два вида проверок:
|
||||
|
||||
`TestCandidateProfileOverHTTP` проверяет собственный профиль через сессию и CSRF: пустой GET, полное сохранение и перезапуск API, конкретные ошибки дат и пересечений, подтверждение параллельной работы, 412, отсутствие записи истории при no-op, недоступность чужого профиля и отказ employer. История, данные и условный переход шага находятся в одной транзакции; ошибки вставки истории и перехода шага откатывают сохранение. Изменение самооценки не создает подтвержденную категорию.
|
||||
- С настоящим backend: регистрация, профиль, анкета, организации, потребности, поиск, приглашения и минимальный путь в `acceptance-path.spec.ts`. Нужные фикстуры включаются почтовым стендом.
|
||||
- С подменой API через `page.route`: состояния экранов, ошибки, конфликты, часть сценариев оценки и доступности интерфейса. Эти тесты подтверждают поведение браузера в заданном состоянии.
|
||||
|
||||
## Тесты анкеты кандидата
|
||||
Playwright запускает Chromium с одним worker и без повторов. Поиск по реальному банку идет первым, чтобы записи других spec не меняли выдачу. Конфигурация принимает только loopback-адрес стенда.
|
||||
|
||||
`TestCandidateQuestionnaireOverHTTP` использует настоящие сессии, CSRF и PostgreSQL. Он проверяет пустую анкету версии 0, сохранение и перезапуск обработчика, изоляцию аккаунтов, отказ работодателю, отклонение неизвестных полей подтвержденного грейда, разные конкурентные записи с ответами 200/412, одинаковые конкурентные записи с ответами 200 и одним повышением версии, условный переход onboarding, откат, парность полей опыта и закрытие каталога после смены политики или отзыва семейства. Самооценка не создает подтвержденную категорию. Канонический API использует 412 для конфликта версий; прежняя формулировка задачи упоминает 409.
|
||||
При ошибке смотрите HTML-отчет, trace и скриншот. Перечисляйте passed, failed и skipped: зеленый запуск с пропущенным нужным сценарием не закрывает его приемку. Не направляйте E2E на общий или production-стенд.
|
||||
|
||||
Изолированный почтовый overlay задает `IDENTITY_CLIENT_HOURLY_LIMIT=200`, поскольку все браузерные сценарии используют один адрес прокси. Обычная и релизная конфигурации сохраняют 30, лимиты отдельного email не меняются.
|
||||
### Приемка демонстрационного пути
|
||||
|
||||
`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior с Go и Python. Тестовая команда `questionnaire-fixture` принимает только неизмененную начальную демо-политику, явно публикует `DemoProductPolicyV2`, затем публикует необходимое число проверенных семейств перед привязкой каталога. Это также включает разделы политики поддержки и оценивания для браузерных тестов. Команда отказывается работать поверх существующего backend-банка или другой действующей либо запланированной политики и отсутствует в обычном и релизном образах. Обычный запуск по-прежнему создает только V1. Браузерный сценарий проходит шаги анкеты (проверка шага, фокус на заголовке, "Назад" и "Изменить" без потери ответов) и проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается.
|
||||
Перед показом выполните `make docs-check`, `make -C deploy check`, smoke и почтовый E2E-набор. В `acceptance-path.spec.ts` должны пройти полный тест с категорией `synthetic_demo`, публикация, поиск с объяснением, приглашение, C4 и раскрытие контактов; повторное принятие не должно создавать дубликаты, а отзыв доступа должен закрывать чтение. Пропуск этого spec не считается приемкой.
|
||||
|
||||
`assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим с продолжением незавершенного запуска после перезагрузки (409 на новое начало, затем 201 по сохраненному ключу), отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки.
|
||||
Сверьте результат с запускаемым коммитом или образами. Локальная почтовая фикстура не доказывает доставку настоящим Resend, локальный Nginx - работу внешнего HTTPS, а синтетический банк - точность грейда. Для выпуска повторите smoke и E2E на закрепленных образах по [DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
|
||||
## Минимальный путь от регистрации до раскрытых контактов
|
||||
## ML и модели
|
||||
|
||||
В режиме регистрации overlay `docker-compose.e2e-mail.yml` выставляет тестовому backend `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` и передает Playwright `E2E_DEMO_CATEGORIES=1`. После `questionnaire-fixture` runner аттестует открытую категорию Backend Junior операторской командой `/assessment-category-attest` из тестового backend-образа, поэтому пройденный полный тест на этом стенде получает некалиброванную категорию `synthetic_demo`, как на демонстрационном стенде. Обычный и релизный наборы сохраняют значение по умолчанию `false`, а `make -C deploy check-e2e-mail` проверяет обе настройки.
|
||||
`make -C ml verify` проверяет формат, Ruff, mypy, pytest, сборку, контракт и актуальность Pydantic-моделей. Обычные тесты отделены от медленных проверок реальных весов.
|
||||
|
||||
`frontend/e2e/acceptance-path.spec.ts` проходит минимальный путь на настоящем backend без ФСП ID. Пять кандидатов регистрируются по ссылке из полученного письма, заполняют профиль и анкету, дают C3, решают каждое задание полного теста по его условию и после явного C2 публикуют одинаковую карточку, потому что карточка показывается только в группе из пяти. Затем spec проверяет:
|
||||
```sh
|
||||
make -C ml model-fetch
|
||||
make -C ml test-model
|
||||
```
|
||||
|
||||
- результат `confirmed` с решением о категории `assigned`, `demo_basic_pass_mark`, `synthetic_demo`; перезагрузка посреди попытки возвращает ту же попытку без второго ответа, а история результатов хранит одну запись после перезагрузки и шага назад и вперед по истории браузера;
|
||||
- потребность, поиск по ее версии требований с пятью подтвержденными записями и объяснением от сервера, фильтр по заявленному грейду senior, который убирает все пять карточек и оставляет только чужие карточки с этим грейдом, и неизменный результат первой версии требований после правки потребности;
|
||||
- три приглашения, привязанные к первой версии требований и доставленные по одному разу; ни результат поиска, ни список приглашений, ни уведомления организации не содержат email, телефон или имя;
|
||||
- принятие в браузере только с email, после которого перезагрузка и шаг по истории не добавляют записей, для организации есть одна запись C4, а организация читает только email;
|
||||
- два одновременных принятия одного приглашения с разными ключами: оба отвечают 200 с одинаковым телом, одна запись C4 и один grant;
|
||||
- отказ без доступа и отказ 409 `state_conflict` в новом приглашении для той же пары;
|
||||
- вторую компанию, которая получает 404 или ошибку поля, но не данные, для потребности, поиска по этой потребности, карточек, приглашений и контактов первой;
|
||||
- отзыв C2, который сразу закрывает чтение контактов и карточки прежнего результата (оставшиеся четыре карточки оказываются меньше группы из пяти и тоже скрываются), и новые C2 и публикацию, которые открывают карточки, но не grant принятого приглашения.
|
||||
`model-fetch` скачивает закрепленные файлы Giga и Qwen3 embeddings и сверяет SHA-256; нужен доступ к источнику весов и место на диске. `test-model` сравнивает реальные модели с исследовательскими векторами; для GPU задайте `ML_TEST_DEVICE=cuda`. Это проверка воспроизводимости inference, а не доказательство качества подбора на реальных кандидатах.
|
||||
|
||||
Spec не проверяет запланированные переходы без операции (отзыв приглашения компанией, отмену участия кандидатом, встречное предложение, интервью, закрытый финал), лимит 20 приглашений на потребность и истечение срока (их покрывают интеграционные тесты backend), рекомендации категорий для потребности, которые остаются `pending`, и PDF. Трассировка и снимки выключены, данные синтетические.
|
||||
## Runner и лаборатории
|
||||
|
||||
## Тесты видимости кандидата
|
||||
`make -C runner check` и `make -C labd check` проверяют Go-модули. Их unit-тесты не требуют работающей песочницы или LXD.
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила видимости без базы:
|
||||
Проверки реального runner, его изоляции и лабораторий запускаются отдельно на предназначенном для тестов окружении. Условия и команды находятся в [runner/](../../runner/README.md) и [labd/](../../labd/README.md). Результат на локальном dev-контейнере не подтверждает изоляцию развернутого runner.
|
||||
|
||||
- `internal/domain/visibility_test.go`: набор полей карточки канонический, закрытый и отклоняет полное имя, любой контакт и зарплату; запрос публикации требует поле для публикации и не допускает его при закрытии; новый профиль закрыт и не публиковался; публикации нужна действующая C2, а согласие она не называет; порядок проверок (будущая версия, неизмененное состояние при устаревшей версии, устаревшее изменение, нет согласия); отозванная C2 закрывает карточку, а новая ее не открывает; статус поиска истекает через срок политики до непубличного статуса без записи, подтверждается заново явно и берет срок из версии политики; сохраненные строки, нарушающие инвариант, отклоняются; типы пишут в журнал только идентификаторы.
|
||||
- `internal/adapter/primary/http/candidate_privacy_contract_test.go`: по бандлу контракта операции следуют соглашениям (схема CSRF ровно для изменений, версия в теле, нет Idempotency-Key и If-Match, одинаковый 404 для скрытия, 204 без 404 для снятия); публикация и статус поиска не несут согласия и не достигают схем друг друга; **анонимная карточка и предпросмотр не достигают схем профиля, контакта, согласия, приглашения или организации и не имеют свойства, называющего или идентифицирующего человека**, а путь организации не достигает настроек; через сгенерированный сервер схема отклоняет контакт как поле карточки, идентификатор согласия и время от клиента до реализации, валидный запрос отвечает 501, а отказанная сессия - 401.
|
||||
- `frontend/src/shared/api/privacy-contract.test.ts`: сгенерированные схемы Zod читают нового кандидата как закрытого и не ищущего с версией 0, отклоняют поле карточки, которое является именем, контактом или зарплатой, убирают согласие, время и срок из разобранных запросов, не пускают контакты в карточку, а в сгенерированных файлах организации, приглашения, потребности, профиля и согласий нет ключей настроек.
|
||||
## Контракты, инфраструктура и безопасность
|
||||
|
||||
`TestCandidatePrivacyStorage` в `backend/integration_test/candidate_privacy_test.go` использует `bootstrap(t, postgresService)`; `candidatePrivacyTables` входят в `usersDependentTables`:
|
||||
После изменения API выполните `make generate`, проверьте потребителей и `make check-generated`. Для намеренного обновления output ожидаемый diff должен быть проверен и сохранен вместе с источником.
|
||||
|
||||
- У нового профиля нет состояния публикации: после сохранения профиля все четыре таблицы пусты, а чтения не возвращают строки. Скрытая организация уникальна для кандидата и принадлежит ему; неизвестную организацию отклоняет ссылка; снятие удаляет один раз; 1001-ю запись отклоняет триггер.
|
||||
- Публикация: внешний ключ принимает только запись C2 того же аккаунта; отзыв в журнале закрывает карточку без записи; новая выдача C2 ничего не публикует; устаревшее обновление не возвращает строку; ограничения отклоняют контакт как поле, неверный порядок и неверную форму состояния.
|
||||
- Статус поиска: в фикстуре статус задается, подтверждается и снимается, а сырые строки журнала согласий, публикации и скрытых организаций остаются равными; `looking` хранит подтверждение под версией политики со сроком политики; истечение не меняет строк; ограничения отклоняют `looking` без подтверждения; в таблице нет столбца согласия, а внешний ключ ведет только на аккаунты.
|
||||
- Закрытие поверх отозванной C2 нормализует сохраненную строку и записывает закрытие; организация читает публикацию только через действующее представление и не читает, если скрыта (тот же ответ без строки, что и для неопубликованного профиля); отзыв, гоняющийся с публикацией, удерживаемой под `LockCurrentC2Record`, ждет ее и закрывает карточку после, либо не находит что блокировать; восемь параллельных скрытий при 999 записях пропускают ровно одно; очистка неподтвержденных аккаунтов удаляет записи скрытия и историю неподтвержденного аккаунта и не трогает подтвержденный. `backend/db/privacy_queries_test.go` падает, когда запрос, кроме трех запросов настроек, называет `candidate_publications`, а `TestCardTextLooksLikeContact` фиксирует отбрасывание свободного текста, похожего на контакт.
|
||||
- История: только добавление (UPDATE отклоняется, DELETE отклоняется, пока аккаунт подтвержден), только идентификаторы, форма каждого вида проверена, страницы продолжаются по позиции, опубликованные поля и запись C2 хранятся со временем. Ни в одной таблице видимости нет столбца для значения профиля, имени, контакта или файла.
|
||||
`make -C deploy check` проверяет конфигурацию и вспомогательные скрипты. `smoke` проверяет готовность инфраструктуры и HTTP-маршруты, `perimeter-test` - правила Nginx на одноразовых контейнерах. Они не заменяют бизнес-сценарий. `make -C observability check` проверяет конфигурацию мониторинга.
|
||||
|
||||
## Тесты банка заданий
|
||||
`make security` запускает проверки зависимостей, кода и секретов; `make security-images` собирает и сканирует образы. Установка инструментов и отчеты описаны в [security/](../../security/README.md).
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. `assessment_choice_test.go` проверяет формат с выбором без базы: один seed дает одинаковые варианты, ID и порядок, а по 400 seed правильный вариант встречается на каждой позиции; каждый отвлекающий вариант `lru_hits_choice.v1` пересчитывается по условию как результат именованной модели ошибки (а добор соседними значениями используется, только если модели дали меньше трех различных значений), варианты не повторяют текст, модели кэша совпадают с посчитанными вручную случаями, а модель LRU равна решателю `lru_hits.v1`, golden-тест фиксирует варианты, их ID и ключ одного seed; правильный вариант, неверный вариант, вариант чужого задания, два варианта, числовой ответ на задание с выбором и ответ с выбором на целочисленное задание оцениваются или отклоняются, как описано, проекция для кандидата содержит только непрозрачные ID и тексты, а поврежденный ключ или повторяющийся вариант замороженного варианта отклоняются. `assessment_table_test.go` проверяет табличные семейства: строки выбираются по seed, ответ - записанный, выбор для фиксированных seed зафиксирован, каждая из 39 ошибок формата (нет столбца, повтор строки, неверный ответ, повторяющийся отвлекающий вариант, слишком большое условие, вызов или конвейер в шаблоне, алгоритм рядом с таблицей и другие) отклоняется с индексом строки, хеш схемы 2 Line truncated
|
||||
## Отчет о проверке
|
||||
|
||||
`TestAssessmentBank` в `backend/integration_test/assessment_bank_test.go` использует `bootstrap(t, postgresService)` и дает каждому случаю свою мигрированную базу:
|
||||
Указывайте команду, проверенный коммит или diff, результат и существенные ограничения. Для сбоя сохраняйте воспроизводимый сценарий без секретов. Для качества оценки, подбора и производительности нужны отдельные данные, методика и измерения.
|
||||
|
||||
- Две версии одного семейства импортируются, версия 1 читается с исходным ключом, а у версии 2 ключ другой; повторный импорт ничего не меняет, та же версия с другим содержимым и пропущенный номер версии отклоняются с причиной, а сырой SQL не может изменить ключ, версию или рецензию, удалить или очистить таблицу (SQLSTATE 23000 на `assessment_families_immutable`).
|
||||
- Один seed дает одинаковые условие и эталонный ответ из сохраненной версии, а другой seed сохраняет рубрику каждого демонстрационного семейства.
|
||||
- Демонстрационный пакет импортируется черновиками; публикация каждого семейства отклоняется с `reviewer_missing`, таблица отклоняет публикацию без одобренной рецензии, а открытие `backend` отклоняется с `coverage_insufficient` и не сохраняет открытия.
|
||||
- Открытие без ссылки на политику, с неизвестной ссылкой или с версией политики, которая сейчас не действует, отклоняется с подходящей причиной.
|
||||
- Тестовый пакет с одобренной рецензией рецензента, который не является автором (фикстура правил загрузчика, а не демонстрационное содержимое), публикуется по одному семейству; категория открывается, только когда опубликованных семейств становится не меньше `max_scored_items` плюс `seed_items` политики; открытие хранит версию политики, оператора и числа, требуемое число, выведенное базой, равно числу из домена, а открытие не редактируется. Вывод из обращения одного семейства после этого заставляет чтение доступности отказывать с `coverage_insufficient`. Опубликованную версию нельзя опубликовать снова, можно один раз вывести из обращения, а назад она не идет.
|
||||
- Публикация более поздней версии семейства выводит из обращения опубликованную более старую и записывает обоих операторов; публикация более старой версии при опубликованной более новой отклоняется; таблица допускает одну опубликованную версию на семейство и отклоняет перезапись записанного публикатора.
|
||||
- Транзакция, держащая блокировку категории, заставляет открытие ждать до срока, а после освобождения блокировки открытие проходит.
|
||||
- Более старый одобренный черновик нельзя опубликовать, когда существует более новая версия, в том числе выведенная из обращения. Проверки действующей политики используют часы базы данных, без сдвига часов в тесте.
|
||||
- Пакет с табличным семейством и семейством с выбором импортируется: таблицы со схемой хеша 2, алгоритм со схемой 1; повторный импорт сообщает их как неизмененные, а сохраненные строки дважды дают одинаковые варианты; прямая правка сохраненной таблицы отклоняется как правка сохраненной версии.
|
||||
- `TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP` в `backend/integration_test/assessment_choice_http_test.go` проходит настоящую попытку по банку из алгоритма с выбором, целочисленной таблицы и таблицы с выбором: каждое задание, которое получает кандидат, содержит только разрешенные поля (для выбора - ID и тексты вариантов в сохраненном порядке, без поля ключа, seed или отвлекающего варианта), вариант чужого задания и два варианта отклоняются с 400, неверный выбор не дает баллов, а верный дает их по ключу, результат совпадает с ожидаемым числом баллов, и каждый ответ оставил наблюдение сигналов.
|
||||
- Сырые строки политики, в документе которых нет границ оцениваемых заданий, они заданы текстом, слишком большим, дробным или отрицательным числом или нет seed-заданий, отклоняются триггером открытия отказом по порогам, а не ошибкой приведения типа; сохраненная схема хеша вне списка CHECK отклоняется, а саму схему изменить нельзя.
|
||||
- В обход usecase таблица отклоняет открытие с заниженным требованием, открытие ниже покрытия, открытие под неизвестной версией политики и название с переопределением направления текста.
|
||||
- Семейства выводятся страницами по две после курсора, каждое один раз и по порядку.
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00011 вместе с остальными и проверяет, что две ее таблицы и пять функций исчезают, а таблица политик остается. Набор доказывает только правила хранилища и загрузчика: он не проверяет содержимое демонстрационного пакета, сложность задач и какие-либо грейды, не доказывает сериализацию одновременных публикаций сверх случая с удерживаемой блокировкой и не покрывает сценарий кандидата, потому что его еще нет. Интеграционным тестам нужен Docker.
|
||||
|
||||
## Тесты сигналов оценки и полосы проверки
|
||||
|
||||
`backend/internal/domain/assessment_signal_policy_test.go` и `assessment_signal_review_test.go` проверяют без базы: демо-раздел сигналов корректен и проходит круг через документ схемы 2, один раздел сигналов - допустимое расширение и никогда не получает значений по умолчанию, схема 1 отклоняет ключ, значения вне диапазона и несогласованные пороги отвергаются, время ответа следует порогам формата и отношению к медиане только на быстрой стороне в пределах одного формата и не учитывает первый элемент сессии, метки происхождения считают чередования и различные сети по времени (возврат в прежнюю сеть не новая сеть), полоса следует политике, слабые сигналы (параллельные сессии и лишние сети - одна коррелированная группа) останавливаются на «внимание», пока нет сильного сигнала, ответ считается один раз как быстрый или как отклонение, клиентские сигналы поднимают полосу только до «внимание», и имя оператора должно быть `operator:<handle>`. `backend/internal/usecase/identity/keyring_test.go` проверяет новые методы keyring: отпечаток ответа детерминирован, ключевой и привязан к версии семейства; дайджесты сессии и сети различаются между попытками (связать нельзя), между сессиями и между ключами клиента и используют отдельные ключи назначения.
|
||||
|
||||
`backend/internal/usecase/assessment/signal_review_test.go` проверяет наблюдателя и задание проверки на поддельных портах: принятый ответ сохраняет серверное время, признак отсчета от предыдущего ответа, версию ключа и только ключевой отпечаток, без текста ответа, адреса и идентификатора сессии ни в сохраняемых значениях, ни в тексте ошибки; метки происхождения пишутся только при смене сессии или сети; первый ответ планирует задание дедлайна (через минуту после дедлайна), а завершение - задание завершения; тренировочные попытки и запросы без сессии ничего не сохраняют; версия политики без раздела сигналов не создает проверку; задание отклоняет испорченную нагрузку, пропускает отсутствующую попытку, блокирует проверки пары по возрастанию идентификатора попытки до чтения любого факта и пишет их под своими закрепленными политиками, и обновляет только завершившиеся попытки на уровне «внимание», ограниченно. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` берет по 4000 seed каждого демо-семейства, строит распределение общих значений с их битами и считает вероятность того, что одна честная пара достигнет каждого демо-порога на попытке из 23 заданий; умноженная на 10 000 соперников она равна примерно 4e-5 («внимание») и 3e-9 («проверить») при целях 1e-3 и 1e-8. `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` считает, сколько ответов на семейство нужно скопированной паре, чтобы демо-пороги ее пометили (26 для «внимание» и 61 для «проверить» при 13 заданиях, 9 и 14 при 23). Модель ложных срабатываний использует только распределение эталонных ответов, а не неверные ответы и коррелированные ошибки. Цели - константы теста, выбранные здесь, а не продуктовое решение, а измерение покрывает четыре семейства, написанных ИИ.
|
||||
|
||||
`backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go` обходит каждый путь публичного контракта по ссылкам и отвергает любое свойство, имя схемы или enum, которые несли бы полосу, ее причины, отпечатки или дайджесты происхождения, и проверяет, что в квитанции сигналов по-прежнему ровно `status`, `accepted_events` и `received_at`. `backend/internal/adapter/primary/cli/assessmentreview/command_test.go` проверяет проверку аргументов до чтения окружения, выводимые поля и очищенные ошибки. Тест bootstrap проверяет, что вид задания проверки зарегистрирован.
|
||||
|
||||
`TestAssessmentSignalReviewOverHTTP` в `backend/integration_test/assessment_signal_review_http_test.go` запускает настоящий роутер, PostgreSQL и worker заданий по сроку:
|
||||
|
||||
- Кандидат отвечает на все задания за миллисекунды из двух сессий входа и с трех сетевых адресов и шлет события вставки из второй сессии. Пока worker не запущен, проверки нет, а задания проверки ожидают, то есть в транзакции кандидата ничего не считалось. Затем у попытки полоса `attention` с причинами быстрые ответы, параллельные сессии, лишние сети и клиентские сигналы, а результат `confirmed` совпадает по исходу, баллам, ограничениям и режиму с результатом столь же верной попытки с полосой `normal`; ни в одной таблице оценки, кроме таблицы проверок, нет колонки полосы.
|
||||
- Пока попытки идут, публикуется версия политики с другими порогами и под ней открывается категория. Попытки, начатые раньше, сохраняют первую версию, попытка, созданная позже, закреплена за новой версией и остается `normal` при том же поведении, а ее факты все равно сохранены.
|
||||
- Двое кандидатов с разными seed копируют одинаковые неверные ответы: у первой попытки нет признака дубликата, пока второй кандидат не ответил и не завершил попытку, после чего у обеих полоса `review` с причиной одинаковые ответы. Третья копирующая попытка брошена: пока она идет, ее не помечают, а после окончания ее задание дедлайна (часы worker сдвинуты за срок) ее помечает. Честные попытки с верными ответами не помечаются, даже если совпал ответ из малого пространства, а у попытки с одной сессией и одной сетью ровно одна метка происхождения.
|
||||
- Чтения кандидатом попытки, результата и доступности не содержат полосу, причины, отпечатки и названия сигналов. Команда оператора выводит полосу, а строки аудита пишутся для найденной и для отсутствующей попытки; имя без префикса `operator:` отклоняется. Факты, проверки и строки аудита отклоняют UPDATE и DELETE, а аудит - и TRUNCATE.
|
||||
- Журналы и текст новых таблиц и `scheduled_jobs` не содержат сетевых адресов, значений ответов, токенов сессии и CSRF.
|
||||
|
||||
`TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag` создает 30 честных кандидатов с разными seed, которые отвечают на каждое задание верно или нет случайно (фиксированный генератор), и двоих, копирующих одинаковые ответы: ни одна честная попытка не помечена дубликатом, обе копирующие помечены. Совокупность мала, поэтому тест использует пороги 32 и 44 бита, а не демо-пороги. `TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt` завершает четыре копирующие попытки одновременно среди восьми честных и запускает их задания на четырех worker сразу: ни одно задание не падает и не повторяется, и каждая копирующая попытка помечена. `TestAssessmentSignalReviewJobWaitsForTheReviewLock` держит блокировку проверки попытки в одной транзакции и проверяет, что задание проверки ждет, ничего не пишет и считает проверку по зафиксированным фактам после снятия блокировки; именно этот порядок не дает устаревшей оценке затереть более новую проверку. Тест параллельных заданий прогнан десять раз подряд (`-count=10`). `TestAssessmentSignalReviewMigrationDownRetainsAudit` проверяет, что откат миграции 33 отклоняется, пока в аудите есть строка (таблицы и строка остаются, TRUNCATE отклоняется), и проходит при пустом аудите.
|
||||
|
||||
Тесты доказывают сохраненные факты, закрепление политики, вычисление заданием и отсутствие полосы в контракте и в чтениях кандидата. Они не доказывают качество обнаружения: пороги не откалиброваны, измерение ложных срабатываний покрывает четыре написанных семейства, исследования на реальных кандидатах нет. Чтения работодателя покрыты обходом контракта, а не HTTP-вызовом каждой операции.
|
||||
|
||||
## Тесты ограничений во время попытки
|
||||
|
||||
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 4 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для текущей версии, а ее версии следуют за `CurrentSignalNoticeVersion`.
|
||||
|
||||
Модульные тесты защиты задания: `model/task-guard.test.ts` проверяет правила на небольших поддельных элементах и событиях: выделение, контекстное меню и перетаскивание отменяются на тексте задания и не трогаются в поле, сброс текста мышью никогда не заполняет поле, вставка отклоняется в полях ответа (и об этом сообщается, чтобы экран мог сказать) и разрешена в редакторе кода, пути `beforeinput` для вставки и сброса закрыты, а набор и композиция никогда не затрагиваются, копирование и вырезание отклоняются, когда цель или выделение доходят до задания, и не отклоняются внутри поля. `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что исключение для вставки есть только у редактора кода.
|
||||
|
||||
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 4. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
|
||||
|
||||
## Тесты водяного знака оценки
|
||||
|
||||
`backend/internal/domain/assessment_watermark_test.go` покрывает метку: две попытки с одним настоящим сгенерированным вариантом получают разные тексты с меткой, у которых равны канонический текст и эталонный ответ; разметка детерминирована и идемпотентна; невидимый запуск декодируется в видимый код, переживает копию двух предложений, а обрезанный, удлиненный или с неверной контрольной цифрой запуск игнорируется; доступный текст содержит только слова; выравнивание сохраненного условия с утекшим текстом читает только найденные там обороты (слова вокруг условия, например цитата или сообщение, игнорируются), согласование формулировок попытки, которая написала текст, выполняется для каждой группы оборотов, другие затравки не согласуются, фрагмент дает обороты фрагмента, посторонний текст ничего не выравнивает, а другой вариант того же семейства выравнивается на меньшее число символов, чем утекший; части между оборотами одинаковы в каждой копии условия; числовая защита оставляет `at most` в конце предложения; коды разбираются так, как их читает оператор или распознавание. `usecase/assessment/watermark_test.go` проверяет, что размечаются только root и corrective, что сохраненный снимок не меняется, что видимый код равен невидимому и что отсутствие `Watermarker` оставляет снимки как есть; `adapter/primary/http/v1/assessment_test.go` проверяет, что каждый ответ с попыткой проходит через презентер и что отказ презентера - ошибка. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) по HTTP проверяет, что реальная попытка при создании, чтении и повторе показывает код, выведенный на сервере, и текст с меткой, что учебный запуск не показывает ни того, ни другого, что в ответе только код и что в сохраненном условии метки нет. Во фронтенде у `features/assessment-watermark` есть тесты Vitest разбиения текста, доступного текста отрисованной разметки (без всего, что в `aria-hidden`, остаются ровно слова) и плитки (код и время UTC, без `@`, скрыта от вспомогательных технологий). `e2e/assessment-watermark.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): плитка есть на экране задания с кодом и временем и без email аккаунта, бледная и не перехватывает клики, у попытки без кода плитки нет, а дерево доступности размеченного условия содержит слова и ни одного символа форматирования, хотя документ их хранит. Эти тесты не запускают настоящий экранный диктор, брайлевский дисплей или другой браузер, поэтому не показывают, как диктор читает текст; они не показывают и того, сколько попыток можно различить по утечке, потому что канал формулировок дает около одного бита на группу оборотов.
|
||||
|
||||
## Тесты подсказок о съемке экрана и рабочего сеанса оценки
|
||||
|
||||
Домен и юзкейс. `assessment_signal_review_test.go` проверяет правила полосы: подсказки о съемке, лишние User-Agent и все слабые сигналы вместе останавливаются на attention при любых счетчиках, лишние агенты достигают review только рядом с сильным сигналом, а политика без порогов съемки игнорирует подсказки. `assessment_signal_policy_test.go` проверяет, что версия, опубликованная до этих полей, декодируется с ними выключенными и кодируется обратно в тот же документ (поэтому хеш содержимого сохраняется), что демо-политика не менялась, что пороги проходят туда и обратно и что значения вне диапазона или противоречивые отклоняются. `assessment_signal_test.go` покрывает два новых вида событий и отказ при наличии измерения. `assessment_work_lease_test.go` покрывает занятие: одна страница допускается, вторая получает отказ до освобождения или истечения, продление сохраняет время занятия, освобождает только владелец, неверные записи отклоняются. `usecase/assessment/work_session_test.go` прогоняет шаги занятия и проверку ответа и начала сеанса на репозиториях в памяти: вторая страница, страница без заголовка и запрос после истечения; учебный запуск и сервис без рабочих сеансов не получают отказов; источник занятия записывается только с отпечатком User-Agent. `signal_review_test.go` проверяет, что метка источника хранит User-Agent как ключевой отпечаток, пишет новую метку только при изменении, а проверка считает лишние агенты и подсказки о съемке и останавливается на attention. `keyring_test.go` проверяет, что новые отпечатки ключевые, привязаны к попытке и различны между собой. Тесты HTTP-адаптера проверяют отображение занятия, освобождения, отказа для занятой попытки при начале сеанса и ответе, новых вариантов событий и их несовпадений и ограничение User-Agent.
|
||||
|
||||
По HTTP с PostgreSQL. `TestAssessmentWorkSessionOverHTTP` создает реальную попытку и проверяет, что первая страница занимает сеанс, что вторая страница и запрос без заголовка получают 409 на занятие, начало сеанса и ответ, при этом ничего не сохраняется, что отказ не сохраняется под ключом (владелец использует оба ключа повторно), что освобождение чужой страницей ничего не меняет, что освобождение владельцем освобождает сеанс сразу, что занятие, переставшее продлеваться, заканчивается само, что неверные идентификаторы страницы дают 400, а отсутствие CSRF-токена - 403, что хранятся только отпечатки страницы и User-Agent (ни один текст таблицы не содержит идентификатор страницы или строку браузера), что события съемки хранятся без измерения и отклоняются с ним и что задание проверки дает полосу attention с учтенными лишними агентами и подсказками о съемке. `TestAssessmentSignalNoticeOverHTTP` следует за `CurrentSignalNoticeVersion`. Ограничения миграции 50 проверяются этими тестами.
|
||||
|
||||
Фронтенд. Vitest покрывает правила клавиш (`capture-keys.test.ts`), эвристику и ее наблюдателя с поддельными окнами и таймерами (`devtools-heuristic.test.ts`), сборщик (одно событие на нажатие и отпускание, без отмены, без события без задания), подключение наблюдателя к сеансу, контроллер рабочего сеанса (занято, свободно, потеряно при продлении, обрыв сети, освобождение во время продления, границы продления, `work-session.test.ts`), заголовок идентификатора страницы в команде ответа и текст версии 4 уведомления. `e2e/assessment-capture.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen и Cmd+Shift+4 записываются как события `screenshot_key` без клавиши и изображения, событие клавиши не отменяется, и тест доходит до ответа; подставная пристыкованная панель записывается как `devtools_open`; вторая вкладка с той же попыткой получает отказ с объяснением и не показывает задание, в ней ничего не начинается, первая вкладка не нарушена, а после ухода первой вкладки вторая продолжает; `pagehide` освобождает сеанс; вкладка, потерявшая сеанс при продлении, останавливается и говорит об этом. Эти тесты не показывают поведение в других браузерах и на телефоне, отдает ли операционная система сочетание странице, как выглядит настоящий снимок и как часто эвристика ошибается на настоящих окнах; подставной сервер изображает правила настоящего, которые покрывает тест HTTP.
|
||||
|
||||
## Тесты поиска источника утечки
|
||||
|
||||
`backend/internal/usecase/assessment/leak_trace_test.go` запускает поиск на репозиториях в памяти с настоящими водяными знаками: утекший текст варианта среди других слов находит правильную из трех попыток, которым выдано одно условие (по невидимой метке); без невидимых символов видимый код из текста плитки находит попытку, а одни формулировки различают попытки, которым выдано одно условие и которые выбрали разные обороты; видимый код допускает один неверно прочитанный символ, но не два; посторонний текст, слишком короткий текст и метка несуществующей попытки не находятся и объясняют причину; условие, выданное одной попытке, находится по варианту и исключается, если ее формулировки противоречат тексту; попытки с одинаковыми оборотами или текст без групп оборотов дают ambiguous без названия попытки; метка, приклеенная к другому тексту, находится с пометкой; метка и видимый код, называющие разные попытки, дают ambiguous; другой вариант того же семейства не конкурирует с утекшим, а утечка удаленной попытки не приписывается оставшемуся варианту ее семейства; утечка, оборванная внутри условия, находится, а другие слова там, где условие продолжается, - нет; каждый поиск попадает в журнал с ключевым отпечатком и без какой-либо части текста, один и тот же текст дает один отпечаток, а неудача записи в журнал проваливает поиск; неверные запросы отклоняются без цитирования текста. `domain/assessment_watermark_test.go` покрывает выравнивание и согласование формулировок (читаются только обороты, выровненные с сохраненным условием, фрагмент, посторонний текст, другой вариант, выравнивающийся на меньшее число символов), `domain/assessment_leak_trace_test.go` - запись журнала, `usecase/identity/keyring_test.go` - ключевой отпечаток текста, `config/identity_test.go` - чтение секрета, а `adapter/primary/cli/leaktrace/command_test.go` - правила аргументов, чтение из файла и стандартного ввода с ограничением, вывод (исход и фиксированные примечания, никогда не текст, честный not found), безопасные сообщения об ошибках и то, что окружение не читается, пока аргументы неверны. `TestAssessmentLeakTraceOverHTTP` (PostgreSQL) создает по HTTP две реальные попытки и проверяет, что текст задания с меткой находит первую по метке, текст без невидимых символов находит вторую по условию, текст снимка с плиткой находит первую по видимому коду и времени плитки, посторонний и короткий текст не находятся, поиск не меняет ни версию и состояние попыток, ни проверки и результаты, каждый поиск попадает в журнал без текста, журнал отклоняет UPDATE, DELETE, TRUNCATE и найденную строку без попытки, журнал переживает удаленную попытку (которая после этого не находится), а команда с секретом сервера находит попытку, тогда как с другим секретом метку не читает. Они не запускают инструмент распознавания, поэтому здесь не измерено, как команда справляется с настоящими ошибками распознаванияLine truncated
|
||||
|
||||
## Тесты внутренних уведомлений
|
||||
|
||||
Модульные тесты (`make -C backend test`, `make -C frontend test`):
|
||||
|
||||
- `domain/notification_inbox_test.go`: запись принимает только разрешенные пары типа события и типа источника (синтетическое событие с организацией, `invitation.delivered` с приглашением), новая запись непрочитана, а `MarkRead` сохраняет первое время.
|
||||
- `usecase/notification/inbox_test.go` с памятью вместо репозитория и фальшивым unit of work: список вычисляет каждый элемент по текущему источнику и при отказе показывает его без содержимого; кабинет кандидата отказывает работодателю, кабинет организации отказывает кандидату, неизвестному или неподтвержденному аккаунту и отозванному членству (оно отвечает как неизвестная организация, и для списка, и для отметки); строка репозитория вне области получателя - внутренняя ошибка; владелец и рекрутер (и остальные роли) читают и отмечают только свои элементы организации, а членство блокируется на время чтения; работодатель с неподтвержденной почтой получает `ErrInboxEmailNotVerified`; отметка сохраняет первое время и не может задеть элемент другого получателя; ссылки содержимого отклоняют внешний URL, URL без схемы, query, fragment, обратную косую черту, escape, сегмент с точками и длинный путь; синтетический преобразователь следует положению получателя, а тип источника без преобразователя недоступен.
|
||||
- `usecase/notification/inbox_handler_test.go`: повторное событие дает одну строку; неверная версия схемы, агрегат, неизвестное поле, отсутствие организации, payload не объектом, лишние данные и ID события, повторенный с другими метаданными, отклоняются окончательно; удаленный получатель пропускается; сбой хранилища остается повторяемым; неподтвержденный адрес все равно получает строку (inbox не читает состояние почты); получатель, исчезнувший между проверкой и вставкой, повторяется и затем пропускается, а не отклоняется; синтетическое событие игнорируется при выключенном флаге; событие `invitation.delivered` с тем же контрактом payload сохраняет приглашение как источник.
|
||||
- `adapter/primary/http/v1/notifications_test.go` и `adapter/primary/http/notification_contract_test.go`: отображение содержимого и запасного варианта, курсор, привязанный к аккаунту и кабинету (чужой или перепутанный курсор дает 400), отказы, соглашения четырех операций и закрытые схемы. `bootstrap/consumers_test.go` фиксирует два зарегистрированных обработчика.
|
||||
- Frontend: `features/notifications/` проверяет проверку ссылки, один повтор отметки после 403 (и отсутствие повтора после 401, 404 и 500), подписи, формулировку элемента без содержимого, ключи запросов и их удаление по аккаунту и отрисованный список (состояние прочтения словом, кнопка отметки только у непрочитанных, нет небезопасной ссылки, пустое состояние, отказ для чужого кабинета).
|
||||
|
||||
Интеграционные тесты (`make -C backend test-int`; PostgreSQL и Redis, без Kafka): `TestNotificationInboxOverHTTP` пишет синтетическое событие через настоящий писатель outbox и доставляет его через хранилище обработчика с настоящим обработчиком. Одно событие, доставленное дважды и еще раз переименованным обработчиком, дает одну строку. Затем на том же роутере проверяются список кандидата, чужой кандидат, чужой кабинет, отсутствие CSRF-токена и чужой Origin, отметка и ее повтор (первое время сохраняется), сохранение состояния прочтения, потеря содержимого, когда кандидат скрывает организацию, страницы с курсором, привязанным к аккаунту, кабинет работодателя только с его элементами организации, рекрутер со своими элементами, не участник, элемент другой организации и 404 для списка и отметки после отзыва членства. `TestSyntheticNotificationMigrationAllowlistAndGuardedRollback` и `TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows` проверяют список разрешенных значений миграции 00036, отказ отката при синтетической строке и восстановленное ограничение. `TestNotificationInboxStoreNamesTheMissingReference` проверяет, что отсутствующий получатель и отсутствующая организация различаются. `TestPostgresMigrations` покрывает подъем и откат до нуля.
|
||||
|
||||
Браузерный тест: `frontend/e2e/notifications.spec.ts` запускается в `make -C deploy test-e2e-registration`, overlay которого задает `NOTIFICATION_SYNTHETIC_ENABLED=true`. `company-fixture` (тег сборки Go `e2e`, bearer-токен, только синтетические получатели `@example.test`) добавляет синтетическое событие в настоящий outbox, поэтому relay, Kafka и обработчик `notification_inbox` доставляют его; тест ждет появления элемента. Затем он повторяет событие через fixture, который обязан сообщить, что настоящий обработчик уже применил его, и проверяет, что в списке по-прежнему один элемент. Кандидат открывает список, отмечает элемент с клавиатуры, перезагружает страницу и видит сохраненное состояние, а второй кандидат получает пустой список и 404 на тот же ID. После скрытия организации элемент остается без содержимого. Второй тест читает inbox организации как владелец, проверяет не участника, отзывает членство через fixture и проверяет, что тот же ID отклоняется, а страница не показывает содержимое.
|
||||
|
||||
Чего эти тесты не показывают: событие настоящего приглашения через Kafka и relay (`TestOrganizationInvitationSendOverHTTP` доставляет его только через хранилище обработчика), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет).
|
||||
|
||||
## Тесты демонстрационного seed
|
||||
|
||||
`backend/internal/usecase/demoseed/seeder_test.go` без базы проверяет, что сброс разрешен только для базы без аккаунтов или только с синтетическими аккаунтами, что синтетические наборы проходят правила загрузчика и совпадают между сборками (поэтому повторный импорт ничего не меняет), что подготовленные ответы имеют задуманную правильность и что в наборе данных два работодателя на синтетическом домене, один кандидат для самостоятельного прохождения и когорта не меньше чем из пяти подготовленных кандидатов. `backend/internal/adapter/primary/cli/demoseed/command_test.go` проверяет разбор аргументов, отказ каждой подкоманды без `DEMO_MODE=isolated` до чтения настроек базы, отказ при коротком пароле без вывода его значения, то, что вывод seed называет логины и подготовленные попытки, но никогда не пароль, безопасные сообщения об ошибках и отказ `check-reset` при любом аккаунте вне синтетического домена.
|
||||
|
||||
`TestDemoSeedCommand` в `backend/integration_test/demo_seed_test.go` использует `bootstrap(t, postgresService)` и запускает операторскую команду против баз с миграциями и стартовой политикой:
|
||||
|
||||
- Без изолированного режима, в том числе против недоступной базы, каждая подкоманда отказывает и ничего не записывает.
|
||||
- База с обычным аккаунтом и без seed отклоняется и seed, и проверкой сброса; аккаунт и политика остаются прежними.
|
||||
- Первый seed создает девять подтвержденных синтетических аккаунтов, две организации, три членства (владелец «Альфы» - рекрутер «Беты»), шесть подготовленных попыток с результатами, текущими синтетическими категориями, доказательствами и опубликованными карточками, версию политики seed, 28 опубликованных семейств, одно открытие, одну аттестацию и одну учебную привязку. Повторный seed от другого оператора ничего не создает и печатает тот же перечень.
|
||||
- Каждый синтетический кандидат находится на шаге онбординга `candidate_assessment`, который оставляет сохраненная анкета, а оба работодателя - на `employer_company`. Стенд, на котором кандидаты остались на шаге согласий, исправляется еще одним запуском: он печатает строку `updated` для каждого кандидата на более раннем шаге, сохраняет кандидата на более позднем шаге, ничего не создает и оставляет перечень прежним.
|
||||
- Каждая организация, имя профиля и подготовленный профиль содержат пометку о синтетических данных или о подготовке, а каждая категория - неоткалиброванная категория `synthetic_demo`.
|
||||
- Владелец «Альфы» видит ровно шесть подготовленных карточек через тот же список карточек, что использует поиск, и не видит неопубликованного кандидата для самостоятельного прохождения.
|
||||
- Безошибочное экспресс-прохождение этого кандидата через операции попытки берет три задания из учебной категории, завершается результатом `demonstration` с русским текстом итога учебного запуска и не добавляет ни категории, ни доказательства; после этого тот же кандидат может начать полный тест.
|
||||
- После регистрации обычного аккаунта в заполненной базе проверка сброса отказывает и учитывает его, повторный seed по-прежнему ничего не создает, а аккаунт не меняется.
|
||||
|
||||
`make -C deploy check-demo` (часть `make -C deploy check`) запускает `deploy/scripts/demo.sh` с записывающей заглушкой docker CLI: каждое действие отказывает без `DEMO_MODE=isolated`, с именем проекта, равным `APP_PROJECT` или без `demo`, с неверным исполнителем или без env-файла, до любой команды Docker; том проекта без демонстрационной метки отклоняется до любой команды Compose; отказ проверки сброса останавливает сброс до `down`; сброс обращается только к демонстрационному проекту и заново заполняет его; `down` сохраняет тома; манифест выпуска, который нельзя восстановить, останавливает `seed` и `reset` до любой команды Compose, а `down` его не использует. При наличии docker CLI тест также рендерит overlay: опубликован только frontend и только на loopback; у контейнера seed только сеть default, корень только для чтения и явный профиль; у каждого тома есть демонстрационная метка; демонстрационный backend включает синтетические категории; release-overlay называет образ seed `lincodex.invalid/demo-seed:<tag>` с `pull_policy: never`; backend-образы команду не содержат.
|
||||
|
||||
Тесты не запускают Make-цели против настоящего стека. Ручная проверка на одноразовом проекте: дважды `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` с одинаковыми перечнями, вход подготовленными аккаунтами при выключенной почте, экспресс-прохождение и начало полного теста, затем отказ `demo-reset` после регистрации посетителя. После проверки удалите проект командой `docker compose -p lincodex-demo-check down --volumes` с теми же переменными. Тесты не проверяют содержание синтетического банка или какой-либо грейд, а браузерный маршрут жюри здесь не покрыт. Интеграционным тестам нужен Docker.
|
||||
|
||||
## Тесты исполнителя кода
|
||||
|
||||
| Команда | Что проверяет |
|
||||
| --- | --- |
|
||||
| make -C runner test | Unit-тесты с race detector: checker, конфигурация, исходы judge на сценарном sandbox, идемпотентность и занятость менеджера прогонов, HTTP API (токен, 202/200/422/503, 400, 413, 404) и отсутствие исходника, входа и токена в логах |
|
||||
| make -C runner lint | golangci-lint для Linux, включая тесты изоляции |
|
||||
| make -C runner check-generated | Сгенерированный ogen-сервер совпадает с bundle |
|
||||
| make -C runner test-sandbox | Эталонные решения и тесты изоляции в привилегированном dev-контейнере с настоящими nsjail и cgroup v2 |
|
||||
| make -C runner test-a16 | Только набор A16 с отчетом в `runner/.reports/`; `A16_ENV` передает переменные `RUNNER_*` |
|
||||
| make -C runner a16-bundle | Пакет набора A16 для запуска на хосте исполнителя |
|
||||
| make -C deploy check-runner-dev | Dev-переключатели не попадают в production-файлы |
|
||||
| make -C deploy check-runner-vm | Скрипт VM исполнителя сохраняет границу VM: VM только со своим профилем, без общих устройств, привилегированных и raw-настроек, sudo и dev-переключателей, настройки песочницы и бюджета в unit, статический адрес без маршрута и секреты вне репозитория |
|
||||
| make -C deploy runner-vm-check | На хосте приложения: работающая VM исполнителя, см. [DEPLOY.md](DEPLOY.md#шаги-скрипта-vm) |
|
||||
| make -C deploy runner-vm-a16 | На хосте приложения: набор A16 в VM исполнителя с настройками песочницы сервиса |
|
||||
|
||||
Сначала `test-sandbox` прогоняет эталонные решения `runner/testdata/judge/manifest.json` на трех задачах с одной публичной и тремя скрытыми группами: верные и неверные решения на Python и Go получают ожидаемый исход каждой группы (`exact` и `tokens`; `numbers` на дробных ответах с абсолютным и относительным допуском; `custom` с checker на Python и на Go в nsjail); Go-код с ошибкой компиляции дает `compile_error` с сообщением `main.go:` и ни одного запущенного теста. Тест также проверяет, что группа останавливается на первом проваленном тесте, у скрытых тестов нет диагностики, а каталоги и cgroup прогонов удалены.
|
||||
|
||||
Затем `test-sandbox` запускает набор A16 (см. ниже).
|
||||
|
||||
### Набор враждебных программ A16
|
||||
|
||||
`make -C runner test-a16` собирает образ и запускает только набор A16 в привилегированном dev-контейнере без сети и без init; отчет JSON записывается в `runner/.reports/` (игнорируется Git). Случаи и ожидания описаны в `runner/testdata/hostile/manifest.json`, программы есть на Python и на Go:
|
||||
|
||||
| Категория | Попытки | Ожидание |
|
||||
| --- | --- | --- |
|
||||
| network | TCP, UDP, listen, DNS, raw ICMP, AF_PACKET и netlink-сокеты | все отказаны, проба печатает `blocked` |
|
||||
| files_and_secrets | `/etc/passwd`, `/etc/shadow`, `/run/secrets` и токен API, файлы runner, `/proc`, `/sys`, `/dev/mem`, переменные окружения с `RUNNER`, `TOKEN` или `SECRET`, запись в корень, исходник и `/out` | ничего не видно и не записывается, кроме `/tmp` |
|
||||
| privileges | setuid, setgid, chown на root, повышение rlimit | отказ, uid и gid не 0 |
|
||||
| escape | ptrace, mount нового procfs, unshare user namespace | процесс убит seccomp (SIGSYS, `runtime_error`) |
|
||||
| processes | fork bomb, на Go также thread bomb (256 горутин, заблокированных в системных вызовах, поэтому стеки остаются намного ниже лимита памяти) | лимит процессов cgroup (`runtime_error`, limit `processes`) |
|
||||
| memory | бесконечное выделение памяти, на Go также бесконечные горутины, ожидающие на канале (без новых потоков) | лимит памяти cgroup (`memory_limit_exceeded`) |
|
||||
| disk | один большой файл и заполнение `/tmp` | отказ лимита размера файла и размера tmpfs |
|
||||
| output | бесконечный вывод | лимит вывода (`output_limit_exceeded`) |
|
||||
| timeout | занятый цикл с игнорированием сигналов, сон, отсоединенный демон в своей сессии | лимит CPU, лимит стены; демон погибает вместе с PID namespace |
|
||||
|
||||
Базовые случаи проверяют, что верное решение принимается, а синтаксическая ошибка дает `compile_error`. После каждого случая тест проверяет, что каталог прогонов пуст, cgroup прогонов удалены, живых процессов uid 99999 нет и не появилось незабранных (zombie); набор работает без init, поэтому это подтверждает, что nsjail забирает каждый остановленный процесс.
|
||||
|
||||
Отчет содержит версию runner (`git describe`), ядро (`uname`), контроллеры cgroup, версию пакета и SHA-256 nsjail, профиль изоляции (аргументы nsjail для тестового прогона, политику seccomp, лимиты cgroup и rlimit), результат каждого случая и вердикт. Любой проваленный случай дает вердикт `fail` и `practice_may_be_enabled: false`: практику нельзя включать, пока набор не прошел на хосте исполнителя.
|
||||
|
||||
Проверка самого набора: `TestA16WeakenedProcessLimitIsDetected` поднимает лимит процессов до 4096 в тестовой копии конфигурации и требует, чтобы случаи категории processes провалились. Тот же эффект вручную: `make -C runner test-a16 A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096"` завершается ошибкой и отчетом `fail` ровно по трем случаям processes.
|
||||
|
||||
На хосте исполнителя набор запускается из пакета: `make -C runner a16-bundle` (по умолчанию `A16_GOARCH=amd64`) собирает `runner/bin/a16-bundle.tar.gz` с тестовым бинарником, fixtures и `run-a16.sh`; на VM его распаковывают и запускают `sudo sh run-a16.sh [report.json]` с теми же переменными `RUNNER_*`, что и у сервиса. Скрипт не обращается к сети и пишет только отчет и рабочий каталог. На production VM то же делает `make -C deploy runner-vm-a16` во временном unit systemd с настройками песочницы сервиса; результаты 2026-10-11 (20 из 20 прогонов проходят с кодом выхода 0) приведены в [DEPLOY.md](DEPLOY.md#проверка-на-хосте-приложения).
|
||||
|
||||
Что тесты не доказывают: изоляцию в production VM, пока набор там не прошел; защиту от уязвимостей ядра, nsjail или cgroup; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой.
|
||||
|
||||
## Тесты практики с кодом
|
||||
|
||||
`TestAssessmentPracticeSubmissionStorage` в `backend/integration_test/assessment_practice_http_test.go` использует `bootstrap(t, postgresService, redisService)`, изолированную базу с миграциями, настоящий роутер, usecase практики и репозиторий PostgreSQL. Поток попытки пока не выдает элементы практики, поэтому тест сам переводит настоящую попытку в `practice_pending` и создает ее основную и дополнительную практики; синтетическая задача помечает текст каждого скрытого теста. Последовательные случаи:
|
||||
|
||||
- Отладочный прогон отвечает 202 с `Cache-Control: no-store` и сохраняется ровно с одним заданием в очереди, а повтор с тем же ключом и телом возвращает тот же прогон без новой строки; тот же ключ с другим телом получает 422. Другой кандидат, другая попытка и неизвестный прогон читаются как 404.
|
||||
- Отказы ничего не сохраняют: практика другого кандидата (404), дополнительная практика, пока попытка на основной (409), и код длиннее предела задачи (400).
|
||||
- Сохраненный результат, в котором есть и скрытая группа, показывается только с публичными тестами; в ответе только поля контракта и нет скрытого текста, исходного кода и текстов тестов.
|
||||
- Финальное решение переводит практику в `pending` и сохраняется с одним заданием; повтор возвращает его, то же решение под новым ключом ничего не сохраняет, другое решение дает конфликт, а ключ с другим телом отклоняется. База отказывает в замене исходного кода или языка сохраненного решения, в его удалении и во второй записи результата. После сбоя песочницы практика принимает другое решение, а первое остается неизменным.
|
||||
- С отключенным исполнителем прогон отклоняется как недоступный, и ничего не сохраняется. В конце у каждой сохраненной отправки ровно одно задание.
|
||||
|
||||
`backend/internal/usecase/practice/request_test.go` проверяет, что запрос к исполнителю для отладочного прогона содержит только публичные примеры и тесты кандидата, а для финального решения - ровно три скрытые группы.
|
||||
|
||||
`TestAssessmentPracticeQueue` в `backend/integration_test/assessment_practice_queue_test.go` использует ту же обвязку с ограничителем в Redis (два отладочных прогона в минуту), настоящие хранилище заданий PostgreSQL, исполнитель и обработчик, поддельного исполнителя кода, который идемпотентен по ключу прогона и считает запущенные прогоны, и тестовые часы для аренд и ожиданий. Последовательные случаи:
|
||||
|
||||
- Двенадцать кандидатов одновременно запускают отладочный прогон: одиннадцать принимаются, и ровно один получает 503 `service_unavailable` с `Retry-After` и ничего не сохраняет. Пока исполнитель держит прогон, задания - одно `running` и десять `queued`, а второй обработчик ничего не берет. После того как исполнитель закончил, все одиннадцать `finished`, каждая отправка выполнена один раз и сохранено одиннадцать результатов.
|
||||
- Пока в очереди одиннадцать прогонов, финальное решение получает практику в `failed` с `sandbox_busy`: отправка не сохраняется, версия попытки не меняется. Когда очередь освободилась, то же решение принимается и завершается.
|
||||
- Занятый исполнитель возвращает задание без учтенной попытки, и задание ждет его `Retry-After`; сбой инфраструктуры учитывает одну попытку, повышает поколение и оставляет практику в `pending` без результата; после паузы следующая попытка ее завершает.
|
||||
- Обработчик убит посреди задания (его пул закрыт, поэтому вернуть задание он не может): другой обработчик ничего не берет, пока аренда жива, забирает задание после ее истечения и завершает его с тем же ключом прогона: один прогон у исполнителя, одна учтенная попытка захвата и один результат; позднее завершение от убитого обработчика отклоняется и не меняет результат.
|
||||
- Второй отладочный прогон, пока первый не завершен, и третий в пределах минуты получают 429 `rate_limited` с `Retry-After` и ничего не сохраняют.
|
||||
|
||||
`TestAssessmentPracticeRunnerProtocol` в `backend/integration_test/assessment_practice_runner_test.go` использует ту же обвязку с настоящим обработчиком очереди и настоящим клиентом исполнителя кода по TLS 1.3 (`adapter/secondary/code_runner`) против локальной подделки протокола исполнителя (`practice_runner_fixture_test.go`: TLS-сервер `httptest` с bearer-токеном, PUT и GET на `/v1/runs/{id}`, одним прогоном на ID прогона и 422 для другого содержимого). Подделка не запускает код: она узнает одну программу на Python и одну на Go, которые печатают сумму двух целых, и сравнивает их вывод с ожидаемым выводом каждого теста; у проваленного публичного теста вывод программы лежит в диагностике. Боевая VM исполнителя не вызывается. Последовательные случаи:
|
||||
|
||||
- Отладочные прогоны на Python и на Go двух кандидатов завершаются через API. Собственный тест каждого кандидата ожидает неверную сумму, поэтому диагностика показывает, что напечатала программа: `got 42` у отправки на Python и `got 123` у отправки на Go, но не наоборот. Задание хранит `runner_run_id` прогона, и подделка запустила этот прогон из исходного кода именно этой отправки. Запрос на проводе содержит только поля `groups`, `language`, `limits` и `source`, группы `public` и `custom` и ни одной скрытой, заголовки только транспортные и сервисный токен, ID прогона версии 8, который не совпадает ни с ID пользователя, попытки, практики или отправки, и ни одного из этих ID, email и cookie сессии в пути, заголовках и теле. Другой кандидат читает прогон как 404.
|
||||
- Финальное решение, ответ на которое оборван после приема прогона исполнителем (соединение сброшено), повторяется после паузы с тем же ключом прогона: у исполнителя один прогон, задание `finished` с одной учтенной попыткой и поколением 0, сохранен ровно один финальный результат, и его `runner_run_id` - этот прогон. Запрос финального решения содержит только группы `hidden-1`...`hidden-3`.
|
||||
- Отладочный прогон, ответ на который идет дольше тайм-аута запроса, завершает попытку повтором, прогон читается как `queued`, а повтор присоединяется к прогону, который исполнитель уже держит.
|
||||
- Обработчик, умерший посреди прогона (его пул закрыт), заменяется после истечения аренды обработчиком с новым клиентом, собранным из тех же настроек. Новый клиент получает тот же ID прогона, поэтому у исполнителя по-прежнему один прогон, учтен один захват, сохранены один результат и один `runner_run_id`.
|
||||
- При остановленном исполнителе отладочный прогон остается `queued`, пока есть попытки, затем читается как `failed` с `sandbox_error`, без результата и `runner_run_id`, со временем завершения. Состояние и версия попытки, число результатов и подтвержденные категории кандидата до и после одинаковы, а практика остается `not_started`. Новый отладочный прогон той же практики принимается и завершается, когда исполнитель снова работает. Финальное решение при остановленном исполнителе переводит практику в `failed` с `sandbox_error` без результата, не меняет состояние кандидата и принимается снова и завершается рабочим исполнителем. В конце ни один `runner_run_id` не принадлежит двум заданиям.
|
||||
|
||||
Подделка доказывает путь по протоколу и правила хранения и повтора; она не доказывает, что настоящая песочница собирает и запускает Python и Go, и не доказывает время работы настоящего исполнителя.
|
||||
|
||||
Unit-тесты: `usecase/practice/execute_test.go` с подделками проверяет, что недоступный исполнитель сохраняет ключ прогона, сбой инфраструктуры и повторно использованный ключ повышают поколение, неверный запрос и последняя попытка завершаются без сохраненного результата, потерянный прогон отправляется снова, остановка возвращает задание без учета попытки, а завершенный прогон без верного ID повторяется и не сохраняет результат, тогда как верный ID сохраняется вместе с результатом. `config/practice_test.go` проверяет значения по умолчанию и отклоняемые значения настроек практики. Тесты не запускают код в песочнице и не доказывают время работы настоящего исполнителя.
|
||||
|
||||
## Тесты семантического подбора
|
||||
|
||||
- ML-сервис (`make -C ml test`, без модели и сети): `tests/test_embeddings.py` проверяет контракт `POST /v1/embeddings` на детерминированном хеш-кодировщике: порядок ответа, нормировку, одинаковые векторы двух одинаковых запросов, микропакеты по длине, 503 `service_unavailable` до готовности и ready только после прогрева, 400 на лишние тексты, длину и неизвестные поля, 413 на тело больше лимита (с Content-Length и потоком), отсутствие текстов запроса в логах; `tests/test_model_files.py` проверяет lock-файл (только safetensors и конфиги, полная ревизия, без кода и pickle) и сверку размера и SHA-256.
|
||||
- Ансамбль и токен ML (`make -C ml test`): `tests/test_ensemble_and_auth.py` проверяет выбор одной из нескольких загруженных моделей полем `model` и 400 для чужой, готовность только после всех моделей, отказ от двух кодировщиков с одним id, 503 и остывание readiness после нехватки видеопамяти с восстановлением, повтор загрузки при нехватке памяти и выход по `ML_EXIT_ON_LOAD_FAILURE` при другой ошибке, 401 без токена, с неверным токеном, со схемой Basic и на `/metrics`, открытые `/healthz` и `/readyz`, только loopback без токена, отказ до чтения тела, отсутствие токена в логах и ошибках настроек, отказ точки входа слушать не-loopback адрес без токена. На CUDA вручную проверено: загрузка при нехватке памяти повторяется, процесс жив и не готов; запрос сверх предела аллокатора получает 503, `/readyz` 30 секунд отвечает 503, затем сервис снова отвечает 200.
|
||||
- Реальные модели: `make -C ml model-fetch` и `make -C ml test-model` (маркер `slow`, обычные проверки его пропускают) сверяют векторы Giga-480M и Qwen3-Embedding-0.6B с векторами исследования для четырех текстов (разница меньше 1e-4) и повторное кодирование (тот же вектор); `ML_TEST_DEVICE=cuda` запускает их на GPU в float32. 2026-10-11 обе модели прошли и на CPU, и на CUDA на GPU-хосте. Это проверка воспроизводимости рецепта, а не оценка качества; сравнение точности float16 с float32 и расчет политики ансамбля - отдельная оценка на DEV исследования (см. [DEPLOY.md](DEPLOY.md#ml-сервис-на-gpu-хосте)).
|
||||
- Backend unit: представления потребности и карточки (`domain/semantic_test.go`: точный текст исследования, только подтвержденные значения, метаданные только у проверенного репозитория), кодек float32 и косинус, калибровка (интерполяция, ступени, монотонность демонстрационной таблицы), пороги, проверка и круговой проход документа политики V5; проекты и адрес GitHub (`domain/candidate_project_test.go`: допустимые и отклоненные адреса, нормализация, лимиты, повтор репозитория, отсутствие адреса в карточке); выбор объяснения (`usecase/matching/semantic_test.go`: порядок, лимит, устаревшее название, скрытые стек и проекты не объясняют, запись поля `projects`); Fit с известным и нейтральным Sem; клиент ML (пакеты по 32, проверка ответа, circuit breaker, отсутствие текста в ошибках); GitHub (`adapter/secondary/github`: httptest, только публичный репозиторий, токен только когда задан, ETag и 304, лимиты 403/429 с ожиданием, ошибки сервера, отказ от редиректа на другой origin, ограничения размера, текст README без разметки и HTML); задания и триггер (ключи и payload без адреса репозитория, отключенные функции ничего не ставят).
|
||||
- Интеграция (Testcontainers): `TestSemanticMatchingOverHTTP` проходит через HTTP, PostgreSQL и настоящий worker заданий с фиктивным ML-сервисом (httptest по контракту) и фиктивным GitHub: сохранение профиля ставит задания без адреса в ключах, проверка репозитория и векторы карточек, нейтральный Sem и флаг до векторов потребности, затем первым идет кандидат с близким проектом, объяснение называет проект и `repository_verified`, а в ответе и карточке нет адреса и владельца репозитория; одинаковые ответы двух поисков; история доступа с полем `projects`; повторный backfill с той же меткой ничего не ставит дважды и не вызывает ML для неизменных текстов; снятие поля `projects` удаляет векторы проектов и название из объяснения; недоступный ML оставляет задание в повторе, а поиск отвечает; лимит повторной проверки (429, затем 202).
|
||||
- Ансамбль и токен в backend: unit-тесты `domain/policy_matching_ensemble_test.go` (политика ансамбля проходит проверку, объясняет Giga с ее порогами, слитый балл в среднем равен 0, калибровка монотонна и обрезана, круговой проход документа V6), `usecase/policy` (публикация ансамбля поверх V5, повтор ничего не публикует, одиночная команда не трогает ансамбль), `cli/policypublish` (трек `semantic-ensemble`), `adapter/secondary/ml` (bearer-токен в каждом запросе, 401 как недоступность без текста токена, клиент без токена не создается), `config` (токен обязателен при включенном подборе, короткий и с пробелами отклоняются, форматирование настроек токены скрывает). В `TestSemanticMatchingOverHTTP` фиктивный ML требует токен и обслуживает обе модели; после публикации ансамбля и до backfill у всех записей нейтральное `Sem`, backfill добавляет векторы `whole` Qwen3 для шести карточек и потребности без повторного кодирования Giga и без векторов элементов Qwen3, после чего у всех записей `Sem` известен.
|
||||
- Не проверено: качество ранжирования и точность объяснений на реальных данных, задержка на рабочем сервере, сборка образа ML на этой машине и запуск стенда с моделью. Внешний GitHub в тестах не вызывается.
|
||||
|
||||
## Будущая программная валидация
|
||||
|
||||
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
|
||||
|
||||
Общие тестовые данные должны быть изолированы по БД/схеме или сбрасываться последовательно. Не запускайте параллельные сценарии с общим truncate. Переиспользуйте окружение bootstrap внутри родительского теста; независимые тесты создают свои окружения. Integration job не должен молча пропускать тесты при отсутствии runtime.
|
||||
|
||||
Контракты проверяются через bundle, lint, codegen всех Go, TypeScript и Python потребителей и generated drift, включая новые untracked файлы. Frontend component tests не заменяют браузерный тест сквозного пути. После реализации продукта расширить набор Playwright сценариями двух ролей и явно синтетического кандидата без ФСП.
|
||||
|
||||
Критические будущие проверки:
|
||||
|
||||
- До принятия предложения контакты не видны другой компании ни через API, поиск, PDF, ошибки или ML объяснения.
|
||||
- Кандидат не получает доступ к чужим приглашениям, файлам, jobs или попыткам; компания не получает чужие потребности и подборки.
|
||||
- Отказ по тесту не понижает грейд; первый переход на более низкий уровень разрешен; cooldown не обходится параллельными запросами.
|
||||
- Повторная отправка результата и принятия идемпотентна; конкурентные status transitions сериализованы.
|
||||
- Выключенный ML сохраняет ручной путь; истекший worker lease восстанавливается; устаревший ответ не заменяет новый профиль.
|
||||
- Нет истории ФСП и ошибка интеграции различаются; отсутствие истории не исключает кандидата.
|
||||
- Уточнение поиска сохраняет прежний снимок; отозванный профиль исключается и из него.
|
||||
|
||||
## Будущая оценка качества
|
||||
|
||||
Подбор оценивается отдельно от функциональных тестов. Начальный план: 60-100 синтетических кандидатов, 8-12 запросов, два независимых разметчика, разбор разногласий и holdout по потребностям. Не помещать близкие копии одного профиля одновременно в настройку и holdout.
|
||||
|
||||
Сравнить keyword search, подтвержденные навыки и ML. Считать Precision@5, nDCG@5, нарушения жестких фильтров, покрытие категорий и долю релевантных результатов без ФСП истории. При выдаче короче пяти зафиксировать знаменатель до прогона и показать размер выборки. Синтетический набор не доказывает качество на реальном рынке.
|
||||
|
||||
Оценка тестов требует пилота на людях с независимой экспертной оценкой навыков. Сравнить эквивалентные формы, менять порядок, измерить agreement грейда, разброс баллов, решения по заданиям и разделение групп. Синтетические ответы годятся для отладки rubric, но не заменяют пилот.
|
||||
|
||||
ML оценка фиксирует набор документов и разметку полей, precision извлечения, выдуманные факты, полезность рекомендаций, schema-valid rate, latency и ошибки. Сохраняются модель, prompt/schema version, параметры и дата. Сравнить с простым baseline и правомерно использовать обезличенные документы.
|
||||
|
||||
Проектные ориентиры: 30 одновременных пользователей; p95 чтения профиля до 500 мс; baseline поиск до 1 секунды на демонстрационных данных без учета внешней сети. Это будущие критерии прогона, фактических результатов пока нет. ML получает отдельный latency budget.
|
||||
Старый результат не подтверждает новый коммит. Проверка health не доказывает бизнес-путь, синтетическая категория не доказывает валидность грейда, а подмена зависимости не доказывает ее реальную работу.
|
||||
+17
-43
@@ -1,55 +1,29 @@
|
||||
# Lab provisioner (labd)
|
||||
# Lab provisioner
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
A separate Go service that creates practical labs (MikroTik CHR and small Ubuntu VMs) as LXD virtual machines on the app host and deletes them. labd is the only component that talks to the LXD API: the `lxd` group is equivalent to root on the host, so the backend gets neither the LXD socket nor node addresses. The backend calls labd through the internal `api/labd/` contract over TLS with a bearer token; the backend has the `LabProvisioner` port, the generated client, and a disabled adapter (`backend/internal/adapter/secondary/lab_provisioner/`), but neither bootstrap nor a use case wires them yet.
|
||||
labd is a Go service that creates and deletes LXD VMs for practical labs. Only labd receives the LXD socket; the backend uses the `api/labd/` contract with TLS and a bearer token. Membership in the `lxd` group grants root-equivalent access to the host.
|
||||
|
||||
- `cmd/labd/` is the entry point.
|
||||
- `internal/lab/` holds the lab record and the names of its LXD objects (`lcxl-<id>-<node>` for instances, `lxl<id><nn>` for bridges) with the `user.lincodex.lab` marker.
|
||||
- `internal/template/` is the template model: nodes (`mikrotik` or `ubuntu`, profile, source snapshot, memory), L2 links, the variant plan from the seed (management addresses, NICs, and MACs), and the hooks that render cloud-init user-data and network-config or a RouterOS script and check a variant. Real templates and images are not part of this build yet: the registry is empty and CreateLab answers `validation_failed`.
|
||||
- `internal/lxd/` is a small client of the LXD REST API over its unix socket. The official `github.com/canonical/lxd/client` is not used: since LXD 5.20 it is AGPL-3.0 and pulls in most of the LXD tree. `internal/lxd/lxdfake/` is an in-memory LXD for unit tests.
|
||||
- `internal/pool/` holds admission by the host memory budget, cloning nodes from snapshots, readiness by the management TCP port, console tokens, checks, expiry, and guaranteed deletion.
|
||||
- `internal/reaper/` runs the periodic sweep (timers, deletion retries) and the reconciliation with LXD (orphans).
|
||||
- `internal/store/` keeps the state in one JSON file.
|
||||
- `internal/server/` is the HTTP API on the generated ogen server (`internal/api/`, from `codegen/ogen.yml`).
|
||||
The built-in template registry is currently empty: lab creation returns `validation_failed`. The backend contains a port and client but does not connect them in bootstrap yet. Console token issuance is implemented; WebSocket attach returns 501. A usable workflow needs prepared images, templates, and integration.
|
||||
|
||||
## How a lab works
|
||||
- `internal/template/` - nodes, links, variant parameters, and lab checkers.
|
||||
- `internal/lxd/` - LXD REST client through a Unix socket and a test fake.
|
||||
- `internal/pool/` - memory budget, creation, readiness, checking, and deletion.
|
||||
- `internal/store/`, `internal/reaper/` - JSON state, lifetimes, and orphan cleanup.
|
||||
- `internal/server/`, `internal/api/` - API and ogen code from `api/labd/`.
|
||||
|
||||
1. CreateLab (`PUT /v1/labs/{lab_id}`) checks the template and the lifetime, reserves memory and management addresses, writes the lab to the state file, and only then starts working with LXD. It answers 202 `provisioning`; a repeat with the same ID and body returns the same lab.
|
||||
2. Every link gets its own bridge without an address on the host (`ipv4.address=none`, `ipv6.address=none`): lab traffic is not routed and reaches neither the host, the application, another lab, nor the internet. Every node is copied from a prepared snapshot (a subvolume snapshot on the btrfs pool `lincodex`, seconds) and gets a management NIC on `lxdbr-labmgmt` with a fixed MAC, `security.mac_filtering`, and `security.port_isolation`, NICs on the bridges of its own lab, and the cloud-init of its variant; `security.devlxd=false`.
|
||||
3. labd starts the nodes and waits until the management port of each (22 for Ubuntu, 8728 for RouterOS) accepts a TCP connection from the host side of the bridge. The lab becomes `ready`; on an LXD error or a timeout it becomes `failed` and is deleted.
|
||||
4. A lab is deleted at `expires_at` (creation time plus `ttl_seconds`) or earlier by DeleteLab. Deletion is retried until LXD confirms that the instances and bridges are gone; only then are the memory and addresses released, and the record becomes `deleted` and stays for `LABD_DELETED_RETENTION`.
|
||||
A lab record is persisted before any LXD object is created. Deletion retries until every object is gone, then releases capacity. A corrupt state file blocks startup; `/readyz` requires successful reconciliation with LXD. The file contains variant seeds; keep it at mode 0600.
|
||||
|
||||
Deletion after a crash: a record exists in the file before the first LXD object and disappears after the last one. At startup a lab in `provisioning` becomes `failed` (`interrupted`) and is deleted; the timers of the others live in the file and fire at the first sweep. Reconciliation deletes instances and bridges with the labd prefix and marker that no record owns; an object with the prefix but without the marker is only logged. labd is not ready (`/readyz` 503) until the first reconciliation succeeds.
|
||||
## Running and checking
|
||||
|
||||
Capacity: a lab is admitted only when the memory of all its nodes fits `LABD_MEMORY_BUDGET_MIB` together with the current labs (and, when set, `LABD_MAX_LABS`). Otherwise the answer is 503 `lab_pool_busy` with Retry-After and nothing is stored. A template that does not fit the budget even alone stops labd from starting. There are no pre-started nodes: a snapshot clone is cheap, and every node must boot with its own variant.
|
||||
```sh
|
||||
make -C labd check
|
||||
```
|
||||
|
||||
Storage: a JSON file that every change rewrites completely through a temporary file, fsync, rename, and a directory fsync. labd holds a few dozen labs, so this needs no SQLite, cgo, or new dependency, and the file can be read during an incident. The file holds variant seeds, so it is `0600` in the directory of the labd user. A corrupt file stops the start: labd must not forget labs whose objects may still exist.
|
||||
This check uses the LXD fake. `make -C labd test-live` creates and deletes a real lab on a separate test LXD; set `LABD_LIVE_SOCKET` and `LABD_LIVE_SOURCE=instance/snapshot`. Never run it against production.
|
||||
|
||||
A console token (`POST /v1/labs/{lab_id}/console-tokens`) is single-use and lives at most 120 seconds; labd keeps only its SHA-256 in memory. The WebSocket attach itself is not implemented yet and answers 501. A check (`POST /v1/labs/{lab_id}/check`) calls the template checker over the management addresses; when the checker cannot reach a node, the answer is 503 `lab_unavailable`, never a failed check.
|
||||
On the app host, use the [systemd unit](../deploy/labs/lincodex-labd.service) and [example settings](../deploy/labs/labd.env.example). TLS, a token file, and restricted clients are required. `LABD_MEMORY_BUDGET_MIB`, `LABD_MAX_LABS`, and `LABD_MAX_LIFETIME` control capacity and lifetime; `internal/config/` reads all `LABD_*` settings.
|
||||
|
||||
## Settings
|
||||
Before enabling labs, test L2 isolation, MAC/port filtering, cloud-init application, and node authentication during checks. LXD group access remains privileged regardless of systemd restrictions.
|
||||
|
||||
`internal/config/` reads the `LABD_*` variables and reports the errors of all of them together. TLS (`LABD_TLS_CERT_FILE`, `LABD_TLS_KEY_FILE`) and a token (`LABD_API_TOKEN_FILE`, at least 32 characters) are required; `LABD_DEV_ALLOW_PLAINTEXT_HTTP=true` is for development only. Main defaults:
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `LABD_LISTEN_ADDRESS` | `127.0.0.1:8445` | API address; in production the gateway address of the application Docker network |
|
||||
| `LABD_ALLOWED_CLIENTS` | `127.0.0.0/8,::1/128` | networks requests are accepted from; others get 401 |
|
||||
| `LABD_LXD_SOCKET`, `LABD_LXD_PROJECT` | `/var/snap/lxd/common/lxd/unix.socket`, `default` | LXD |
|
||||
| `LABD_STATE_FILE` | `/var/lib/lincodex-labd/labs.json` | state file |
|
||||
| `LABD_MEMORY_BUDGET_MIB`, `LABD_MAX_LABS` | `3072`, `0` (no separate cap) | capacity |
|
||||
| `LABD_MAX_LIFETIME`, `LABD_PROVISION_TIMEOUT` | `2h`, `5m` | lifetime and provisioning |
|
||||
| `LABD_SWEEP_INTERVAL`, `LABD_RECONCILE_INTERVAL`, `LABD_DELETED_RETENTION` | `15s`, `5m`, `1h` | deletion |
|
||||
| `LABD_CONSOLE_TOKEN_TTL`, `LABD_CHECK_TIMEOUT`, `LABD_RETRY_AFTER` | `1m`, `1m`, `30s` | tokens, checks, Retry-After |
|
||||
| `LABD_MGMT_NETWORK`, `LABD_MGMT_SUBNET`, `LABD_MGMT_HOST_ADDRESS`, `LABD_MGMT_FIRST_ADDRESS` | `lxdbr-labmgmt`, `10.81.0.0/24`, `10.81.0.1`, `10.81.0.16` | management plane from `deploy/labs/lxd-preseed.yaml` |
|
||||
|
||||
## Running on the host
|
||||
|
||||
labd runs as a systemd service on the app host, not in Docker: `deploy/labs/lincodex-labd.service` and the example settings `deploy/labs/labd.env.example` (no secrets). The service runs as the dedicated user `lincodex-labd` with the supplementary group `lxd`, without capabilities, with `ProtectSystem=strict`, `StateDirectory=lincodex-labd`, and write access only to the LXD socket. The certificate, key, and token live in `/etc/lincodex-labd/`, readable only by that user. The host firewall opens the API port only to the application network. A compromise of labd is still a compromise of the host: the `lxd` group gives root through the LXD API, so labd accepts nothing but the described contract and never executes request data.
|
||||
|
||||
Before the rollout, check on the host what this build did not verify: that a bridge without an address gets no IPv6 link-local address (LXD disables IPv6 on such a bridge), that L2 traffic between nodes is not dropped by the Docker FORWARD chain when `br_netfilter` is loaded, that the LXD version supports `security.port_isolation` and `cloud-init:config`, and how the CHR image applies the script from cloud-init user-data. A template checker must authenticate the node (a pinned SSH host key or credentials of this lab), because a node of another lab can answer ARP for a foreign management address.
|
||||
|
||||
## Checks
|
||||
|
||||
From the repository root, `make -C labd check` runs formatting, the Linux build, unit tests with the race detector, the generated code check, and lint. The tests use the in-memory LXD: creating and deleting a lab (nodes on isolated bridges that disappear completely), restarting labd in the middle of a lab's life and the timer deletion after it, a restart during provisioning, orphans, a failing and retried deletion, and the capacity limit with 503 for the extra lab. `make -C labd test-live` creates and deletes one bridge and one instance on a real LXD; it does not run without `LABD_LIVE_SOCKET` and `LABD_LIVE_SOURCE` and must not target the production host.
|
||||
Networks and host preparation: [DEPLOYMENT.md](../docs/en/DEPLOYMENT.md#labs-and-labd).
|
||||
+17
-43
@@ -1,55 +1,29 @@
|
||||
# Провиженер лабораторий (labd)
|
||||
# Провиженер лабораторий
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
Отдельный Go-сервис, который создает практические лаборатории (MikroTik CHR и небольшие Ubuntu VM) как LXD-машины на app-хосте и удаляет их. labd - единственный компонент, который обращается к LXD API: группа `lxd` равна root на хосте, поэтому backend не получает ни сокет LXD, ни адреса узлов. Backend вызывает labd по внутреннему контракту `api/labd/` с TLS и bearer-токеном; в backend есть порт `LabProvisioner`, сгенерированный клиент и отключенный адаптер (`backend/internal/adapter/secondary/lab_provisioner/`), но ни bootstrap, ни usecase их пока не подключают.
|
||||
labd - Go-сервис, который создает и удаляет LXD VM для практических лабораторий. Только он получает сокет LXD; backend обращается по контракту `api/labd/` с TLS и bearer-токеном. Группа `lxd` дает права, эквивалентные root на хосте.
|
||||
|
||||
- `cmd/labd/` - точка входа.
|
||||
- `internal/lab/` - запись лаборатории и имена LXD-объектов (`lcxl-<id>-<узел>` для машин, `lxl<id><nn>` для мостов) с меткой `user.lincodex.lab`.
|
||||
- `internal/template/` - модель шаблона: узлы (`mikrotik` или `ubuntu`, профиль, снимок-источник, память), L2-связи, план варианта по seed (адреса управления, NIC и MAC) и хуки рендера (cloud-init user-data и network-config, скрипт RouterOS) и проверки. Реальные шаблоны и образы в этой сборке еще не входят: реестр пуст, и CreateLab отвечает `validation_failed`.
|
||||
- `internal/lxd/` - небольшой клиент LXD REST API через unix-сокет. Официальный `github.com/canonical/lxd/client` не используется: с LXD 5.20 он под AGPL-3.0 и тянет большую часть дерева LXD. `internal/lxd/lxdfake/` - LXD в памяти для unit-тестов.
|
||||
- `internal/pool/` - допуск по бюджету памяти хоста, клонирование узлов из снимков, готовность по TCP-порту управления, console-токены, проверка, истечение и гарантированное удаление.
|
||||
- `internal/reaper/` - периодический sweep (таймеры, повтор удаления) и сверка с LXD (сироты).
|
||||
- `internal/store/` - состояние в одном JSON-файле.
|
||||
- `internal/server/` - HTTP API на сгенерированном ogen-сервере (`internal/api/`, из `codegen/ogen.yml`).
|
||||
Сейчас встроенный реестр шаблонов пуст: создание лаборатории отвечает `validation_failed`. Backend содержит порт и клиент, но bootstrap их пока не подключает. Выдача console-токенов реализована, WebSocket attach отвечает 501. Рабочий сценарий требует подготовленных образов, шаблонов и интеграции.
|
||||
|
||||
## Как работает лаборатория
|
||||
- `internal/template/` - узлы, связи, параметры варианта и checker лаборатории.
|
||||
- `internal/lxd/` - LXD REST-клиент через unix socket и fake для тестов.
|
||||
- `internal/pool/` - бюджет памяти, создание, готовность, проверка и удаление.
|
||||
- `internal/store/`, `internal/reaper/` - состояние в JSON, сроки жизни и уборка сирот.
|
||||
- `internal/server/`, `internal/api/` - API и ogen-код из `api/labd/`.
|
||||
|
||||
1. CreateLab (`PUT /v1/labs/{lab_id}`) проверяет шаблон и время жизни, резервирует память и адреса управления, записывает лабораторию в файл состояния и только после этого начинает работу с LXD. Ответ 202 `provisioning`; повтор с тем же ID и телом возвращает ту же лабораторию.
|
||||
2. Для каждой связи создается свой мост без адреса на хосте (`ipv4.address=none`, `ipv6.address=none`): трафик лаборатории не маршрутизируется и не доходит до хоста, приложения, другой лаборатории или интернета. Каждый узел копируется из подготовленного снимка (на btrfs-пуле `lincodex` это snapshot подтома, секунды), получает NIC управления на `lxdbr-labmgmt` с фиксированным MAC, `security.mac_filtering` и `security.port_isolation`, NIC на мостах своей лаборатории и cloud-init своего варианта; `security.devlxd=false`.
|
||||
3. labd запускает узлы и ждет, пока порт управления каждого (22 для Ubuntu, 8728 для RouterOS) примет TCP-соединение с хостовой стороны моста. Лаборатория становится `ready`; при ошибке LXD или по таймауту - `failed` и удаляется.
|
||||
4. Лаборатория удаляется в `expires_at` (время создания плюс `ttl_seconds`) или раньше по DeleteLab. Удаление повторяется, пока LXD не подтвердит, что машин и мостов нет; только тогда освобождаются память и адреса, а запись становится `deleted` и хранится `LABD_DELETED_RETENTION`.
|
||||
Запись лаборатории сохраняется до создания LXD-объектов. Удаление повторяется до исчезновения всех объектов, после чего освобождается емкость. Поврежденный файл состояния останавливает запуск; `/readyz` требует успешной сверки с LXD. Файл содержит seed вариантов, храните его с правами 0600.
|
||||
|
||||
Гарантия удаления после сбоя: запись появляется в файле до первого LXD-объекта и исчезает после последнего. При старте лаборатория в `provisioning` становится `failed` (`interrupted`) и удаляется; таймеры остальных живут в файле и срабатывают при первом sweep. Сверка удаляет машины и мосты с префиксом и меткой labd, которых нет ни в одной записи; объект с префиксом, но без метки, только попадает в лог. labd не готов (`/readyz` 503), пока первая сверка не прошла.
|
||||
## Запуск и проверки
|
||||
|
||||
Емкость: лаборатория допускается, только если память всех ее узлов помещается в `LABD_MEMORY_BUDGET_MIB` вместе с текущими лабораториями (и, если задан, в `LABD_MAX_LABS`). Иначе ответ 503 `lab_pool_busy` с Retry-After, ничего не сохраняется. Шаблон, который не помещается в бюджет даже один, не дает labd запуститься. Готовых заранее запущенных узлов нет: клон снимка дешев, а каждый узел должен загрузиться со своим вариантом.
|
||||
```sh
|
||||
make -C labd check
|
||||
```
|
||||
|
||||
Хранилище: JSON-файл, который при каждом изменении целиком пишется во временный файл, fsync, rename и fsync каталога. Лабораторий десятки, поэтому этого хватает без SQLite, cgo и новых зависимостей, а файл читается при разборе инцидента. В файле есть seed вариантов, поэтому он `0600` в каталоге пользователя labd. Поврежденный файл останавливает старт: labd не должен забыть лаборатории, объекты которых еще могут существовать.
|
||||
Проверка использует LXD fake. `make -C labd test-live` создает и удаляет настоящую лабораторию на отдельном тестовом LXD; нужны `LABD_LIVE_SOCKET` и `LABD_LIVE_SOURCE=instance/snapshot`. Не запускайте ее против production.
|
||||
|
||||
Console-токен (`POST /v1/labs/{lab_id}/console-tokens`) одноразовый, до 120 секунд, labd хранит только его SHA-256 в памяти. Сам WebSocket attach пока не реализован и отвечает 501. Проверка (`POST /v1/labs/{lab_id}/check`) вызывает checker шаблона по адресам управления; если checker не может дойти до узла, ответ 503 `lab_unavailable`, а не проваленная проверка.
|
||||
На app-хосте используйте [systemd unit](../deploy/labs/lincodex-labd.service) и [пример настроек](../deploy/labs/labd.env.example). Обязательны TLS, файл токена и ограниченный список клиентов. `LABD_MEMORY_BUDGET_MIB`, `LABD_MAX_LABS` и `LABD_MAX_LIFETIME` задают емкость и срок; все `LABD_*` читает `internal/config/`.
|
||||
|
||||
## Настройки
|
||||
Перед включением проверьте L2-изоляцию, MAC/port filtering, применение cloud-init и подлинность узлов при проверке. Доступ к группе `lxd` остается привилегированным независимо от ограничений systemd.
|
||||
|
||||
Переменные `LABD_*` читает `internal/config/`; ошибки всех переменных выводятся вместе. Обязательны TLS (`LABD_TLS_CERT_FILE`, `LABD_TLS_KEY_FILE`) и токен (`LABD_API_TOKEN_FILE`, не короче 32 символов); `LABD_DEV_ALLOW_PLAINTEXT_HTTP=true` только для разработки. Основные значения по умолчанию:
|
||||
|
||||
| Переменная | По умолчанию | Смысл |
|
||||
| --- | --- | --- |
|
||||
| `LABD_LISTEN_ADDRESS` | `127.0.0.1:8445` | адрес API; в production - адрес шлюза Docker-сети приложения |
|
||||
| `LABD_ALLOWED_CLIENTS` | `127.0.0.0/8,::1/128` | сети, из которых принимаются запросы; остальные получают 401 |
|
||||
| `LABD_LXD_SOCKET`, `LABD_LXD_PROJECT` | `/var/snap/lxd/common/lxd/unix.socket`, `default` | LXD |
|
||||
| `LABD_STATE_FILE` | `/var/lib/lincodex-labd/labs.json` | файл состояния |
|
||||
| `LABD_MEMORY_BUDGET_MIB`, `LABD_MAX_LABS` | `3072`, `0` (без отдельного лимита) | емкость |
|
||||
| `LABD_MAX_LIFETIME`, `LABD_PROVISION_TIMEOUT` | `2h`, `5m` | время жизни и подготовки |
|
||||
| `LABD_SWEEP_INTERVAL`, `LABD_RECONCILE_INTERVAL`, `LABD_DELETED_RETENTION` | `15s`, `5m`, `1h` | удаление |
|
||||
| `LABD_CONSOLE_TOKEN_TTL`, `LABD_CHECK_TIMEOUT`, `LABD_RETRY_AFTER` | `1m`, `1m`, `30s` | токены, проверка, Retry-After |
|
||||
| `LABD_MGMT_NETWORK`, `LABD_MGMT_SUBNET`, `LABD_MGMT_HOST_ADDRESS`, `LABD_MGMT_FIRST_ADDRESS` | `lxdbr-labmgmt`, `10.81.0.0/24`, `10.81.0.1`, `10.81.0.16` | план управления из `deploy/labs/lxd-preseed.yaml` |
|
||||
|
||||
## Запуск на хосте
|
||||
|
||||
labd работает как systemd-сервис на app-хосте, не в Docker: `deploy/labs/lincodex-labd.service` и пример настроек `deploy/labs/labd.env.example` (без секретов). Сервис запускается от отдельного пользователя `lincodex-labd` с дополнительной группой `lxd`, без capabilities, с `ProtectSystem=strict`, `StateDirectory=lincodex-labd` и правом записи только на сокет LXD. Сертификат, ключ и токен лежат в `/etc/lincodex-labd/` с правами только для этого пользователя. Порт API открывается в межсетевом экране хоста только для сети приложения. Компрометация labd остается компрометацией хоста: группа `lxd` дает root через LXD API, поэтому labd не принимает ничего, кроме описанного контракта, и не исполняет данные запроса.
|
||||
|
||||
Перед выкаткой на хосте нужно проверить то, что в этой сборке не проверялось: что мост без адреса не получает IPv6 link-local (LXD отключает IPv6 на таком мосту), что пересылаемый между узлами L2-трафик не режется цепочкой FORWARD Docker при включенном `br_netfilter`, что `security.port_isolation` и `cloud-init:config` поддерживаются версией LXD, и как образ CHR применяет скрипт из cloud-init user-data. Checker шаблона должен проверять подлинность узла (закрепленный ключ хоста SSH или учетные данные этой лаборатории), потому что узел другой лаборатории может ответить ARP на чужой адрес управления.
|
||||
|
||||
## Проверки
|
||||
|
||||
Из корня: `make -C labd check` запускает форматирование, сборку для Linux, unit-тесты с race detector, проверку generated-кода и lint. Тесты используют LXD в памяти: создание и удаление лаборатории (узлы на изолированных мостах и их полное исчезновение), перезапуск labd посреди жизни лаборатории и удаление по таймеру после него, перезапуск во время подготовки, сироты, отказ удаления и повтор, лимит емкости и 503 для лишней лаборатории. `make -C labd test-live` создает и удаляет один мост и одну машину на настоящем LXD; без `LABD_LIVE_SOCKET` и `LABD_LIVE_SOURCE` он не запускается, и его нельзя направлять на production-хост.
|
||||
Сети и подготовка хоста: [DEPLOYMENT.md](../docs/ru/DEPLOYMENT.md#лаборатории-и-labd).
|
||||
+18
-9
@@ -2,15 +2,24 @@
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
A separate Python service using FastAPI. It serves `POST /v1/embeddings` with the pinned Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B models for semantic matching (the `ML_EMBEDDER` list; the optional `model` field selects the model, and a request for a model the service has not loaded gets 400), plus `/healthz`, `/readyz`, and metrics. It runs on CPU or CUDA (`ML_DEVICE`, `ML_DTYPE`, `ML_CUDA_MEMORY_LIMIT_MB`); a lack of device memory gives 503, not a crash. Every route except `/healthz` and `/readyz` requires a bearer token (`ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE`); without a token the service answers loopback callers only, and `python -m lincodex_ml.serve` does not listen on a non-loopback address. `/readyz` returns 503 until the models are loaded and warmed up, and always without a model (`ML_EMBEDDER=none`, the default outside the image). The model files are pinned by the lock files `model/*.lock.json` and verified by SHA-256; see [deployment](../docs/en/DEPLOY.md#separate-ml-compose-project) and [the GPU host](../docs/en/DEPLOY.md#ml-service-on-a-gpu-host).
|
||||
Python/FastAPI embedding service for semantic matching. `POST /v1/embeddings` uses Giga-Embeddings-instruct-480M or Qwen3-Embedding-0.6B; model revisions and file SHA-256 hashes are pinned in `model/`. Text generation and resume analysis are outside the current HTTP service.
|
||||
|
||||
- `src/lincodex_ml/` contains the application, HTTP routes, and infrastructure code.
|
||||
- `codegen/` configures Pydantic model generation from `api/ml/`.
|
||||
- `tests/` checks service health, the embedding contract with a fake encoder, several models, the token, a lack of device memory, the model locks, and (marked `slow`, `make -C ml test-model`) the real models against the study vectors.
|
||||
- `model/` pins the model revisions and the SHA-256 of their files.
|
||||
- `scripts/` checks Pydantic models generated from the OpenAPI 3.2 fixture.
|
||||
- `pyproject.toml` and `uv.lock` define dependencies and Python tool settings.
|
||||
- `src/lincodex_ml/` - API, model loading, and CPU/CUDA inference.
|
||||
- `codegen/` - Pydantic models generated from `api/ml/`.
|
||||
- `tests/` - unit, contract, and separate real-model tests.
|
||||
- `model/` - weight revisions and hashes; `uv.lock` - Python dependencies.
|
||||
|
||||
From the repository root, `make -C ml check` runs checks, `make -C ml run` starts the service locally on 127.0.0.1:8000, and `make -C ml cuda-requirements` writes the dependency list of a GPU host. To use its separate Compose project, run `make -C deploy ml-up` after preparing `.env`.
|
||||
From the repository root:
|
||||
|
||||
See [development](../docs/en/DEVELOPMENT.md) and [deployment](../docs/en/DEPLOY.md).
|
||||
```sh
|
||||
make -C ml install
|
||||
make -C ml check
|
||||
make -C deploy ml-build
|
||||
make -C deploy ml-up
|
||||
```
|
||||
|
||||
Compose needs a running core and the shared `ML_SERVICE_TOKEN` in `.env`. The image includes both models; `/readyz` returns 200 after loading and warmup. The configured bearer token protects every route except `/healthz` and `/readyz`. Without a token, access is limited to loopback clients.
|
||||
|
||||
For a local process, run `make -C ml model-fetch`, then `make -C ml run` with `ML_EMBEDDER` and model directories in the environment. `make -C ml test-model` checks real weights; `cuda-requirements` prepares GPU dependencies. Ordinary tests do not establish matching quality or model performance.
|
||||
|
||||
Semantic policy setup, CPU Compose, and a GPU host: [DEPLOYMENT.md](../docs/en/DEPLOYMENT.md#separate-ml-compose-project).
|
||||
+18
-9
@@ -2,15 +2,24 @@
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
Отдельный Python-сервис на FastAPI. Он отдает `POST /v1/embeddings` с закрепленными моделями Giga-Embeddings-instruct-480M и Qwen3-Embedding-0.6B для семантического подбора (список `ML_EMBEDDER`, необязательное поле `model` выбирает модель; запрос модели, которую сервис не загрузил, получает 400), а также `/healthz`, `/readyz` и метрики. Работает на CPU или CUDA (`ML_DEVICE`, `ML_DTYPE`, `ML_CUDA_MEMORY_LIMIT_MB`); нехватка видеопамяти дает 503, а не падение процесса. Все маршруты, кроме `/healthz` и `/readyz`, требуют bearer-токен (`ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE`); без токена сервис отвечает только loopback-клиентам, а `python -m lincodex_ml.serve` не слушает не-loopback адрес. `/readyz` отвечает 503, пока модели не загружены и не прогреты, и всегда без моделей (`ML_EMBEDDER=none`, значение по умолчанию вне образа). Файлы моделей закреплены lock-файлами `model/*.lock.json` и проверяются по SHA-256; см. [развертывание](../docs/ru/DEPLOY.md#отдельный-ml-compose) и [GPU-хост](../docs/ru/DEPLOY.md#ml-сервис-на-gpu-хосте).
|
||||
Python/FastAPI-сервис эмбеддингов для семантического подбора. `POST /v1/embeddings` использует Giga-Embeddings-instruct-480M или Qwen3-Embedding-0.6B; модели и SHA-256 файлов закреплены в `model/`. Генерация текстов и анализ резюме не входят в текущий HTTP-сервис.
|
||||
|
||||
- `src/lincodex_ml/` - приложение, HTTP-маршруты и инфраструктурный код.
|
||||
- `codegen/` - настройки генерации моделей Pydantic из `api/ml/`.
|
||||
- `tests/` - проверки состояния сервиса, контракта эмбеддингов на фиктивном кодировщике, нескольких моделей, токена, нехватки видеопамяти, lock-файлов и (маркер `slow`, `make -C ml test-model`) реальных моделей против векторов исследования.
|
||||
- `model/` - закрепленные ревизии моделей и SHA-256 их файлов.
|
||||
- `scripts/` - проверка Pydantic-моделей, сгенерированных из фикстуры OpenAPI 3.2.
|
||||
- `pyproject.toml` и `uv.lock` - зависимости и настройки Python-инструментов.
|
||||
- `src/lincodex_ml/` - API, загрузка моделей и CPU/CUDA inference.
|
||||
- `codegen/` - генерация Pydantic-моделей из `api/ml/`.
|
||||
- `tests/` - unit, контрактные и отдельные тесты реальных моделей.
|
||||
- `model/` - ревизии и хеши весов; `uv.lock` - зависимости Python.
|
||||
|
||||
Из корня: `make -C ml check` запускает проверки, `make -C ml run` - сервис локально на 127.0.0.1:8000, `make -C ml cuda-requirements` - список зависимостей для GPU-хоста. Для запуска через отдельный Compose используйте `make -C deploy ml-up` после подготовки `.env`.
|
||||
Из корня репозитория:
|
||||
|
||||
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md) и [развертывание](../docs/ru/DEPLOY.md).
|
||||
```sh
|
||||
make -C ml install
|
||||
make -C ml check
|
||||
make -C deploy ml-build
|
||||
make -C deploy ml-up
|
||||
```
|
||||
|
||||
Compose требует запущенный core и общий `ML_SERVICE_TOKEN` в `.env`. Образ включает обе модели; `/readyz` отвечает 200 после их загрузки и прогрева. Все маршруты, кроме `/healthz` и `/readyz`, защищены настроенным bearer-токеном. Без токена доступ разрешен только с loopback.
|
||||
|
||||
Локальный процесс: `make -C ml model-fetch`, затем `make -C ml run` с `ML_EMBEDDER` и каталогами моделей в окружении. `make -C ml test-model` проверяет реальные веса, а `cuda-requirements` готовит зависимости для GPU. Обычные тесты не доказывают качество подбора или производительность модели.
|
||||
|
||||
Подключение семантической политики, CPU Compose и GPU-host: [DEPLOYMENT.md](../docs/ru/DEPLOYMENT.md#отдельный-ml-compose).
|
||||
@@ -2,13 +2,19 @@
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
Configuration for collecting metrics and logs, with dashboards for service health.
|
||||
Prometheus, Loki, Grafana, and Grafana Alloy configuration. The stack starts separately from the application, after core.
|
||||
|
||||
- `prometheus/` configures metric collection and ML targets; `prometheus/rules/` holds the alert rules and `prometheus/tests/` their `promtool` unit tests.
|
||||
- `loki/` configures log storage; `alloy/` handles log collection and forwarding.
|
||||
- `grafana/` contains data sources and dashboards for Go, PostgreSQL, Redis, SeaweedFS, the host, and the Lincodex product metrics: API latency and errors, outbox lag, consumers and scheduled jobs, mail deliveries and quota, and assessment answer saves.
|
||||
- `scripts/verify-product-metrics.sh` is the end-to-end check behind `make -C observability verify-product-metrics`.
|
||||
- `prometheus/` - metric collection, alert rules, and rule tests.
|
||||
- `loki/` - log storage.
|
||||
- `alloy/` - container logs through a restricted Docker socket proxy.
|
||||
- `grafana/` - data sources and service and product dashboards.
|
||||
- `scripts/` - integration checks for metrics and log privacy.
|
||||
|
||||
From the repository root, `make -C observability check` validates configuration and runs the alert rule tests using Docker. `make -C observability verify-product-metrics` is an explicit end-to-end check, not part of `check`: it starts two separate throwaway Compose projects, core and monitoring, and checks the product metrics, the dashboard, and that a fixture address reaches neither metrics nor logs. Start monitoring separately after the core services with `make -C deploy monitoring-up`; its Compose file lives in `deploy/docker/`.
|
||||
```sh
|
||||
make -C observability check
|
||||
make -C deploy monitoring-up
|
||||
```
|
||||
|
||||
See the [deployment guide](../docs/en/DEPLOY.md).
|
||||
Grafana listens on `127.0.0.1:3000`; other services stay on internal networks. Alert notifications and the React telemetry SDK are not connected yet. Treat Alloy's Docker API access as privileged even when writes are disabled.
|
||||
|
||||
`make -C observability verify-product-metrics` checks metrics, the dashboard, and the absence of fixture personal data in telemetry on disposable stands. Access, exporter, and retention settings: [DEPLOYMENT.md](../docs/en/DEPLOYMENT.md#separate-monitoring-compose-project).
|
||||
+13
-7
@@ -2,13 +2,19 @@
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
Настройки сбора метрик и логов, а также готовые дашборды для технического состояния сервисов.
|
||||
Конфигурации Prometheus, Loki, Grafana и Grafana Alloy. Стек запускается отдельно от приложения, после core.
|
||||
|
||||
- `prometheus/` - сбор метрик и список ML-targets; `prometheus/rules/` - правила alerts, `prometheus/tests/` - их unit-тесты для `promtool`.
|
||||
- `loki/` - хранение логов; `alloy/` - их сбор и отправка.
|
||||
- `grafana/` - источники данных и дашборды Go, PostgreSQL, Redis, SeaweedFS, хоста и продуктовых метрик Lincodex: задержка и ошибки API, отставание outbox, обработчики и задания по сроку, доставки и квоты почты, сохранение ответов теста.
|
||||
- `scripts/verify-product-metrics.sh` - сквозная проверка за `make -C observability verify-product-metrics`.
|
||||
- `prometheus/` - сбор метрик, alert rules и их тесты.
|
||||
- `loki/` - хранение логов.
|
||||
- `alloy/` - сбор логов контейнеров через ограниченный Docker socket proxy.
|
||||
- `grafana/` - источники данных и дашборды сервисов и продукта.
|
||||
- `scripts/` - интеграционная проверка метрик и приватности логов.
|
||||
|
||||
Из корня: `make -C observability check` проверяет конфигурации и запускает тесты правил alerts через Docker. `make -C observability verify-product-metrics` - явная сквозная проверка, не входящая в `check`: она поднимает два отдельных одноразовых Compose проекта, core и monitoring, и проверяет продуктовые метрики, dashboard и то, что fixture адрес не попадает ни в метрики, ни в логи. Сам стек запускается отдельно после основных сервисов командой `make -C deploy monitoring-up`; его Compose-файл находится в `deploy/docker/`.
|
||||
```sh
|
||||
make -C observability check
|
||||
make -C deploy monitoring-up
|
||||
```
|
||||
|
||||
Подробнее: [развертывание](../docs/ru/DEPLOY.md).
|
||||
Grafana слушает `127.0.0.1:3000`; остальные сервисы остаются во внутренних сетях. Уведомления по alerts и React SDK телеметрии пока не подключены. Доступ Alloy к Docker API считается привилегированным, даже когда запись запрещена.
|
||||
|
||||
`make -C observability verify-product-metrics` проверяет метрики, дашборд и отсутствие тестовых персональных данных в телеметрии на одноразовых стендах. Настройки доступа, exporter и хранения: [DEPLOYMENT.md](../docs/ru/DEPLOYMENT.md#отдельный-monitoring-compose).
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
# Production image of the code runner. It runs only on the dedicated runner
|
||||
# host or VM, never on the core application host; see docs/en/DEPLOY.md.
|
||||
# host or VM, never on the core application host; see docs/en/DEPLOYMENT.md.
|
||||
#
|
||||
# Base images are build arguments so that a release build can pin each one to
|
||||
# the digest it resolved; the defaults keep the agreed tags.
|
||||
|
||||
+16
-11
@@ -2,17 +2,22 @@
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
A separate Go service that runs untrusted candidate code in nsjail and checks it against public and hidden tests. It supports Python 3 and Go (a separate compile phase with a prebuilt standard library) and the `exact`, `tokens`, `numbers`, and `custom` (a family program in nsjail) checkers. The backend calls it through the internal `api/runner/` contract over TLS with a bearer token; no backend use case calls it yet.
|
||||
Go service that executes candidate Python and Go code in nsjail. It checks public and hidden tests with `exact`, `tokens`, `numbers`, or a custom checker. The backend uses it through the `CodeRunner` port and practice queue; the connection is disabled by default.
|
||||
|
||||
- `cmd/runner/` is the entry point and the container `healthcheck`.
|
||||
- `internal/sandbox/` holds nsjail, cgroup v2, seccomp, run directories, and stopping on limits.
|
||||
- `internal/judge/` holds languages, the syntax check step, and test and group outcomes.
|
||||
- `internal/checker/` holds the checker interface and the `exact`, `tokens`, and `numbers` comparisons; the custom checker lives in `internal/judge/`.
|
||||
- `internal/judgetest/` and `testdata/judge/` are reference Python and Go solutions with their expected group results.
|
||||
- `internal/jobs/` keeps runs in memory, makes them idempotent by run ID, and bounds concurrent runs.
|
||||
- `internal/server/` is the HTTP API on the generated ogen server (`internal/api/`, from `codegen/ogen.yml`).
|
||||
- `internal/isolationtest/`, `testdata/hostile/`, and `scripts/run-a16.sh` are the A16 hostile-program suite in Python and Go, its report, and its run on the runner host.
|
||||
- `internal/sandbox/` - namespaces, cgroup v2, seccomp, and limits.
|
||||
- `internal/judge/`, `internal/checker/` - execution and result checking.
|
||||
- `internal/jobs/` - in-memory runs and concurrency limits.
|
||||
- `internal/server/`, `internal/api/` - HTTP API and ogen code from `api/runner/`.
|
||||
- `internal/isolationtest/`, `testdata/hostile/` - A16 isolation tests.
|
||||
|
||||
From the repository root, `make -C runner check` runs formatting, build, unit tests, the generated code check, and lint; `make -C runner test-sandbox` builds the image and runs the reference solutions and the A16 suite in a privileged dev container; `make -C runner test-a16` runs only the A16 suite with a report, and `make -C runner a16-bundle` builds it for the runner host. Local start: `make -C deploy runner-dev-up` (development only).
|
||||
```sh
|
||||
make -C runner check
|
||||
make -C deploy runner-dev-up
|
||||
make -C deploy runner-dev-down
|
||||
```
|
||||
|
||||
Production: the service runs only in the dedicated runner VM, never on the core host. More: [deployment](../docs/en/DEPLOY.md#code-runner), [architecture](../docs/en/ARCHITECTURE.md#code-runner), and [checks](../docs/en/TESTING.md#code-runner-tests).
|
||||
The development container is privileged, serves HTTP only on loopback, and must not run on the core host. Production requires a dedicated VM with its own kernel, no application secrets or outgoing connections, TLS 1.3, and a service token. The backend cannot connect directly to development HTTP.
|
||||
|
||||
`make -C runner test-sandbox` checks solutions and A16 in a privileged development container. `test-a16` saves an isolation report; `a16-bundle` builds the checks for the target VM. Unit tests do not establish isolation of a real VM.
|
||||
|
||||
Settings and activation steps: [DEPLOYMENT.md](../docs/en/DEPLOYMENT.md#code-runner).
|
||||
+16
-11
@@ -2,17 +2,22 @@
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
Отдельный Go-сервис, который запускает недоверенный код кандидата в nsjail и проверяет его на публичных и скрытых тестах. Поддерживаются Python 3 и Go (отдельная фаза компиляции с заранее собранной стандартной библиотекой); checker `exact`, `tokens`, `numbers` и `custom` (программа семейства в nsjail). Backend вызывает его по внутреннему контракту `api/runner/` с TLS и bearer-токеном; ни один usecase backend пока не использует его.
|
||||
Go-сервис для запуска кода кандидата на Python и Go в nsjail. Проверяет публичные и скрытые тесты через `exact`, `tokens`, `numbers` или custom checker. Backend использует его через порт `CodeRunner` и очередь практики; по умолчанию подключение выключено.
|
||||
|
||||
- `cmd/runner/` - точка входа и `healthcheck` для контейнера.
|
||||
- `internal/sandbox/` - nsjail, cgroup v2, seccomp, рабочие каталоги и остановка по лимитам.
|
||||
- `internal/judge/` - языки, шаг проверки синтаксиса, исходы тестов и групп.
|
||||
- `internal/checker/` - интерфейс checker и сравнения `exact`, `tokens` и `numbers`; custom checker находится в `internal/judge/`.
|
||||
- `internal/judgetest/` и `testdata/judge/` - эталонные решения на Python и Go с ожидаемыми результатами групп.
|
||||
- `internal/jobs/` - прогоны в памяти, идемпотентность по run ID и лимит параллельных прогонов.
|
||||
- `internal/server/` - HTTP API на сгенерированном ogen-сервере (`internal/api/`, из `codegen/ogen.yml`).
|
||||
- `internal/isolationtest/`, `testdata/hostile/` и `scripts/run-a16.sh` - набор враждебных программ A16 на Python и Go, его отчет и запуск на хосте исполнителя.
|
||||
- `internal/sandbox/` - namespaces, cgroup v2, seccomp и лимиты.
|
||||
- `internal/judge/`, `internal/checker/` - запуск и проверка результатов.
|
||||
- `internal/jobs/` - прогоны в памяти и ограничение параллелизма.
|
||||
- `internal/server/`, `internal/api/` - HTTP API и ogen-код из `api/runner/`.
|
||||
- `internal/isolationtest/`, `testdata/hostile/` - проверка изоляции A16.
|
||||
|
||||
Из корня: `make -C runner check` запускает форматирование, сборку, unit-тесты, проверку generated-кода и lint; `make -C runner test-sandbox` собирает образ и запускает эталонные решения и набор A16 в привилегированном dev-контейнере; `make -C runner test-a16` запускает только набор A16 с отчетом, а `make -C runner a16-bundle` собирает его для хоста исполнителя. Локальный запуск: `make -C deploy runner-dev-up` (только для разработки).
|
||||
```sh
|
||||
make -C runner check
|
||||
make -C deploy runner-dev-up
|
||||
make -C deploy runner-dev-down
|
||||
```
|
||||
|
||||
Production: сервис работает только в отдельной VM исполнителя, никогда на core-хосте. Подробнее: [развертывание](../docs/ru/DEPLOY.md#исполнитель-кода), [архитектура](../docs/ru/ARCHITECTURE.md#исполнитель-кода) и [проверки](../docs/ru/TESTING.md#тесты-исполнителя-кода).
|
||||
Dev-контейнер привилегированный, обслуживает HTTP только на loopback и не подходит для core-хоста. Production требует отдельную VM с собственным ядром, без секретов приложения и исходящих соединений, с TLS 1.3 и сервисным токеном. Backend не подключается напрямую к dev HTTP.
|
||||
|
||||
`make -C runner test-sandbox` проверяет решения и A16 в привилегированном dev-контейнере. `test-a16` сохраняет отчет только по изоляции; `a16-bundle` собирает пакет проверки для целевой VM. Unit-тесты не подтверждают изоляцию реальной VM.
|
||||
|
||||
Настройки и порядок включения: [DEPLOYMENT.md](../docs/ru/DEPLOYMENT.md#исполнитель-кода).
|
||||
+10
-3
@@ -8,9 +8,16 @@ Helper tools that work across multiple parts of the repository.
|
||||
- `check-api-compat.sh` checks public API compatibility against a selected Git ref.
|
||||
- `check-generated.py` detects generated files that differ from Git.
|
||||
- `docs-check.py` checks documentation, README language pairs, and local links.
|
||||
- `test_docs_check.py` and `test_merge_schemas.py` test documentation validation and schema merging; `test_contract_copies.py` checks that the OpenAPI 3.2 fixture and the ML contract keep identical copies of the api/core conventions.
|
||||
- `test_workflow_aggregate.py` checks every workflow in `.github/workflows` that has an `aggregate` job: the aggregate needs every other job and runs with `if: always()`, and every `needs` entry names an existing job. The test uses only the Python standard library and fails when it does not recognize the workflow structure.
|
||||
- `test_*.py` test these tools, API conventions, and dependencies between CI jobs.
|
||||
|
||||
Run them through Make from the repository root: `make -C api check`, `make -C api check-compat API_BASE_REF=<ref>`, `make check-generated`, `make docs-check`, and `make -C deploy check-workflows` (part of `make -C deploy check`). Service-specific scripts live in their service directories.
|
||||
From the repository root:
|
||||
|
||||
| Purpose | Command |
|
||||
| --- | --- |
|
||||
| Contracts and their tests | `make -C api check` |
|
||||
| Compatibility with a Git ref | `make -C api check-compat API_BASE_REF=<ref>` |
|
||||
| Generated files against Git | `make check-generated` |
|
||||
| Documentation and links | `make docs-check` |
|
||||
| CI job dependencies | `make -C deploy check-workflows` |
|
||||
|
||||
See the [development guide](../docs/en/DEVELOPMENT.md).
|
||||
+10
-3
@@ -8,9 +8,16 @@
|
||||
- `check-api-compat.sh` проверяет совместимость публичного API с выбранной Git-ссылкой.
|
||||
- `check-generated.py` обнаруживает расхождения сгенерированных файлов с Git.
|
||||
- `docs-check.py` проверяет документацию, языковые пары README и локальные ссылки.
|
||||
- `test_docs_check.py` и `test_merge_schemas.py` проверяют валидацию документации и объединение схем; `test_contract_copies.py` проверяет, что фикстура OpenAPI 3.2 и ML-контракт хранят идентичные копии соглашений api/core.
|
||||
- `test_workflow_aggregate.py` проверяет каждый workflow в `.github/workflows` с job `aggregate`: aggregate зависит от всех остальных jobs и запускается с `if: always()`, а все `needs` ссылаются на существующие jobs. Тест использует только стандартную библиотеку Python и падает, если не распознал структуру workflow.
|
||||
- `test_*.py` проверяют эти инструменты, соглашения API и зависимости между CI jobs.
|
||||
|
||||
Запускайте их через Make из корня: `make -C api check`, `make -C api check-compat API_BASE_REF=<ref>`, `make check-generated`, `make docs-check` и `make -C deploy check-workflows` (входит в `make -C deploy check`). Скрипты конкретного сервиса находятся в его каталоге.
|
||||
Из корня репозитория:
|
||||
|
||||
| Задача | Команда |
|
||||
| --- | --- |
|
||||
| Контракты и их тесты | `make -C api check` |
|
||||
| Совместимость с Git ref | `make -C api check-compat API_BASE_REF=<ref>` |
|
||||
| Сгенерированные файлы против Git | `make check-generated` |
|
||||
| Документация и ссылки | `make docs-check` |
|
||||
| Зависимости CI jobs | `make -C deploy check-workflows` |
|
||||
|
||||
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
|
||||
@@ -37,7 +37,13 @@ IGNORED_DIRS = {
|
||||
"vendor",
|
||||
"venv",
|
||||
}
|
||||
LANGUAGE_DOCS = {"ARCHITECTURE.md", "DEPLOY.md", "DEVELOPMENT.md", "TESTING.md"}
|
||||
LANGUAGE_DOCS = {
|
||||
"ARCHITECTURE.md",
|
||||
"DEPLOYMENT.md",
|
||||
"DEVELOPMENT.md",
|
||||
"SECURITY.md",
|
||||
"TESTING.md",
|
||||
}
|
||||
README_NAMES = ("README.md", "README.en.md")
|
||||
INLINE_LINK = re.compile(
|
||||
r"!?\[[^\]]*\]\(\s*(<[^>]+>|(?:\\.|[^\s)])+)(?:\s+[^)]*)?\)"
|
||||
|
||||
@@ -34,7 +34,7 @@ class RepositoryTestCase(unittest.TestCase):
|
||||
self.write(".agents/workflows/development.md", "Development.\n")
|
||||
self.write(".agents/workflows/validation.md", "Validation.\n")
|
||||
for language in ("ru", "en"):
|
||||
for name in ("ARCHITECTURE", "DEPLOY", "DEVELOPMENT", "TESTING"):
|
||||
for name in ("ARCHITECTURE", "DEPLOYMENT", "DEVELOPMENT", "SECURITY", "TESTING"):
|
||||
self.write(f"docs/{language}/{name}.md", f"# {name}\n")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
@@ -58,6 +58,16 @@ class DocsCheckTests(RepositoryTestCase):
|
||||
self.write("docs/en/FAQ.md", "# FAQ\n")
|
||||
self.assertEqual([], DOCS_CHECK.validate_repository(self.root))
|
||||
|
||||
def test_requires_deployment_and_security_guides(self) -> None:
|
||||
for name in ("DEPLOYMENT", "SECURITY"):
|
||||
with self.subTest(name=name):
|
||||
path = self.root / "docs/ru" / f"{name}.md"
|
||||
path.unlink()
|
||||
self.write("docs/ru/DEPLOY.md", "# Legacy deployment guide\n")
|
||||
errors = DOCS_CHECK.validate_repository(self.root)
|
||||
self.assertIn(f"docs/ru is missing required files: {name}.md", errors)
|
||||
self.write(f"docs/ru/{name}.md", f"# {name}\n")
|
||||
|
||||
def test_accepts_top_level_readme_pairs(self) -> None:
|
||||
for directory in ("backend", ".github", ".agents", "docs"):
|
||||
self.write(f"{directory}/README.md", "[English](README.en.md)\n")
|
||||
|
||||
@@ -7,8 +7,8 @@ Tools and rules that CI runs against source code, dependencies, and container im
|
||||
- `trivy/` configures dependency, configuration, and image scans, including scoped exceptions.
|
||||
- `gitleaks/` configures secret detection in files and Git history.
|
||||
- `semgrep/` contains local TypeScript and Python rules with test fixtures.
|
||||
- `install.py` and `tests/` handle tool installation and execution checks. govulncheck separately scans Go code.
|
||||
- `install.py` and `tests/` handle tool installation and execution checks. govulncheck scans the `backend/` module.
|
||||
|
||||
From the repository root, `make -C security install` installs tools locally, `make -C security test check` checks rules and source code, and `make -C security images` builds and scans images using Docker. Reports are saved in the ignored `reports/` directory.
|
||||
From the repository root, `make -C security install` installs tools locally, `make -C security test check` checks rules and source code, and `make -C security images` builds and scans the backend, frontend, and ML images using Docker. Reports are saved in the ignored `reports/` directory.
|
||||
|
||||
See the [security guide](../docs/en/SECURITY.md).
|
||||
+2
-2
@@ -7,8 +7,8 @@
|
||||
- `trivy/` - зависимости, конфигурация, образы и адресные исключения.
|
||||
- `gitleaks/` - поиск секретов в файлах и истории Git.
|
||||
- `semgrep/` - локальные правила для TypeScript и Python с тестовыми примерами.
|
||||
- `install.py` и `tests/` - установка инструментов и проверки их запуска. Go-код отдельно проверяет govulncheck.
|
||||
- `install.py` и `tests/` - установка инструментов и проверки их запуска. govulncheck проверяет модуль `backend/`.
|
||||
|
||||
Из корня: `make -C security install` устанавливает инструменты локально, `make -C security test check` проверяет правила и исходники, `make -C security images` собирает и сканирует образы через Docker. Отчеты сохраняются в игнорируемом `reports/`.
|
||||
Из корня: `make -C security install` устанавливает инструменты локально, `make -C security test check` проверяет правила и исходники, `make -C security images` собирает и сканирует образы backend, frontend и ML через Docker. Отчеты сохраняются в игнорируемом `reports/`.
|
||||
|
||||
Подробнее: [безопасность](../docs/ru/SECURITY.md).
|
||||
Reference in new issue
Block a user