ИИшка / Orchestration / 09 of 10

MVP архитектура

Orchestration — координационный слой над уже существующими доменными модулями. Он управляет workflow, ожиданиями, retries, handoff, human gates и recovery, но не присваивает себе доменную истину Writer, Researcher, Curator, Skeptic, Dossier, Source Watch, Investigator или Experiment.

Главный архитектурный инвариант: canonical orchestration core должен работать без Temporal, Prefect, LangGraph или Kestra. Внешний orchestration engine — заменяемый execution adapter, а не system of record и не владелец policy.
01 / Architecture principles

Что обязательно остаётся нашим

Canonical state

OUR CORE
  • workflow IDs
  • step IDs
  • state transitions
  • revision history
  • module handoffs

Domain policy

OUR CORE
  • кто может что вызвать
  • какой gate обязателен
  • что считать stale
  • что требует human review
  • когда retry запрещён

Audit

OUR CORE
  • actor
  • action
  • scope
  • before/after revision
  • evidence/result refs

Execution engine

ADAPTER
  • durable timers
  • worker dispatch
  • retry scheduling
  • heartbeat
  • resume/replay

LLM reasoning

TOOL
  • Qwen proposes routing
  • summarizes state
  • generates candidate plans
  • never mutates canonical state directly

Module systems

EXTERNAL DOMAIN
  • retain own truth
  • retain own permissions
  • retain own verdicts
  • return signed/scoped outputs
02 / Logical architecture

Engine-neutral core + adapters

                                  ┌──────────────────────────┐
                                  │        Human / UI        │
                                  └────────────┬─────────────┘
                                               │
                                  ┌────────────▼─────────────┐
                                  │   Orchestration API/MCP  │
                                  │ auth • policy • revision │
                                  └────────────┬─────────────┘
                                               │
                 ┌─────────────────────────────▼─────────────────────────────┐
                 │                 ORCHESTRATION CORE                        │
                 │                                                         │
                 │ Workflow Service  • State Machine  • Routing Policy      │
                 │ Step/Handoff Svc   • Human Gates   • Retry Policy        │
                 │ Idempotency Svc    • Compensation  • Reconciliation      │
                 │ Audit/Event Log    • Outbox         • Projection Builder  │
                 └─────────────┬───────────────────────┬─────────────────────┘
                               │                       │
                      canonical│                       │dispatch
                               │                       ▼
                    ┌──────────▼─────────┐   ┌──────────────────────────────┐
                    │ Postgres + Outbox  │   │ Execution Engine Adapter     │
                    │ source of truth    │   │ Temporal / Prefect / other   │
                    └──────────┬─────────┘   └──────────────┬───────────────┘
                               │                            │
                               │                            ▼
                               │                  ┌───────────────────────┐
                               │                  │ Worker / Queue Layer  │
                               │                  │ bounded concurrency   │
                               │                  └───────────┬───────────┘
                               │                              │
         ┌─────────────────────┼──────────────────────────────┼─────────────────────┐
         │                     │                              │                     │
         ▼                     ▼                              ▼                     ▼
   Writer/Researcher      Curator/Skeptic              Investigator           Experiment
         │                     │                              │                     │
         └─────────────────────┴──────────────┬───────────────┴─────────────────────┘
                                              ▼
                                           Dossier
Why this split: если execution engine недоступен, мы всё равно можем прочитать каноническое состояние, увидеть ожидающий step, понять последний committed transition и восстановить execution после ремонта или смены адаптера.
03 / Canonical data model

Минимальные объекты MVP

WorkflowRun

{
  "workflow_run_id": "wf_...",
  "workflow_type": "ARTICLE_RESEARCH|INVESTIGATION|...",
  "scope_ref": "dossier_...",
  "status": "PENDING|RUNNING|WAITING|REVIEW|COMPLETED|FAILED|CANCELLED|PARTIAL",
  "current_step_refs": [],
  "policy_version": "orch-policy-v1",
  "revision": 17,
  "created_by": "...",
  "engine_ref": "optional"
}

StepRun

