Commit Graph

83 Commits

Author SHA1 Message Date
Zimin A.N. c8dd5aad4e feat(schema): Phase 1 schema templates + Nexus DevOps runbook
## AI Schema Assist Phase 1 (steps 1-2)

Approach A core (templates only, no LLM) — admin начинает создание нового
справочника с curated skeleton вместо пустого Monaco. Approach C (per-field
LLM suggest) — Phase 2 на этом фундаменте.

### Backend
- `templates/*.template.json` в ordinis-cuod-bundle resources — 6 шаблонов
  (blank/spacecraft/ground-station/antenna/frequency-band/operator)
- `SchemaTemplateRegistry` (rest-api) — classpath scan at startup, strip
  x-template-* metadata, expose canonical JSON Schema
- `SchemaTemplatesController` — GET /api/v1/dictionaries/templates (list)
  + /{id} (detail с schemaJson)
- Cross-bundle support: scanner matches classpath*:templates/*.template.json
  — другие bundles могут shippит свои templates через те же conventions

### Frontend
- types: SchemaTemplateSummary + SchemaTemplateDetail
- queries: schemaTemplatesQuery + lazy detail query
- TemplatePicker.tsx — grid of cards (icon + name + description + tags),
  click → fetch detail → fire onPick(detail)
- Integrated в DictionaryEditorDialog (create mode, properties.length===0
  visible — после первой property picker исчезает чтобы не перезатереть)

## Nexus DevOps handoff

`docs-internal/ops/nexus-alpine-mirror.md` — runbook про APKINDEX vs file
inventory drift на v3.23 mirror. Includes:
- Verification commands
- 3 fix options (invalidate cache / scheduled refresh / self-host)
- Prometheus alert proposal
- Current workaround (node:22-alpine3.20 pin) reference

Active issue paired с CI saga !227/!229/!230 — нужен DevOps action.
2026-05-16 13:20:43 +03:00
Zimin A.N. 35147df683 fix(search): scope filter uppercase — fixes Smart Search 0 results bug
QA report BUG-005: "/search" возвращал 0 результатов на любые запросы
(«антенна», «GS_MOSCOW», «super» — всё пусто).

Root cause: SearchController convertedil scope enum в lowercase перед
WHERE filter:
  data_scope = ANY(CAST(? AS TEXT[]))  -- value: 'public'

Но DB stores UPPERCASE per migrations 0008/0009 CHECK constraint:
  CHECK (data_scope IN ('PUBLIC', 'INTERNAL', 'RESTRICTED'))

Filter 'public' никогда не матчил 'PUBLIC' → empty result для всех queries.
Багу 5+ месяцев — comment в коде утверждал что DB lowercase, что было
неправдой даже в момент написания.

Fix: убрать .toLowerCase() — pass enum names как есть. Verified:
  curl /api/v1/antenna/records?as_scope=PUBLIC возвращает GS_MOSCOW_A1
  но curl /api/v1/search?q=GS_MOSCOW возвращал 0. После fix должен матчить.
2026-05-15 22:51:01 +03:00
Zimin A.N. ff7e72e0fd fix(qa-report): version tag, /drafts redirect, audit filter complete, i18n cleanup
QA report v2.31.x batch:

- **VersionController.tag**: было 'none' (maven build на main без git tag) → UI
  показывал «dev · 6077d4df». Helm передаёт image.tag через env
  ORDINIS_BUILD_IMAGE_TAG, controller парсит «v2-31-2-e3c82775» → «v2.31.2».
  Helm chart change в ordinis-infra (separate MR).

- **/drafts redirect** (BUG-003): пустой 404 «Not Found» plain text → теперь
  static redirect на /my-drafts.

- **Audit action filter** (BUG-004): дропдаун содержал только 3 значения
  (CREATE/UPDATE/CLOSE), но в таблице 11 типов (DRAFT_*, DEFINITION_*).
  Frontend AuditAction enum + ACTIONS list синхронизированы с backend
  AuditLogger/SchemaDraftService/DraftService.

- **i18n cleanup** (BUG-006/007/UX-005):
  - myDrafts.description: «Все ваши submissions с pending/approved...» →
    «Все ваши черновики с историей: ожидает рассмотрения, одобрен...»
  - reviews.description: «Pending drafts от makers, ждут approve/reject» →
    «Черновики от авторов, ждут одобрения или отклонения. Общая очередь...»
  - reviews.queueTotal: «N pending drafts» → «N черновиков в очереди»
  - myDrafts.col.reviewer: «Reviewer» → «Рецензент» (RU only)
  - notifications chip labels: 'submit/approved/rejected' → 'отправлен/
    одобрен/отклонён'
  - audit.action.* expanded к 13 entries для каждого backend action
    type, с понятными лейблами «Черновик одобрен» вместо «DRAFT_APPROVE»

- **WhatsNewModal markdown** (UX-006): тексты вроде «**График доставки
  webhook'ов**» рендерились с буквальными звёздочками. Mini inline renderer
  для **bold**, *italic*, `code` — без full markdown library.
2026-05-15 22:02:29 +03:00
Александр Зимин f04b1be1f6 feat(notifications): Phase B-2 — per-event-type granular preferences 2026-05-15 16:53:32 +00:00
Александр Зимин fd35e71fe8 fix(rest-api): preserve status code from ResponseStatusException 2026-05-15 15:20:21 +00:00
Александр Зимин 9452adaf55 feat(notifications): Phase B backend — per-user channel preferences 2026-05-15 14:56:25 +00:00
Александр Зимин e43e3f617f fix(schema-drafts): /drafts/active returns 200+null instead of 404 (no console spam) 2026-05-14 22:41:45 +00:00
Александр Зимин f028ec5796 fix(notifications): panic-level defensive GET /me/notifications 2026-05-14 21:50:51 +00:00
Александр Зимин 0cf76d23c1 fix(notifications): defensive /me/notifications — wrap DB ops in try/catch 2026-05-14 21:00:42 +00:00
Александр Зимин 9050e2427e feat(notifications): TODO 7 — draft decision toast + email + bell badge 2026-05-14 14:40:35 +00:00
Александр Зимин d338c52c63 fix(approval): allow non-breaking schema changes inline 2026-05-14 12:35:39 +00:00
Александр Зимин 9ec723dd17 Merge branch 'feat/record-draft-audit-outbox' into 'main'
feat(drafts): audit + outbox для record-draft lifecycle (audit findings)

See merge request 2-6/2-6-4/terravault/ordinis!184
2026-05-14 12:32:06 +00:00
Александр Зимин 0003fb6801 feat(drafts): audit + outbox для record-draft lifecycle (audit findings) 2026-05-14 12:32:06 +00:00
Александр Зимин 4e0902706e fix(approval): close 2 more bypass paths from security audit 2026-05-14 12:32:03 +00:00
Andrei Zimin 018ebff207 fix(schema): enforce approvalRequired on PUT /{name} + PATCH /{name}/schema
Reported 2026-05-14: editing schema on an approvalRequired dictionary
applied inline without going through the schema-draft maker-checker
workflow. Two endpoints both lacked the gate that DictionaryRecordService
already had for record CRUD:

1. PUT /api/v1/admin/dictionaries/{name}
   (frontend SchemaDrivenForm "edit schema" save button hits this).
   DictionaryDefinitionService.updateSchema overwrote schemaJson directly.
   Bonus backdoor: same request could simultaneously flip
   approvalRequired:true→false and rewrite the schema in one transaction
   — review-bypass via toggle.

2. PATCH /api/v1/admin/dictionaries/{name}/schema (inline non-breaking
   patch — description / title / minimum / maximum / enum-add). Frontend
   doesn't currently call this, but backend exposed it without a gate.

Both now reject with `422 approval_required` carrying the schema-drafts
URL in the message. Frontend's existing serverErrorMessage in
DictionaryEditorDialog already surfaces backend `message` to the user,
so no UI changes needed for correctness. UX polish (hide "Save" /
show "Create draft" CTA when approvalRequired=true) is a follow-up.

The PUT gate is narrow on purpose: schemaChanged OR approvalRequired
toggle-off. Pure metadata edits (display name, description, locales,
projection flag) on an approvalRequired dict still go through inline
— those don't affect record validation, no review needed.
2026-05-14 15:05:09 +03:00
Andrei Zimin 83caf9c3c8 feat(user-display): KeycloakAdminUserResolver — Phase 2 on-demand lookup
Implements the Phase 2 hook from the previous commit. With this in
place, UserDisplayService.find chains:

  hot cache → DB (user_display_cache) → Keycloak Admin API

so any realm user resolves on first display, even if they never made
an authenticated request to ordinis. The resolved entry is persisted
via UserDisplayService.upsert with source=KEYCLOAK_ON_DEMAND, so the
next render of the same sub hits the DB tier (~ms) instead of going
back to Keycloak.

Implementation notes:

- Spring RestClient (modern blocking HTTP, replaces RestTemplate).
- client_credentials grant against
  {issuer}/realms/{realm}/protocol/openid-connect/token. Token cached
  in-memory minus a 30s safety margin from `expires_in`.
- 401 on user lookup wipes the cached token and surfaces a
  RuntimeException, so the next resolve refetches.
- 404 on user lookup → Optional.empty (definitive miss, sub not in
  realm). UserDisplayService logs and the caller falls back to short
  UUID. Negative cache TTL not implemented — added complexity not
  justified for the current realm size (~50 users).
- Bean activated only when ordinis.keycloak.admin.enabled=true AND
  the env vars are set. Default disabled — UserDisplayService treats
  KeycloakUserResolver as @Autowired(required = false), so a
  deployment without Keycloak admin creds keeps the previous behavior
  (DB cache only) instead of crashing on startup.

Application config:
- ORDINIS_KEYCLOAK_ADMIN_ENABLED      (false by default)
- ORDINIS_KEYCLOAK_ADMIN_URL          e.g. https://auth.nstart.space
- ORDINIS_KEYCLOAK_ADMIN_REALM        defaults to nstart
- ORDINIS_KEYCLOAK_ADMIN_CLIENT_ID    via vault (see docs-internal/keycloak-admin-setup.md)
- ORDINIS_KEYCLOAK_ADMIN_CLIENT_SECRET via vault

Setup runbook (docs-internal/keycloak-admin-setup.md) covers:
- creating the Keycloak service-account client + assigning view-users
- writing the secret into both vault instances (different per env)
- wiring vault.hashicorp.com agent-inject annotations into the chart
- verification steps + common failure modes

Phase 3 (scheduled bulk sync) is documented at the end of the runbook
but deferred — depends on observed cache miss rate after this lands.
2026-05-14 14:47:49 +03:00
Andrei Zimin ec0c74afdf feat(user-display): persistent DB cache + Keycloak resolver hook (Phase 1+2 wiring)
Closes "ток мой UUID отображается" pain reported on staging today: any
reviewer / maker / publisher / actor whose JWT sub never landed in the
JVM cache shows up as a short UUID in audit / reviews / changelog /
events / history / record drawer / webhook detail / record version
history. Restart the pod and even captured users disappear.

Three-tier resolve, replacing the in-memory-only cache that was the
"Альтернатива (на будущее)" TODO in the original UserDisplayService:

  1. JVM ConcurrentHashMap hot cache (~µs, capped at 10k).
  2. user_display_cache Postgres table (~ms, persistent across restart).
     New migration 0023 — sub PK + preferred_username + name + email +
     source enum + synced_at + updated_at, plus an index on synced_at
     for the scheduled bulk sync that lands later.
  3. Keycloak Admin API on-demand (Phase 2) — dispatched to optional
     KeycloakUserResolver bean. When the bean isn't wired (no Keycloak
     admin creds yet), the third tier is a no-op and UserCell falls
     back to short UUID exactly like before.

Source enum on every row — JWT_CAPTURE / KEYCLOAK_SYNC /
KEYCLOAK_ON_DEMAND — so the eventual scheduled sync can prefer JWT-
captured rows (richest claims as the user actually saw them) and the
on-demand fallback can be distinguished from bulk sync in audits.

JwtUserCaptureFilter and UserDisplayController are unchanged — they
already used UserDisplayService.put / find with the same signatures.
The behavior change is invisible at the API layer: same /admin/users/
{sub}/display endpoint, same 404 user_not_cached on miss; persistence
just survives pod restart now.

mergeFrom on UserDisplayCacheEntry deliberately keeps the existing
non-blank field when an update brings null — Keycloak sync may have a
richer email than JWT capture; don't blank it out.

Phase 2 will land a KeycloakAdminUserResolver impl + vault secret
plumbing on this same branch. Phase 3 (scheduled bulk sync via
@Scheduled) is a separate sprint — it needs the Keycloak admin client
already in place.
2026-05-14 14:45:14 +03:00
Александр Зимин 95c2b46dd3 Merge branch 'feat/user-display-endpoint' into 'main'
feat(users): /admin/users/{sub}/display endpoint + UserCell uses it

See merge request 2-6/2-6-4/terravault/ordinis!177
2026-05-13 16:42:46 +00:00
Александр Зимин be90077520 feat(users): /admin/users/{sub}/display endpoint + UserCell uses it 2026-05-13 16:42:46 +00:00
Александр Зимин 0a9deb51bd Merge branch 'feat/admin-role-gate-audit-outbox-webhooks' into 'main'
feat(admin): scope-gated audit и outbox endpoints

See merge request 2-6/2-6-4/terravault/ordinis!176
2026-05-13 16:42:12 +00:00
Александр Зимин da17930def feat(admin): scope-gated audit и outbox endpoints 2026-05-13 16:42:11 +00:00
Александр Зимин 5187845047 feat(approval): enforce per-dictionary approvalMinRole (Phase 2) 2026-05-13 16:42:09 +00:00
Александр Зимин f096b5746d feat(my-drafts): schema drafts тоже в "Мои черновики" 2026-05-13 12:45:45 +00:00
Zimin A.N. 4fe7f1e800 fix(auth): @Autowired на WorkflowRoles main ctor
Класс имеет два constructor'а (main + test). Без явной @Autowired
аннотации Spring может выбрать no-arg ctor → props=null →
rolesClaimPath() fallback на realm_access.roles несмотря на
env var ORDINIS_AUTH_ROLES_CLAIM=resource_access.ordinis.roles.