{
  "step_run_id": "step_...",
  "workflow_run_id": "wf_...",
  "step_type": "MODULE_CALL|HUMAN_GATE|TIMER|ROUTER|COMPENSATION",
  "owner": "researcher",
  "status": "READY|DISPATCHED|RUNNING|WAITING|SUCCEEDED|FAILED|STALE|CANCELLED",
  "attempt": 2,
  "idempotency_key": "...",
  "input_hash": "...",
  "result_ref": "...",
  "expected_revision": 16
}

Handoff

  • from module
  • to module
  • scope
  • requested capability
  • input refs
  • expected result contract

ApprovalGate

  • gate type
  • required role
  • bound revision
  • decision
  • single-use token/ref
  • expires/invalidates

ExecutionEvent

  • append-only
  • monotonic sequence
  • actor
  • transition
  • payload hash
  • trace correlation

Canonical workflow states

DRAFT
  ↓ start
PENDING
  ↓
RUNNING ───────────────┐
  │                    │
  ├─ needs module ───> WAITING_MODULE ──┐
  ├─ human gate ─────> WAITING_HUMAN ───┤
  ├─ retry delay ────> WAITING_RETRY ───┤
  ├─ stale input ────> NEEDS_REPLAN ────┤
  │                    │                 │
  └────────────────────┴─────────────────┘
                       ↓
                    RUNNING
                       ↓
             REVIEW / COMPLETED
                 ↘ FAILED
                  ↘ PARTIAL
                   ↘ CANCELLED
04 / Execution engine adapter

Движок исполняет, но не решает

CapabilityCore contractEngine responsibility
dispatchstart(step_ref, revision, idempotency_key)deliver to worker
timerschedule(resume_at, step_ref)durable wake-up
retrypolicy decides whether retry is legalexecute approved backoff schedule
heartbeatrecord liveness signal/refdetect lost worker
resumecore validates current canonical revisioncontinue execution
cancelcore creates cancellation intentstop dispatch where possible
replaycore enforces idempotency/reconciliationre-execute safely
Forbidden: engine-local workflow state не может быть единственным источником правды. Любое существенное состояние, влияющее на дальнейшую маршрутизацию или итог, обязано иметь canonical representation в нашем store.

Adapter shortlist

Temporal

PRIMARY DURABILITY SPIKE

Сильный кандидат для durable execution, retries, timers, replay и long-running workflows. Использовать через адаптер; не отдавать ему domain policy.

Prefect

PYTHON-FIRST ALTERNATIVE

Удобен для Python-heavy execution и operational workflows. Проверять durable semantics и recovery на нашем golden set.

LangGraph

AGENT FLOW SPECIALIST

Полезен для локальных reasoning graphs внутри шага, но не должен автоматически становиться глобальным orchestration system of record.

05 / Module contracts

Оркестратор знает контракты, но не внутреннюю логику

ModuleTypical orchestration actionResult ownership
Writerrequest draft / revise draftWriter owns draft artifact
Researcherresearch request / fill evidence gapResearcher owns research run + evidence refs
Curatorpromotion requestCurator owns permanent-RAG promotion decision
Skepticverification requestSkeptic owns verification verdict
Dossierread/append working contextDossier owns case state
Source Watchsubscribe / react to change eventSource Watch owns watch/freshness events
Investigatorcausal investigation requestInvestigator owns hypotheses/causal verdicts
Experimentcontrolled test requestExperiment owns design/run/result integrity

Handoff envelope

{
  "handoff_id": "ho_...",
  "workflow_run_id": "wf_...",
  "from": "orchestration",
  "to": "skeptic",
  "scope": {"dossier_id":"...","artifact_ref":"..."},
  "request_type": "VERIFY_CAUSAL_CLAIMS",
  "input_refs": ["..."],
  "required_output_schema": "skeptic.verdict.v1",
  "deadline_policy": "NO_AUTO_APPROVAL",
  "idempotency_key": "...",
  "trace_id": "..."
}
Rule: module result is attached only after actor identity, schema, scope, workflow, expected step and revision are validated. Plain text “done” is never completion evidence.
06 / Security & policy enforcement

Least privilege by default

API façade

  • authn/authz
  • role + capability checks
  • scope validation
  • rate limits
  • expected_revision

Worker identity

  • short-lived credentials
  • module-scoped capability
  • no direct canonical DB write
  • no cross-dossier access by default