Симптом: 403 forbidden_role с message 'Требуется realm role:
ordinis:schema:reviewer' для user с ordinis:admin в
resource_access.ordinis.roles (super-role override не работал
потому что currentRoles() возвращал пустой set из неправильного
claim path).

Fix: @Autowired на main ctor — Spring выбирает его, props
инжектится, rolesClaim читается из env var правильно.
2026-05-13 13:49:07 +03:00
Zimin A.N. 36c06ae1da feat(auth): WorkflowRoles configurable claim path + ordinis:admin super-role
User report: token has roles в resource_access.ordinis.roles (client-scoped),
backend WorkflowRoles читал hardcoded realm_access.roles → forbidden_role
для всех reviewer actions.

Backend:
- WorkflowRoles: depends OrdinisAuthProperties → reads via rolesClaim path
  (же что ScopeContext). Default realm_access.roles, на staging/prod env
  var ORDINIS_AUTH_ROLES_CLAIM=resource_access.ordinis.roles (уже wired
  в helm helper).
- Nested claim path resolver — mirror ScopeContext.readClaimByPath
- New super-role ADMIN ('ordinis:admin') — holder автоматически проходит
  любой workflow check без явного назначения отдельных ролей. Convenience
  для small teams.

Frontend (usePermissions.ts):
- tokenRoles() читает оба claim path (realm_access.roles +
  resource_access.ordinis.roles) и объединяет — UI gate работает
  независимо от backend config
- hasRole() recognizes 'ordinis:admin' как super-role override
- ROLE_ADMIN exported

Docs:
- docs/operator/rbac.md: добавлен ordinis:admin row, JWT claim path note,
  Admin profile updated (super-role vs composite explanation)
2026-05-13 13:17:54 +03:00
Zimin A.N. c5b00ff623 refactor(auth): domain-specific role names (consistent convention)
User feedback: универсальный 'ordinis:approver' отступал от convention
'ordinis:<domain>:<action>'. Меняю на domain-specific:

WorkflowRoles constants:
- APPROVER → SCHEMA_REVIEWER ('ordinis:schema:reviewer')
- PUBLISHER → SCHEMA_PUBLISHER ('ordinis:schema:publisher')
- Новая RECORD_REVIEWER ('ordinis:record:reviewer')

Applied:
- SchemaDraftService.decide() → require SCHEMA_REVIEWER
- SchemaDraftService.publish() → require SCHEMA_PUBLISHER
- DraftService.approve() / .reject() → require RECORD_REVIEWER

Frontend usePermissions.ts:
- ROLE_APPROVER + ROLE_PUBLISHER → ROLE_SCHEMA_REVIEWER +
  ROLE_SCHEMA_PUBLISHER + ROLE_RECORD_REVIEWER
- Новый hook useCanReviewRecord() для record draft actions

Keycloak setup (updated):
- ordinis:schema:reviewer
- ordinis:schema:publisher
- ordinis:record:reviewer
(Composite role 'ordinis:admin' = all три + scope roles — для удобства.)
2026-05-13 12:44:23 +03:00
Zimin A.N. 24aa94d130 feat(auth): Phase 1d — backend role enforcement для workflow
User explicitly requested 'Phase 1d пора'. До этого MR'а backend гейтил
только maker-checker (self_approve_forbidden), frontend hooks возвращали
auth.isAuthenticated.

Реализация:

Backend WorkflowRoles (ordinis-rest-api/auth/WorkflowRoles.java):
- Component reads realm_access.roles из JWT claim
- Constants: ordinis:approver (decide/approve/reject), ordinis:publisher (publish)
- requireRole(role) throws 403 forbidden_role если missing
- Defensive parse: malformed/missing realm_access → empty roles
- 9 unit tests cover authenticated + anonymous + malformed JWT

Applied gates:
- SchemaDraftService.decide() — require ordinis:approver
- SchemaDraftService.publish() — require ordinis:publisher
- DraftService.approve() — require ordinis:approver
- DraftService.reject() — require ordinis:approver

WorkflowRoles is Optional в test ctors → unit tests без auth setup
не ломаются. Все existing tests должны проходить (legacy ctor overloads
сохранены).

Frontend usePermissions.ts:
- Stub return auth.isAuthenticated заменён на real role decode из
  auth.user.profile.realm_access.roles
- ROLE_APPROVER + ROLE_PUBLISHER constants exported
- Defensive parsing — graceful с missing/malformed claims
- useCanCreateSchemaDraft остаётся permissive (любой auth — maker'ом
  может быть anyone, scope ACL заведует видимостью)

Naming convention — colon-separated (consistent с ordinis:client:*
scope ролями), aligned с MR !161.

MIGRATION (BREAKING без правильной Keycloak setup):
1. Keycloak realm 'nstart' → Realm Roles → Create:
   - ordinis:approver
   - ordinis:publisher
2. Users → assign roles:
   - reviewer/approver users → ordinis:approver
   - publisher users → ordinis:approver + ordinis:publisher
3. После refresh JWT (logout/login) роли появляются в realm_access.roles

Без этого все decide/publish операции вернут 403 forbidden_role.
2026-05-13 12:36:53 +03:00
Zimin A.N. f2adc37e2e fix(restapi): NoResource/NoHandler → 404, не 500
GlobalExceptionHandler catch-all Exception → 500 ловил NoResourceFoundException
и NoHandlerFoundException. Симптомы на prod:

- /swagger-ui/index.html при disabled springdoc возвращал 500 (UI всё равно
  не рендерился, но spring логировал 'Unhandled exception' на каждый запрос —
  спамил alerting и затруднял поиск настоящих ошибок).
- GET /api/v1/typo от integrator'ов давал 500 вместо 404, осложняло
  debugging без traceId-correlation.
- Любой stale frontend bundle с переименованным endpoint мог триггерить
  false-positive incident alerts.

Fix: explicit @ExceptionHandler для обоих exception типов → 404 not_found.
Логирование DEBUG (не WARN/ERROR) — это ожидаемый 404, не аномалия.

Test: SmokeE2ETest.unknownPath_returns404WithNotFoundCode покрывает оба пути
(/api/v1/* и /swagger-ui/*) → 404 + body.code='not_found'.
2026-05-13 00:00:36 +03:00
Александр Зимин 5479142093 feat(webhook): time-series histogram stats endpoint + frontend chart 2026-05-12 14:30:22 +00:00
Александр Зимин b3a9104d54 feat(schema-workflow): PATCH /drafts/{id} — edit без recreate (A) 2026-05-12 11:33:01 +00:00
Александр Зимин 72268f9add feat(api): GET /changelog/{entryId}/diff — full before/after schemas 2026-05-12 08:51:28 +00:00
Александр Зимин 12975e0d83 feat(api): full timeline в /changelog — workflow events + draft kinds 2026-05-12 00:14:09 +00:00
Александр Зимин 01fc5771f2 feat(api): schema workflow API — backend #3 (drafts/review/decision/publish) 2026-05-11 23:11:56 +00:00
Zimin A.N. f5e7348f92 fix(audit): definition action != record action — fix SmokeE2ETest filter
SmokeE2ETest.contextLoadsAndCreatesRecord фильтрует audit_log по
action='CREATE' и ожидает row с businessKey. Мой backend #1 commit
сделал definitionCreated() писать action='CREATE' — конфликт с
record-level CREATE rows: filter подбирал dict-level row первой
(no businessKey → null assertion fail).

Fix: definitionCreated/definitionUpdated теперь пишут action
'DEFINITION_CREATE' / 'DEFINITION_UPDATE'. event_type остаётся
DEFINITION_CREATED/UPDATED (changelog query filter по event_type
IN список, не задеть).
2026-05-11 23:23:21 +03:00
Zimin A.N. db4f859ef6 feat(api): PATCH /dictionaries/{name}/schema — inline non-breaking field edit (backend #4)
Backend #4 из pending-endpoints brief. Frontend Fields tab inline edit:
кликаешь field row → form показывает только allowed (non-breaking) changes
→ submit → patch component bumps (1.4.0 → 1.4.1) без full DictionaryEditorDialog.

Body:
```json
{
  "expectedHeadVersion": "1.4.0",
  "field": "altitude",
  "changes": { "description": {"ru":"Высота орбиты"}, "minimum": 0 }
}
```

Allowed change keys: description / title / minimum / maximum / enum.
Breaking keys (type/format/x-references/etc) → 422 breaking_change_requires_draft.

Validation:
- minimum tighter than current → 422 validation_failed (могло бы invalidate existing)
- maximum tighter than current → 422 validation_failed
- enum removing existing values → 422 (only additions allowed inline)
- expectedHeadVersion != actual → 409 version_mismatch (optimistic lock)

Implementation:
- PatchSchemaRequest DTO (record).
- SchemaPatchService: gates dict/scope/version, applies whitelisted changes
  on deep-copied JsonNode, bumps patch component via bumpPatchVersion helper
  (semver-safe + fallback для non-semver).
- DictionaryDefinitionController новый @PatchMapping.
- OrdinisException.unprocessableEntity helper (422).

Audit: hooks через existing AuditLogger.definitionUpdated после save.

Tests +10: 4xx scenarios, description update bumps version, enum add ok,
enum remove blocked, minimum expand ok / tighten blocked, version bump
helpers (semver + non-semver fallback).
2026-05-11 23:13:04 +03:00
Zimin A.N. e02e684cca feat(api): GET /dictionaries/{name}/snapshots — record-change buckets (backend #2)
Backend #2 из pending-endpoints brief. Frontend TimeTravelModal использует
этот endpoint для slider marks — каждая точка = bucket где минимум одна
запись validFrom попадает.

GET /api/v1/dictionaries/{name}/snapshots?from=...&to=...&granularity=day

Implementation:
- DictionaryRecordRepository.findSnapshotBuckets — native SQL date_trunc
  GROUP BY bucket, ORDER BY bucket DESC. scope filter через text[] из CSV.
- SnapshotsService — gates dict existence/scope, validates granularity
  (hour/day/week) + window, formats RU label (1 апр / сейчас), reverses
  список чтобы oldest first (UI читает слева-направо).
- DictionaryChangelogController новый endpoint /snapshots.

Errors:
- 404 dictionary_not_found
- 400 invalid_granularity (not in {hour,day,week})
- 400 invalid_window (from >= to)

Frontend impact: TimeTravelModal slider marks переходит с recordTimestamps
derived data на реальный API. ~1h frontend swap.
2026-05-11 23:08:07 +03:00
Zimin A.N. ebc90d76e9 feat(api): GET /dictionaries/{name}/changelog — schema versions timeline (backend #1)
Backend #1 из pending-endpoints brief. Frontend HistoryTabContent +
TimeTravelModal используют этот endpoint для отображения версий схемы
во времени с per-version property-level diff summary.

Implementation:
- AuditLogger.definitionCreated / definitionUpdated — пишет в audit_log
  с event_type DEFINITION_CREATED / DEFINITION_UPDATED. payload_before/
  after = JsonNode schema. record_id / business_key — NULL (dict-level event).
- DictionaryDefinitionService.create / updateSchema hook в audit logger
  (autowired, null-safe для tests).
- AuditLogRepository.findByDictionaryIdAndEventTypes — query by dict_id +
  event_type IN (...), ORDER BY event_time DESC, paginated.
- ChangelogService.findChangelog — собирает entries, computes top-level
  property-key diff (added/removed/changed). Первая entry (newest) =
  isCurrent + schemaVersion из DictionaryDefinition; старые entries
  возвращают version=null (semver-в-аудит backfill — separate migration).
- DictionaryChangelogController — GET /dictionaries/{name}/changelog?limit=50

Errors:
- 404 dictionary_not_found когда dict missing OR scope hidden (consistent
  с другими endpoints).

Tests +9: dict-not-found, scope-hidden, empty-audit, first-is-current,
diff-added/removed/changed/null-before/identical.
2026-05-11 23:04:09 +03:00
Zimin A.N. ff05ef9a9f feat(api): GET /dictionaries/graph/outgoing — batch outgoing FK summary
Frontend admin-UI catalog list (`→` column) парсил schemaJson per-row
для подсчёта outgoing FK refs. Этот endpoint возвращает batch:

  GET /api/v1/dictionaries/graph/outgoing?dicts=satellites,operators

  → { "outgoing": {
      "satellites": { "fkCount": 3, "targets": ["launch_sites", "missions", "operators"] },
      "operators":  { "fkCount": 0, "targets": [] }
    } }

Implementation:
- LineageIndexService.findOutgoingFkSummary — обходит DictionaryDefinitionRepo.findAll()
  + ScopeContext filter, парсит x-references через ReferenceValidator.parseRef,
  dedup target dict names, sort alphabetically.
- LineageController новый endpoint + OutgoingGraphResponse wrapper record
  (extensible — sibling fields в будущем без breaking).

Errors: scope hide (тихо skip — same pattern что и GET /dictionaries).
Malformed x-references логируются WARN + skip (не падают на одной плохой
schema).

Tests +6 cases: empty, basic counts, scope hide, whitelist filter, dedup
repeated target, malformed-not-fatal.
2026-05-11 22:54:43 +03:00
Александр Зимин e8f98230f2 feat: version banner UI + GET /api/v1/version backend endpoint 2026-05-10 16:50:50 +00:00
Zimin A.N. aedeafc84e feat(approval): /my-drafts maker self-tracking view + /api/v1/drafts/me
Approval Workflow v2 Phase 4 — UX:

Backend:
- DraftController.myDrafts: GET /api/v1/drafts/me?page&size — все статусы
  (PENDING/APPROVED/REJECTED/WITHDRAWN) текущего authenticated user, sorted
  submitted_at DESC. Resolve maker_id из JWT subject (fallback "anonymous"
  если auth off).
- Reuses existing DraftService.listByMaker (Phase 1 method, был не exposed).

Frontend:
- routes/my-drafts.tsx: новый маршрут с табличным view.
  Колонки: businessKey / operation / status / submittedAt / reviewedAt /
  reviewerId / comment / actions. Status badge tinted (warning/success/
  error/neutral). PENDING строки имеют Withdraw кнопку (calls existing
  useWithdrawDraft с confirm).
- api/queries.ts: useMyDrafts (refetch 30s — maker увидит когда reviewer
  decide).
- api/mutations.ts: useWithdrawDraft теперь invalidate'ит ['drafts'] —
  /me + by-dict обе видят изменение.
- routes/__root.tsx: nav link "Мои черновики" / "My drafts" (после Reviews).
- i18n RU/EN: 18 keys (nav.myDrafts, myDrafts.* col/action/status).
  Pluralization для total через i18next plurals.

Why это нужно:
- До этого maker submit'нул draft и пропадал — единственный feedback был
  badge "На review" в records list (только для текущего dict). Здесь — все
  его submissions с history + withdraw для PENDING.
- Reviewer pool (D3=A) маленький, /reviews queue только для них. Maker
  без role'а не видит queue, но должен tracking своих submissions.

Tests: ordinis-rest-api unit 119/119, ordinis-app e2e 28/28, vitest 89/89.
2026-05-10 12:07:35 +03:00
Zimin A.N. b2e7fd84c9 feat(approval): Approval Workflow v2 Phase 4 monitoring + pending-review badges
Approval Workflow v2 — Phase 4: monitoring + UX visibility.

Backend metrics (Micrometer → Prometheus):
- Gauge nsi_draft_pending_total — global queue depth (polled на scrape).
- Counter nsi_draft_submit_total{dictionary,operation,outcome=ok|already_pending|error}
  — submit attempts с разбивкой по outcome. Phase 3 lessons: error outcome
  выявит schema bugs которые ранее маскировались.
- Counter nsi_draft_decision_total{dictionary,operation,outcome=approved|rejected|withdrawn}
  — counts decisions, разбит по типу.
- Timer nsi_draft_review_duration_seconds — time-to-decide histogram (от
  submit до approve/reject/withdraw). publishPercentileHistogram() — для
  Prometheus histogram_quantile p95/p99.

DraftService:
- Optional<MeterRegistry> — null-safe в test ctor'ах.
- @PostConstruct registerGauges() — Gauge.builder polled от
  RecordDraftRepository.countPending().
- recordDecision() helper в approve/reject/withdraw — записывает Timer +
  Counter одной точкой.
- 4-arg ctor compat для Phase 1 unit tests.

UI (admin):
- useDictPendingDrafts — per-dict pending list, refetch 30s, gated на
  detailQuery.data.approvalRequired (no-op для не-approval dicts).
- "На review" badge в businessKey cell records table — моментальная
  видимость что есть pending draft. Open /reviews для act'а.
- i18n RU/EN: dict.pendingReview.label + tooltip.

Domain:
- RecordDraftRepository.countPending() — для Gauge polled count.

Tests: ordinis-rest-api unit 119/119, ordinis-app e2e 28/28, vitest 89/89.
2026-05-08 15:11:25 +03:00
Zimin A.N. 9ef9b8147e feat(approval): Approval Workflow v2 Phase 3 — e2e suite + 0020 case fix
Phase 3 e2e coverage (8 tests, ApprovalWorkflowE2ETest):
- happyFlow: maker submit → checker approve → live record + outbox event
- rejectFlow: keeps draft REJECTED, no live record, re-approve blocked
- selfApprove: same JWT subject blocked (self_approve_forbidden / self_reject_forbidden)
- twoPendingDrafts: exclusion constraint → 409 draft_already_pending
- directCRUD on approval_required dict: POST/PUT/DELETE → 409 draft_required (D2=A)
- regression: dict без approval_required — direct CRUD по-прежнему работает
- withdrawByMaker: maker может, reviewer не может (403 not_draft_maker)
- rejectWithoutComment: 400 reject_reason_required

E2e exposed real Phase 0 bug:
Hibernate @Enumerated(EnumType.STRING) пишет UPPERCASE ('PENDING'), а
Liquibase 0019 check constraint + exclusion WHERE использовали lowercase
('pending'). Каждый insert проваливался на check, маппился в
DataIntegrityViolation, и DraftService.submit маскировал его в
draft_already_pending — скрывая реальную причину.

Fixes:
1. Migration 0020: пересоздание record_drafts_status_check + exclusion
   с UPPERCASE значениями (matches enum serialization).
2. DraftService.submit: только SQLSTATE 23P01 (exclusion violation)
   маппится в draft_already_pending. Остальные DataIntegrity (check, FK,
   NOT NULL) пробрасываются как-есть — иначе schema bugs продолжат
   маскироваться.
3. DraftServiceTest StubDraftRepo: оборачивает SQLException 23P01 в
   DataIntegrityViolation cause chain — отражает прод поведение.

Test counts:
- ordinis-rest-api unit: 119/119 PASS
- ordinis-app e2e: 28/28 PASS (был 20, +8 новых ApprovalWorkflowE2ETest)
2026-05-08 13:52:17 +03:00
Zimin A.N. 2020af99b7 feat(approval): Approval Workflow v2 Phase 1 — full lifecycle + approval gate
Phase 1 на скелете Phase 0 (e438c4c). Делает workflow рабочим end-to-end:
maker submit → reviewer approve/reject → COPY → live record + outbox event.

Backend:
- DictionaryRecordService:
  * requireApprovalGate() — pre-check на create/update/close. Throws 409
    draft_required если dict.approval_required=true с pointer на drafts API.
  * applyApprovedCreate/Update/Close — public bypass methods для DraftService.
    Обходят approval check (drafts уже прошли review). Schema validation
    повторяется ON APPROVE — schema может measure'ся между submit и approve
    (failure modes #2 из design doc).
  * createDirect/updateDirect/closeDirect — internal helpers (private),
    extract'ed из public методов.
- DraftService:
  * approve(draftId, comment) — SERIALIZABLE tx. Validates pending status,
    self-approve guard (D3 maker-checker), dispatches на applyApproved*
    based on draft.operation. Marks draft APPROVED + reviewer fields
    (D4=A: kept в таблице для compliance).
  * reject(draftId, comment) — non-blank reason required (compliance).
    Marks REJECTED + reviewer fields. Никаких applyApproved calls.
  * withdraw(draftId) — maker-only. 403 not_draft_maker если другой user.
    Marks WITHDRAWN.
  * Constructor split: production-ctor (с recordService) + test-ctor
    (без recordService — для unit tests submit/list path). @Autowired
    отмечает canonical для Spring.
- DraftController endpoints:
  * POST /api/v1/drafts/{id}/approve?comment=
  * POST /api/v1/drafts/{id}/reject?comment=
  * DELETE /api/v1/drafts/{id} — withdraw

DTO surface — admin UI токglet'ы для approval policy:
- DictionaryResponse: +approvalRequired, +approvalMinRole.
- CreateDictionaryRequest: optional Boolean approvalRequired, String
  approvalMinRole (null = no change в update).
- DictionaryDefinitionService.create + updateSchema: применяют поля.
- DictionaryDefinitionService.findById — added (нужно DraftService.approve
  чтобы взять def name по id).

Tests:
- DraftServiceTest 13 unit tests (+7 new для Phase 1):
  * approve dispatches CREATE/UPDATE/CLOSE per draft.operation
  * approve blocked при self-approve (maker == reviewer)
  * approve 409 если draft уже approved/rejected
  * reject marks с reason; reject 400 если reason пустой
  * withdraw marks WITHDRAWN; 403 если не maker
  * + 6 Phase 0 tests от прошлого commit'а сохранены

TrackingRecordService stub — extends DictionaryRecordService с null deps,
overrides applyApproved* для записи calls в list. Verifies dispatch без
real DB.

Verify:
- mvn -pl ordinis-rest-api -am test: 119/119 PASS (+7 new).
- mvn -P e2e -pl ordinis-app -am test: 20/20 PASS — approval gate не
  ломает existing flow когда approval_required=false (default).

Phase 2 (next): admin UI reviewer queue + diff viewer + status badges.
Phase 3: e2e/integration tests + per-dict opt-in soak.

Source: ~/.gstack/projects/claude/zimin-main-design-approval-workflow-v2-20260507-121632.md
2026-05-08 13:19:24 +03:00
Zimin A.N. e438c4c8c8 feat(approval): Approval Workflow v2 Phase 0 — schema + skeleton API
Approval Workflow v2 epic, Phase 0 foundation. Maker-checker pattern для
критичных справочников через record_drafts отдельную таблицу (Approach A
из design doc).

Decisions made (auto, per design doc recommendations):
- D1=A: per-dict policy через колонки на dictionary_definitions
  (approval_required + approval_min_role).
- D2=A: legacy POST на approval-required dict вернёт 409 (Phase 1 wire'ит
  в DictionaryRecordService).
- D3=A: pool model для reviewer'ов — все ordinis:approver видят queue.
- D4=A: rejected drafts kept (status='rejected'); compliance audit trail.

Migration 0019:
- record_drafts table:
  * id, dictionary_id, business_key, parent_record_id, operation
  * data (jsonb), geometry, proposed_valid_from/to
  * status, maker_id, maker_comment, submitted_at
  * reviewer_id, reviewed_at, review_comment, version
- 4 constraints:
  * status_check: pending/approved/rejected/withdrawn
  * operation_check: CREATE/UPDATE/CLOSE
  * no_self_approve: maker_id != reviewer_id
  * one_pending_per_key: EXCLUDE WHERE status=pending
    (concurrent edits → последний wins на submit, prevents merge conflicts)
- 3 indices: pending_by_dict, by_maker, pending_global.
- dictionary_definitions: +approval_required (BOOLEAN, default false),
  +approval_min_role (VARCHAR 64, optional Keycloak role).

Backend:
- Entity RecordDraft + Repository с JPQL queries для:
  * findPendingByKey (single pending lookup)
  * findPending (global queue для approver pool, paginated)
  * findPendingByDictionary (per-dict list)
  * findByMaker (own drafts tracking, paginated)
- DTO SubmitDraftRequest, DraftResponse.
- DraftService skeleton:
  * submit() — creates pending draft. 409 на exclusion violation.
  * findById, listPendingByDictionary, listPendingGlobal — read-only.
  * approve / reject / withdraw / updateDraft — Phase 1 stubs (комментарии).
- DraftController с 4 endpoints:
  * POST /api/v1/dictionaries/{name}/records/drafts — submit
  * GET /api/v1/dictionaries/{name}/records/drafts — list per dict
  * GET /api/v1/drafts/{id} — single draft
  * GET /api/v1/admin/reviews/pending — global queue (paginated)

Tests:
- DraftServiceTest 6 unit tests:
  * submit creates with PENDING status
  * 409 на duplicate pending business_key (exclusion constraint)
  * invalid WKT → 400
  * dict not found → 404
  * findById unknown → 404
  * listPendingByDictionary returns multiple pending
- StubDraftRepo simulates DB exclusion constraint в memory.

Verify:
- mvn -pl ordinis-rest-api -am test: 112/112 PASS (+6 new).
- mvn -P e2e -pl ordinis-app -am test: 20/20 PASS — migration 0019
  applies clean, no regression.
- helm/yaml configs не трогали — Phase 0 чистый schema + code.

Phase 1 (next session) — full lifecycle:
- DraftService.approve(): SERIALIZABLE tx с COPY draft → live + outbox
  RecordCreated/Updated/Deleted event + audit. Validate against schema
  ON APPROVE (могла schema измениться с момента submit'а).
- reject() — mark status=rejected, kept (D4).
- withdraw() — maker отзывает свой pending.
- DictionaryRecordService.create/update/close: pre-check
  approval_required → 409 draft_required. JWT subject → maker_id.
- Reviewer queue + diff viewer admin UI.

Source: ~/.gstack/projects/claude/zimin-main-design-approval-workflow-v2-20260507-121632.md
2026-05-08 13:08:21 +03:00
Zimin A.N. 48df5ceeb8 feat(search): smart JSONB search across all dictionaries
CEO plan v1 stretch — закрывает gap "Smart JSONB search across all dictionaries".
Last gap из v1 list shipped.

Migration 0018:
- CREATE EXTENSION pg_trgm (CNPG initdb обычно не enable'ит, добавили
  явно с MARK_RAN preCondition если уже есть).
- CREATE INDEX idx_dict_records_data_trgm
    ON dictionary_records USING GIN ((data::text) gin_trgm_ops)
- Trigram-based ILIKE с минимум 3 символа в query — index используется.
  ILIKE '%pat%' на data::text возвращает любые matches в JSONB serialized.

Backend:
- New RecordSearchQuery (ordinis-domain): native SQL c ROW_NUMBER()
  per-dict cap. SQL injection защищён PreparedStatement param + extension
  whitelist (allowed_scopes — text[]).
- New SearchController (ordinis-rest-api): GET /api/v1/search?q=&size&perDict.
  Default size=100, perDict=10. Min q length=3 (silently empty if shorter).
  Scope filtering through ScopeContext — каждый caller видит только свои
  scope levels. Results grouped per dict с display name + count + items.

Admin UI:
- New /search route с SearchInput + grouped Panel results.
- URL state ?q=… — share-friendly link "/search?q=SAR-X".
- Per-result link → /dictionaries/{dict}?q={businessKey} для drill-down.
- Min-3 hint, empty state, loading + error.
- New "Поиск" / "Search" tab в navigation header.
- i18n RU (с правильными plurals search.totalHits) + EN.

Behavior:
- Active records only (valid_from <= now() < valid_to).
- Per-dict cap 10 — защита от dominant-dict skew (один dict с 1000 matches
  не забьёт результат).
- Total cap 100 — admin "find this code" use case достаточно. Browser-style
  search-as-you-type (10k+ matches, instant) — отложен на v2 с dedicated
  index server (Elastic / Meili).

Verify:
- mvn -P e2e -pl ordinis-app -am test: 20/20 PASS (migration applied).
- pnpm tsc --noEmit: clean.
- pnpm test (vitest): 89/89 PASS.
- pnpm build: clean.

После migration apply'я index size на dictionary_records будет ~30-40%
data column. На текущих 5k records ~3-5 MB, acceptable.
2026-05-08 12:53:44 +03:00
Zimin A.N. 0a8275ef4c feat(redis-projection): per-dict feature flag (CEO plan E2 tiered perf)
Per-dictionary opt-in для Redis projection materialization. Default false
— projection-writer пропускает event'ы того dict'а, никаких dead writes
в Redis. Включается админ'ом через UI checkbox в Metadata tab.

Migration 0017:
- ALTER TABLE dictionary_definitions ADD COLUMN redis_projection_enabled
  BOOLEAN NOT NULL DEFAULT false.
- Index idx_dict_def_redis_proj для быстрого filtering в list queries.

Backend:
- DictionaryDefinition entity: new field + getter/setter.
- DictionaryResponse DTO: returns flag в response.
- CreateDictionaryRequest DTO: optional Boolean (null/missing = no change).
- DictionaryDefinitionService.create + updateSchema: применяет flag из request.
- ProjectionWriter (projection-writer service):
  * upsert() — early-return + skip counter если flag=false на dict.
  * delete() — symmetric: skip если flag=false (защита от stale keys
    после flag-flip; полный cleanup TODO Phase 2).
  * New metric: ordinis_projection_records_skipped_total.

Admin UI:
- DictionaryEditorDialog Metadata tab: checkbox "Включить Redis-проекцию"
  с описанием. Apply через CreateDictionaryRequest payload.
- DictionaryDefinition + CreateDictionaryRequest types updated.
- i18n RU/EN: schema.redisProjection.{label,hint}.

Что НЕ делается (deferred Phase 2):
- read-api Redis routing — read-api сейчас всегда идёт в PG read replica.
  Когда dict опт-инится в флаг, projection материализуется, но read-api
  ещё не использует. Read routing — отдельная feature с benchmark proof
  (через JMH + k6 SLO test).
- One-shot cleanup job для stale keys после flag-flip from true→false.

Behavior change в production:
- До patch: projection-writer пишет в Redis для ВСЕХ dict events (40
  dictionaries). Default flag=false после migration → projection-writer
  пропускает всё → Redis keys для existing dicts становятся stale.
  Это OK потому что read-api НИКОГДА не читал из Redis (writes были
  dead). Stale keys eventually evicted Redis maxmemory policy.
- После patch: только dicts с redis_projection_enabled=true получают
  материализацию. По default — нет. Admin opt-ins per-dict через UI.

Verify:
- mvn test (full reactor): SUCCESS, all green.
- mvn -P e2e -pl ordinis-app -am test: 20/20 PASS (migration 0017 applied).
- pnpm tsc --noEmit: clean.
- pnpm test (vitest): 89/89 PASS.
- pnpm build: clean.
2026-05-08 12:34:58 +03:00
Zimin A.N. c11044c32e feat(bench): JMH microbenchmarks module + manual CI job
CEO plan v1 polish — закрывает gap "JMH performance benchmarks в CI для
baseline + Redis-enabled scenarios".

New module:
- ordinis-bench/ — JMH 1.37 microbenchmarks. Gated behind `bench` Maven
  profile в parent pom — НЕ строится при обычном `mvn package` (default
  CI остаётся быстрым).
- maven-shade-plugin под `bench` profile собирает uber-jar
  `target/benchmarks.jar` (86 MB, ~12 sec build).
- LineageBenchmark covers hot paths из dict-relationships-v2:
  * parseRef_simple / withSchemaButNoOnClose / withOnClose
  * onCloseAction_block / cascade / null
  * schemaTraversal_findRefs (40 props, 5 refs — realistic shape)

Baseline numbers (M3 MBP, JDK 25, single thread):
- onCloseAction_*: 0.6–12 ns/op
- parseRef_*: 20–93 ns/op
- schemaTraversal: 417 ns/op (~83 ns per ref на 40 props)
Cumulative budget for findSchemaDependents на 40 dicts × 40 props × 5 refs:
~17 µs. p99 endpoint SLO = 200 ms — запас 4 порядка. README documents
budget + 2x regression alarm.

CI integration:
- New job maven-bench (stage: test). Manual trigger only:
  * RUN_BENCH=true variable, OR
  * web pipeline source с manual click.
- Default CI (push/merge) НЕ запускает bench — slow + noisy в history.
- Output artifacts: bench-results.json + bench-results.txt (5 day expire).
- Quick smoke config: 1 fork, 2 warmups, 3 measurements × 2s = ~5 min total.

Side effect: ReferenceValidator.parseRef static methods переведены из
package-private в public. Они и так часть public ParsedRef contract —
visible to bench module без изменения design intent.

Verify:
- mvn -P bench -pl ordinis-bench -am package: BUILD SUCCESS (12s).
- java -jar benchmarks.jar -f 1 -wi 1 -i 2 Lineage: all 7 benchmarks
  exec'ятся, valid ns/op numbers.
- mvn -pl ordinis-rest-api -am test: 106/106 PASS unchanged.
- glab ci lint: clean.

README в ordinis-bench/README.md документирует:
- baseline numbers + 2x regression budget
- local run options (smoke / full / GC profile / JSON output)
- when CI bench runs (manual web trigger)
- difference vs k6/wrk (HTTP load tests are different layer, both needed)
- how to add new benchmark
2026-05-08 12:22:18 +03:00
Zimin A.N. 7d2199a3f3 fix(lineage): 3 e2e CI failures — Liquibase XSD + JSONB ?-op + size cap
Phase 4 e2e suite (skipped в local mvn verify, гонится только на CI с
testcontainers) поймал 3 issues. Все исправлены, e2e теперь 20/20 PASS
локально (Postgres testcontainer):
- AuthE2ETest 6/6
- AutoDeriveGeometryE2ETest 6/6
- BitemporalE2ETest 4/4
- OutboxKafkaE2ETest 1/1
- SmokeE2ETest 1/1
- WebhookE2ETest 2/2

Fix #1 — Liquibase XSD ordering (0016 changeset):
- <comment> должен идти ПОСЛЕ <preConditions>. Liquibase XSD строгий:
  preConditions → comment → operations.
- "Invalid content was found starting with element preConditions" на
  startup → ApplicationContext fail → весь webserver не поднимается.

Fix #2 — JSONB ?-operator vs JDBC parameter substitution (0016):
- Postgres JDBC PreparedStatement обрабатывает любой `?` как $N
  placeholder. SQL "prop.value ? 'x-references'" → "prop.value $1
  'x-references'" → "syntax error at or near $1". Same для regex с $
  anchor.
- Replaced `?` operator на эквивалент `-> 'key' IS NOT NULL`,
  drop-or-replace regex anchors на `LIKE '%.%'` (split_part guards
  malformed values gracefully).
- Comment в migration документирует ловушку для будущих changesets.

Fix #3 — service size cap mismatch (LineageIndexService):
- CascadeCloseService.evaluatePlan вызывает findRecordDependents с
  size=CASCADE_MAX_PER_REQUEST=500. Но findRecordDependents enforced
  size 1..200 → IllegalArgumentException → 400 на DELETE record path.
- Bumped service cap до 500. Controller отдельно держит public cap=200
  (UI не нуждается в больше).
- Test updated: expects "size 1..500".

Lessons learned:
- Local pre-push discipline должна включать `mvn -P e2e` для миграций.
  Не запустил, потому что: e2e требует Docker, медленнее, не было в
  routine. Now corrected — будущие migration changes будут идти через
  e2e check.
- Liquibase JDBC рабочий принцип: SQL прогоняется через PreparedStatement
  → любой `?` или `$N` ловится. Documenting в migration comment.

Verify:
- mvn -pl ordinis-app -am -P e2e test: BUILD SUCCESS, 20/20 PASS (28s).
- mvn test: 106 unit tests + 20 e2e — все green.
2026-05-08 11:48:39 +03:00
Zimin A.N. a7cdd5df5c feat(lineage): Phase 4 — SLO metrics + bundle v1.3.0 pilot (warn mode)
dict-relationships-v2 epic, Phase 4 (final). Backend SLO instrumentation +
schema bundle pilot. Alert rules + runbook идут отдельным коммитом в
ordinis-infra.

Backend metrics (Micrometer / Prometheus):
- nsi_dependents_query_duration_seconds (Timer + p50/p95/p99 percentiles)
  labels: mode={schema|record|*_error}, target_dict
- nsi_cascade_close_total (Counter)
  labels: target_dict, outcome={success|blocked|cascade_required|too_large|timeout|error}
- nsi_cascade_close_duration_seconds (Timer + percentiles)
- nsi_lineage_mv_last_refresh_seconds_ago (Gauge, NaN when mv disabled)
- nsi_lineage_mv_row_count (Gauge)
- nsi_lineage_mv_last_duration_seconds (Gauge)
- nsi_lineage_mv_refresh_total{outcome=ok|error} (Counter)

Cardinality bound: target_dict tag — ≤40 dictionaries; outcome — 6 values.
Total time series ≈ 240 per app instance — приемлемо.

Optional MeterRegistry inject — null в test ctor'ах (back-compat).

Bundle v1.3.0 pilot:
- spacecraft.satellite_type_code → satellite_type.code теперь имеет
  x-references-on-close: warn. Закрытие satellite_type больше не
  блокируется через 1.3.0; spacecraft остаётся orphan; orphan scanner
  поднимет metric. Data steward потом repoints.
- bundle version 1.2.1 → 1.3.0, spacecraft schema 1.0.0 → 1.1.0
  (description обновлён с pilot context).
- WARN-mode выбран как safe pilot — validates новый code path без
  destructive cascade. CASCADE-mode flip может быть отдельным PR
  per-relationship после operator review.

Verify:
- mvn verify -pl '!ordinis-app': SUCCESS (5.7s).
- 106/106 tests still green (existing tests не задеты).
- helm lint в ordinis-infra: clean (alerts render correctly).

Backward-compat: REGRESSION test (ReferenceCloseRegressionTest) covers
v1.2.1-style schemas без x-references-on-close. WARN mode на one field
не меняет contract других — bundle import idempotent.

Roadmap: 4 phases  shipped. Cascade engine + lineage UI + materialized
view + SLO metrics live.
2026-05-08 11:34:29 +03:00
Zimin A.N. 3eeaba058f feat(cascade): Phase 3 — CascadeCloseService + 409 routing + UI confirm dialog
dict-relationships-v2 epic, Phase 3. Cascade engine + UX guards.

Backend:
- New CascadeCloseService:
  * evaluatePlan(target, key, at) — read-only, splits dependents по
    onClose mode (BLOCK / WARN / CASCADE).
  * executeCascade(target, key, when, reason, confirmed) —
    @Transactional(timeout=30, isolation=SERIALIZABLE) atomic close
    target + all CASCADE deps в one hop (design F.OUT). 503
    x_references_cascade_timeout если tx exceeds 30s, 400
    x_references_cascade_too_large если N > 500.
  * RecordCloseSink interface — test seam над repo+audit+outbox
    mechanics (concrete classes на JDK 25 + Mockito incompat).
- Wired DictionaryRecordService.close():
  * Optional<CascadeCloseService> inject через ctor (back-compat ctor
    для тестов с null deps).
  * Pre-close evaluatePlan: blockers → 409 x_references_blocked_by_dependents,
    cascade non-empty → 409 x_references_cascade_required (просит cascade-close
    endpoint). WARN-only — close проходит.
- Endpoints в DictionaryRecordController:
  * GET /dictionaries/{dict}/records/{key}/cascade-preview — read-only план.
  * POST /dictionaries/{dict}/records/{key}/cascade-close?confirmed=true —
    atomic execute. Existing DELETE остался (теперь учитывает план).

Tests (8 unit tests):
- evaluatePlan empty / split-by-mode (BLOCK/WARN/CASCADE)
- 409 blockers exist (not closed)
- 409 cascade-required без confirmed
- WARN-only — closes target only, warnings returned
- CASCADE — atomic close target + 2 cascaded (verifies order + reasons)
- BLOCK overrides CASCADE — 409 даже при confirmed=true
- Empty plan — closes only target

Admin UI:
- New CascadeConfirmDialog component:
  * Trigger: 409 на existing close → opens dialog с GET cascade-preview.
  * BLOCKERS section — Alert error, list первых 5, "resolve first" hint.
  * CASCADE section — per-source grouping, sample 3 + overflow,
    badges per (count, onClose mode).
  * WARN section — yellow Alert "будут orphan".
  * Reason input + "Type CONFIRM" gate если N > 50 (UX guard).
  * Cancel — close без changes.
- Wired в dictionaries.$name.tsx: existing close-confirm flow на 409
  cascade error pivots в new dialog (same UX path, transparent для user).
- Types в client.ts: CascadeEntry, CascadePlan, CascadeCloseResult.
- Mutation useCascadeCloseRecord, query useCascadePreview.
- i18n RU/EN: cascade.* (35 keys, plurals для счётчиков).

Verify:
- mvn -pl ordinis-rest-api -am test: 106/106 PASS (8 new cascade tests).
- mvn verify -pl '!ordinis-app': все модули SUCCESS (5.1s).
- pnpm tsc --noEmit: clean.
- pnpm test (vitest): 89/89 PASS.
- pnpm build: clean.

Backward-compat: bundle v1.2.1 (без x-references-on-close) → onClose=BLOCK
default → existing dependents теперь блокируют close (правильное поведение
для FK semantics). Если был race condition close-with-deps в v1, он
exposed теперь как 409. CRITICAL: REGRESSION test покрывает.
2026-05-08 11:23:46 +03:00