Content isolation

  • untrusted content ≠ command
  • tool invocation schema validated
  • prompt injection cannot grant role
  • LLM output always candidate, never authority

Audit

  • append-only transition events
  • approval actor/ref
  • result hashes
  • policy version
  • engine attempt refs

Idempotency

  • side-effect command key
  • input hash
  • scope binding
  • stable prior-result lookup
  • duplicate suppression

Staleness

  • scope revision
  • artifact revision
  • module-result revision
  • invalidate dependent steps
  • replan before commit
07 / server2 resource model

Qwen 30B получает приоритет

Orchestration itself должен быть лёгким. Основная нагрузка — module jobs, особенно Qwen 30B, causal analysis, experiments, parsing и indexing. Поэтому scheduling обязан учитывать реальную загрузку server2.

Priority 0  CONTROL PLANE
            API / state transitions / audit / outbox
            must remain responsive

Priority 1  QWEN 30B INTERACTIVE / USER-BLOCKING
            Writer / Researcher / Investigator reasoning

Priority 2  MODULE BACKGROUND
            Curator indexing, Source Watch classification,
            Skeptic batch verification

Priority 3  HEAVY NUMERICAL / EXPERIMENT
            DoWhy / pgmpy / EconML / benchmark / bootstrap

Queues

  • separate control and heavy queues
  • per-module concurrency caps
  • priority classes
  • backpressure

Admission

  • GPU/CPU/RAM checks
  • load-aware deferral
  • no unbounded fan-out
  • deadline awareness

Benchmark

  • measure p50/p95
  • queue wait
  • Qwen latency impact
  • recovery time
  • no invented numbers
No fake capacity claims: реальные concurrency limits, p50/p95 и acceptable headroom определяются только practical benchmark на server2.
08 / MVP deployment topology

Минимальный self-hosted контур

server2
├── orchestration-api
├── orchestration-core
├── orchestration-worker-control
├── orchestration-worker-general
├── postgres
│   ├── orchestration schema
│   ├── event log
│   └── outbox
├── execution-engine (candidate adapter)
├── redis / broker (only if selected stack needs it)
├── observability
│   ├── structured logs
│   ├── metrics
│   └── traces
└── module APIs
    ├── writer
    ├── researcher
    ├── curator
    ├── skeptic
    ├── dossier
    ├── source-watch
    ├── investigator
    └── experiment

Transactional boundary

BEGIN
  validate expected_revision
  validate policy/capability
  mutate canonical workflow/step state
  append audit/event
  insert outbox command
COMMIT

outbox dispatcher
  ↓
execution engine / module API
  ↓
result callback
  ↓
validate + idempotent attach
  ↓
next canonical transition
Why outbox: state transition и намерение отправить следующий command должны коммититься атомарно. Иначе crash между DB commit и dispatch создаёт потерянный workflow step.
09 / MVP scope

Что входит и что не входит в MVP

IN MVP

REQUIRED
  • canonical Postgres state
  • workflow/step state machine
  • module handoff contracts
  • expected_revision + idempotency
  • event log + outbox
  • one execution-engine adapter
  • human approval gate
  • retry/backoff/cancel/reconcile
  • audit + basic observability
  • server2 load-aware concurrency
  • failure/security golden tests

NOT MVP-CRITICAL

LATER
  • visual no-code workflow builder
  • multi-engine active/active
  • cross-server federation
  • autonomous self-modifying workflow policy
  • complex BPMN compatibility
  • automatic compensation synthesis
  • multi-tenant SaaS control plane

Architecture decision gate

1. canonical core implemented enough for spike
2. Temporal / Prefect / alternative adapter spikes
3. golden failure/recovery suite
4. server2 practical benchmark
5. compare operational burden + recovery semantics
6. ADR: REUSE / ADAPT / BUILD
7. freeze MVP engine choice
Final principle: выбрать engine можно только после practical spike. README, popularity и feature checklist недостаточны.
10 / Next

Следующий документ

AI_orchestration_10_план_реализации_MVP.html

В нём: repo layout, migrations, coding phases, engine spike, golden tests, server2 benchmark, ADR, rollout/shadow mode и Definition of Orchestration MVP Done.