Compare commits
69
Commits
master
..
75b93bbba5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75b93bbba5 | ||
|
|
f0fc084fbb | ||
|
|
d7478726a8 | ||
|
|
504f77cb7c | ||
|
|
3402fd69d4 | ||
|
|
827b783be3 | ||
|
|
751aaed4b1 | ||
|
|
57caeb6b5a | ||
|
|
cf41f7c64d | ||
|
|
6c706a727e | ||
|
|
c7e7a86627 | ||
|
|
02f385866f | ||
|
|
763b025557 | ||
|
|
1aec062aba | ||
|
|
5596ca935c | ||
|
|
41700c27e5 | ||
|
|
8e4532f6f5 | ||
|
|
dd4021b678 | ||
|
|
568ff6643e | ||
|
|
d2e684f0cf | ||
|
|
6ffb90d1d1 | ||
|
|
61dcb6bf13 | ||
|
|
21937f920f | ||
|
|
f1ee385a1b | ||
|
|
3de1dcdc84 | ||
|
|
b6c04f2296 | ||
|
|
adca7c6edc | ||
|
|
2891b37e75 | ||
|
|
54099e1da3 | ||
|
|
96e934ed8f | ||
|
|
c8cb263c77 | ||
|
|
81dd816df2 | ||
|
|
58cae16ef8 | ||
|
|
8cb5a664c6 | ||
|
|
df345b32e1 | ||
|
|
b1916236f4 | ||
|
|
5c3c238d17 | ||
|
|
3b3cb5bd7f | ||
|
|
8cd30488d2 | ||
|
|
e927afdb09 | ||
|
|
7ac1a4a11b | ||
|
|
5ca2cdc9af | ||
|
|
7dca40c55e | ||
|
|
de9dc61ebc | ||
|
|
a335f654ed | ||
|
|
51fa19a8ee | ||
|
|
91731fd317 | ||
|
|
62986245a2 | ||
|
|
148868bdfb | ||
|
|
d2744bc1ac | ||
|
|
2b19277b1e | ||
|
|
a774a2fbbd | ||
|
|
98df351235 | ||
|
|
28055a8551 | ||
|
|
0e4eb1738c | ||
|
|
70a0c6065e | ||
|
|
a41580aceb | ||
|
|
e4253eb076 | ||
|
|
db901d6401 | ||
|
|
24f9d6195b | ||
|
|
5aa766acff | ||
|
|
f9760fc098 | ||
|
|
00826a40d3 | ||
|
|
76c9673ab3 | ||
|
|
3794df20d4 | ||
|
|
d7fb96bb70 | ||
|
|
bf8e4e3cd1 | ||
|
|
b0f463ac5c | ||
|
|
ec540a1a72 |
@@ -0,0 +1,181 @@
|
||||
---
|
||||
name: "OPSX: Apply"
|
||||
description: "Implement tasks from an OpenSpec change (Experimental)"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "artifacts", "experimental"]
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
- Optional `context`: current required project instruction input from the selected root
|
||||
- Optional `operationGuidance`: current advisory guidance for apply
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue` (if it is not installed, run `openspec status --change "<name>" --json` to see the next artifact and `openspec instructions <artifact-id> --change "<name>" --json` for how to create it)
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
Treat `context` as a required prompt-level input. Read and consider it, and
|
||||
apply relevant project facts, conventions, and constraints while implementing.
|
||||
Treat `operationGuidance` as optional additive advice. Read and consider every
|
||||
entry, and follow entries that are applicable and compatible with the built-in
|
||||
workflow.
|
||||
|
||||
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
|
||||
progress, `contextFiles`, and the built-in `instruction`. They are not
|
||||
evidence of task completion, do not replace the built-in instruction, and do
|
||||
not permit bypassing a blocked state. If context conflicts with the built-in
|
||||
instruction, an explicit user choice, or a CLI-controlled value, report the
|
||||
conflict and preserve the controlling value. If guidance is inapplicable or
|
||||
conflicts with those controlling inputs, do not follow it and explain why.
|
||||
These are prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
Do not copy `context` or `operationGuidance` verbatim into implementation
|
||||
files or planning artifacts unless the user separately asks for that content.
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! You can archive this change with `/opsx:archive`.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
- Do not use context or operation guidance as proof that a task is complete
|
||||
- Apply relevant project context; report conflicts with controlling workflow inputs
|
||||
- Consider every guidance entry; explain any inapplicable or conflicting advice
|
||||
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
|
||||
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
@@ -0,0 +1,225 @@
|
||||
---
|
||||
name: "OPSX: Archive"
|
||||
description: "Archive a completed change in the experimental workflow"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "archive", "experimental"]
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:archive <other>`).
|
||||
|
||||
**Load current archive inputs before the existing archive checks:**
|
||||
|
||||
After resolving the selected change and planning root, run:
|
||||
```bash
|
||||
openspec instructions archive --change "<name>" --json
|
||||
```
|
||||
Keep the same selected-root flags on this command. This lookup is advisory and
|
||||
optional: it only supplies extra prompt inputs, so it must never block archiving.
|
||||
If it exits non-zero or returns invalid JSON — for example on an older CLI that
|
||||
does not support this command yet — continue the archive workflow with no
|
||||
context and no operation guidance. Do not report an error and do not stop.
|
||||
|
||||
A successful response may omit both optional fields. Treat `context` as a
|
||||
required prompt-level input: read and consider it, and apply relevant project
|
||||
facts, conventions, and constraints. Treat `operationGuidance` as optional
|
||||
additive advice: read and consider every entry, and follow entries that are
|
||||
applicable and compatible with the built-in archive workflow.
|
||||
|
||||
Keep both fields separate from built-in steps, explicit user choices, resolved
|
||||
paths, CLI checks, and command contracts. If context conflicts with one of those
|
||||
controlling inputs, report the conflict and preserve the controlling value. If
|
||||
guidance is inapplicable or conflicts with a controlling input, do not follow it
|
||||
and explain why. Do not infer replacement paths, skipped prompts, or flags from
|
||||
either field, and do not copy their text verbatim into specs, change artifacts,
|
||||
or archive summaries unless the user separately asks for it. These are
|
||||
prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
|
||||
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
|
||||
|
||||
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
|
||||
- Display warning listing incomplete artifacts
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||
|
||||
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
|
||||
delta-spec source. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
|
||||
delta specs from other artifacts.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Show a combined summary before prompting
|
||||
|
||||
**Prompt options:**
|
||||
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
Route on the answer:
|
||||
- "Cancel" — stop, do not archive
|
||||
- "Archive without syncing" or "Archive now" — proceed to archive
|
||||
- "Sync now" or "Sync anyway" — sync, then verify (below)
|
||||
- Anything else — ask again rather than archiving
|
||||
|
||||
Before a selected sync writes any main spec, run
|
||||
`openspec instructions specs --change "<name>" --json` once with the same
|
||||
selected-root flags. Require a zero exit status and valid artifact-instruction
|
||||
JSON. If the lookup fails or returns invalid JSON, report the error and stop
|
||||
before writing any main spec or moving the change. A valid response with omitted
|
||||
`rules` is the no-rules case. Apply returned `rules` only to the content and
|
||||
form of main specs produced by this merge; do not use them as archive guidance,
|
||||
change CLI behavior, or copy the rule text into any output file.
|
||||
|
||||
Then run the `/opsx:sync` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
|
||||
|
||||
Then re-run the comparison from the top of this step against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
|
||||
- ADDED requirements present
|
||||
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
|
||||
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty; a spec the sync deliberately kept and reported is also a match
|
||||
- RENAMED requirements present under the new name and absent under the old one
|
||||
|
||||
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p "<planningHome.changesDir>/archive"
|
||||
```
|
||||
|
||||
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move `changeRoot` to the archive directory
|
||||
|
||||
```bash
|
||||
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Spec sync status (synced / sync skipped / no delta specs)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** ✓ Synced to main specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success (No Delta Specs)**
|
||||
|
||||
```markdown
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** No delta specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success With Warnings**
|
||||
|
||||
```markdown
|
||||
## Archive Complete (with warnings)
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** Sync skipped (user chose to skip)
|
||||
|
||||
**Warnings:**
|
||||
- Archived with 2 incomplete artifacts
|
||||
- Archived with 3 incomplete tasks
|
||||
- Delta spec sync was skipped (user chose to skip)
|
||||
|
||||
Review the archive if this was not intentional.
|
||||
```
|
||||
|
||||
**Output On Error (Archive Exists)**
|
||||
|
||||
```markdown
|
||||
## Archive Failed
|
||||
|
||||
**Change:** <change-name>
|
||||
**Target:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
|
||||
Target archive directory already exists.
|
||||
|
||||
**Options:**
|
||||
1. Rename the existing archive
|
||||
2. Delete the existing archive if it's a duplicate
|
||||
3. Wait until a different date to archive
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Announce the selected change; prompt for selection when it is ambiguous
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, run the `/opsx:sync` workflow inline (agent-driven)
|
||||
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
|
||||
- Consider every guidance entry and explain any inapplicable or conflicting advice
|
||||
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
|
||||
- Artifact rules constrain only the specs being written and are never operation guidance
|
||||
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
|
||||
@@ -0,0 +1,193 @@
|
||||
---
|
||||
name: "OPSX: Explore"
|
||||
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "explore", "experimental", "thinking"]
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing. For a new change, scaffold it first as described below.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
|
||||
- A vague idea: "real-time collaboration"
|
||||
- A specific problem: "the auth system is getting unwieldy"
|
||||
- A change name: "add-dark-mode" (to explore in context of that change)
|
||||
- A comparison: "postgres vs sqlite for this"
|
||||
- Nothing (just enter explore mode)
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Use ASCII diagrams liberally │
|
||||
├─────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────┐ ┌────────┐ │
|
||||
│ │ State │────────▶│ State │ │
|
||||
│ │ A │ │ B │ │
|
||||
│ └────────┘ └────────┘ │
|
||||
│ │
|
||||
│ System diagrams, state machines, │
|
||||
│ data flows, architecture sketches, │
|
||||
│ dependency graphs, comparison tables │
|
||||
│ │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names, schemas, and status
|
||||
- What the user might be working on
|
||||
|
||||
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
|
||||
- `context`: project background - tech stack, conventions, constraints
|
||||
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
|
||||
|
||||
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
|
||||
|
||||
If the user mentioned a specific change name, read its artifacts for context.
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
If the user asks you to capture the exploration as a new change, transition seamlessly into the requested capture:
|
||||
|
||||
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
|
||||
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
|
||||
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.
|
||||
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
|
||||
|
||||
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status.
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Resolve and read existing artifacts for context**
|
||||
- Run `openspec status --change "<name>" --json`.
|
||||
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
|
||||
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|----------------------------|-------------------------------------|
|
||||
| New requirement discovered | `specs/<capability-path>/spec.md` |
|
||||
| Requirement changed | `specs/<capability-path>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
@@ -0,0 +1,145 @@
|
||||
---
|
||||
name: "OPSX: Propose"
|
||||
description: "Propose a new change - create it and generate all artifacts in one step"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "artifacts", "experimental"]
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
|
||||
|
||||
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
|
||||
- proposal.md (what & why)
|
||||
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
When the user is ready to implement, they must start the apply workflow explicitly.
|
||||
|
||||
---
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Understand the request and clarify material ambiguity**
|
||||
|
||||
If no input is provided, ask the user (open-ended, no preset options):
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
|
||||
|
||||
2. **Determine the workflow schema**
|
||||
|
||||
Use the configured default schema unless the user explicitly requests a different workflow.
|
||||
|
||||
**Use a different schema only if the user:**
|
||||
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
|
||||
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; `schemas` does not accept `--store`. If context reports only `no_openspec_root`, run `openspec schemas --json` from the current working directory instead. Do not use this fallback for invalid or unavailable stores.
|
||||
|
||||
Otherwise, omit `--schema` to preserve the configured default.
|
||||
|
||||
3. **Create the change directory**
|
||||
|
||||
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
|
||||
|
||||
Using the configured default:
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
|
||||
Using an explicitly requested schema:
|
||||
```bash
|
||||
openspec new change "<name>" --schema "<schema-name>"
|
||||
```
|
||||
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
|
||||
|
||||
4. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
5. **Create every artifact in the required set**
|
||||
|
||||
Use a todo list to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
|
||||
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
|
||||
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
|
||||
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
|
||||
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
|
||||
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
|
||||
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
|
||||
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
|
||||
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
|
||||
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Ask the user to clarify
|
||||
- Then continue with creation
|
||||
|
||||
6. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
|
||||
- What's ready: "All artifacts needed for implementation are ready."
|
||||
- Prompt: "The artifacts are ready for review. When you are ready, run `/opsx:apply`."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
|
||||
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
|
||||
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
|
||||
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
|
||||
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
@@ -0,0 +1,258 @@
|
||||
---
|
||||
name: "OPSX: Sync"
|
||||
description: "Sync delta specs from a change to main specs"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "specs", "experimental"]
|
||||
---
|
||||
|
||||
Sync delta specs from a change to main specs.
|
||||
|
||||
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show changes that have delta specs (under `specs/` directory).
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:sync <other>`).
|
||||
|
||||
2. **Resolve change context**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
|
||||
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
|
||||
|
||||
3. **Find delta specs**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
|
||||
only source of delta spec paths. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, report that there are no delta specs to sync,
|
||||
do not infer them from other artifacts, and stop without requesting artifact
|
||||
instructions or writing a main spec.
|
||||
|
||||
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
|
||||
A caller narrows it by naming an explicit list of complete entries from
|
||||
`existingOutputPaths` — copy those absolute values verbatim. Archive does
|
||||
this inline, and a user can too (for example, by selecting the entry ending
|
||||
in `/specs/billing/invoices/spec.md`).
|
||||
Then sync only the named paths and leave the remaining delta specs untouched:
|
||||
bulk archive excludes a delta whose implementation it could not find, and
|
||||
syncing it anyway would write a main spec the caller deliberately withheld.
|
||||
Carry that narrowed selection through step 4; never widen it back to the full
|
||||
list. If a named path is not in `existingOutputPaths`, do not sync it —
|
||||
report it and stop, rather than dropping it silently. If the named list is
|
||||
empty, report that there is nothing to sync and stop without writing a main
|
||||
spec.
|
||||
|
||||
Each delta spec file contains sections like:
|
||||
- `## ADDED Requirements` - New requirements to add
|
||||
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||
- `## REMOVED Requirements` - Requirements to remove
|
||||
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||
|
||||
If no delta specs found, inform user and stop.
|
||||
|
||||
4. **For each delta spec, apply changes to main specs**
|
||||
|
||||
Before the first main-spec write, obtain one current specs-rule snapshot:
|
||||
- If archive invoked this workflow inline and supplied a valid snapshot from
|
||||
`openspec instructions specs --change "<name>" --json`, reuse it and do not
|
||||
fetch the same instructions again.
|
||||
- Otherwise run that command once now with the same selected-root flags.
|
||||
- If the direct lookup exits non-zero or returns invalid artifact-instruction
|
||||
JSON, report the error and stop before writing any main spec. Do not treat the
|
||||
failure as an absent rule set.
|
||||
- A valid response with omitted `rules` means no artifact rules are configured
|
||||
and the existing semantic merge continues.
|
||||
|
||||
Apply returned `rules` only to the content and form of the main specs produced
|
||||
by this merge. Artifact rules are not operation guidance and cannot change
|
||||
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
|
||||
constraints without copying it verbatim into a main spec or summary.
|
||||
|
||||
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
|
||||
|
||||
a. **Read the delta spec** to understand the intended changes
|
||||
|
||||
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
|
||||
|
||||
c. **Apply changes intelligently**:
|
||||
|
||||
**ADDED Requirements:**
|
||||
- If requirement doesn't exist in main spec → add it
|
||||
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||
|
||||
**MODIFIED Requirements:**
|
||||
- Find the requirement in main spec
|
||||
- Apply the changes - this can be:
|
||||
- Adding new scenarios the main spec does not have yet
|
||||
- Modifying existing scenarios
|
||||
- Changing the requirement description
|
||||
- Preserve scenarios/content not mentioned in the delta
|
||||
|
||||
**REMOVED Requirements:**
|
||||
- Remove the entire requirement block from main spec
|
||||
- Retiring the capability. Delete the whole `spec.md` - and the directory once
|
||||
nothing else is left in it - only when ALL of these hold:
|
||||
1. removing the requirements *this run* left no requirement blocks;
|
||||
2. the rest of the spec is well-formed (it still has a `## Purpose`);
|
||||
3. the main spec was not already empty before this sync - if you removed
|
||||
nothing, change nothing;
|
||||
4. every other nonblank line in the whole file is accounted for as the
|
||||
title, Purpose, Requirements header, or a canonical requirement's
|
||||
statement, scenarios, or fenced examples;
|
||||
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
|
||||
6. the `spec.md` resolves inside the real specs root (do not follow a
|
||||
capability-directory symlink to delete an external file).
|
||||
If removing the selected requirements would leave no requirement blocks and
|
||||
any retirement condition is not satisfied, do not modify the main spec. Stop
|
||||
the sync for that capability, report the blocking condition, and tell the user
|
||||
how to resolve it. Never write or leave an empty `## Requirements` section.
|
||||
When only the marker is missing, say that too - it is the one thing the user
|
||||
can add to make the retirement go through.
|
||||
- Deleting the file also deletes its `## Purpose`; any other section blocks
|
||||
retirement. Name Purpose when you report the retirement. Include a pasteable
|
||||
`git checkout` only when the spec lived in the caller's checkout;
|
||||
otherwise give checkout-scoped recovery guidance.
|
||||
|
||||
**RENAMED Requirements:**
|
||||
- Find the FROM requirement, rename to TO
|
||||
|
||||
**`## Purpose` in the delta:**
|
||||
- The main spec already has one and it is authoritative - leave it alone
|
||||
(this is what `openspec archive` does; it warns and moves on)
|
||||
|
||||
d. **Create new main spec** if capability doesn't exist yet:
|
||||
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
|
||||
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
|
||||
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
|
||||
- Add Requirements section with the ADDED requirements
|
||||
- Follow the **Main Spec Format Reference** below
|
||||
|
||||
5. **Validate updated main specs**
|
||||
|
||||
Run `openspec validate --specs` with the same selected-root flags used earlier.
|
||||
If validation fails, report the problems and do not claim the sync succeeded.
|
||||
|
||||
6. **Show summary**
|
||||
|
||||
After applying all changes, summarize:
|
||||
- Which capabilities were updated
|
||||
- What changes were made (requirements added/modified/removed/renamed)
|
||||
- Any new main spec left with a TBD Purpose placeholder, so it gets written
|
||||
now rather than lingering
|
||||
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
|
||||
either a pasteable `git checkout` or checkout-scoped recovery guidance
|
||||
|
||||
**Delta Spec Format Reference**
|
||||
|
||||
```markdown
|
||||
## Purpose
|
||||
|
||||
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Existing Feature
|
||||
The system SHALL keep doing the existing thing, now also handling A.
|
||||
|
||||
#### Scenario: Scenario the main spec already has
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
#### Scenario: New scenario to add
|
||||
- **WHEN** user does A
|
||||
- **THEN** system does B
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: Deprecated Feature
|
||||
|
||||
## RENAMED Requirements
|
||||
|
||||
- FROM: `### Requirement: Old Name`
|
||||
- TO: `### Requirement: New Name`
|
||||
```
|
||||
|
||||
**Main Spec Format Reference**
|
||||
|
||||
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
|
||||
|
||||
```markdown
|
||||
# <capability> Specification
|
||||
|
||||
## Purpose
|
||||
Short description of what this capability does and why it exists.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
```
|
||||
|
||||
**Key Principle: Intelligent Merging**
|
||||
|
||||
Unlike programmatic merging, you merge rather than overwrite:
|
||||
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
|
||||
- Keep anything the delta does not mention, in the main spec's existing order
|
||||
- Use your judgment to merge changes sensibly
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Specs Synced: <change-name>
|
||||
|
||||
Updated main specs:
|
||||
|
||||
**<capability-1>**:
|
||||
- Added requirement: "New Feature"
|
||||
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||
|
||||
**<capability-2>**:
|
||||
- Created new spec file
|
||||
- Added requirement: "Another Feature"
|
||||
|
||||
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Read both delta and main specs before making changes
|
||||
- Preserve existing content not mentioned in delta
|
||||
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
|
||||
- If something is unclear, ask for clarification
|
||||
- Show what you're changing as you go
|
||||
- The operation should be idempotent - running twice should give same result
|
||||
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
|
||||
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
|
||||
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
|
||||
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
|
||||
- Artifact rules constrain only the specs being written and are never copied into output files
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
name: "OPSX: Update"
|
||||
description: "Update a change - revise existing planning artifacts and keep them coherent (Experimental)"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "artifacts", "experimental"]
|
||||
---
|
||||
|
||||
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:update` (e.g., `/opsx:update add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
`/opsx:continue` is an expanded-profile workflow and may not be installed. Before suggesting it anywhere below, verify that it is available. If it is unavailable, `openspec status --change "<name>" --json` shows the next artifact and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to create it.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one
|
||||
|
||||
When prompting, present the top 3-4 most recently modified changes as options, showing:
|
||||
- Change name
|
||||
- Schema (from `schema` field if present, otherwise "spec-driven")
|
||||
- Status (e.g., "0/5 tasks", "complete", "no tasks")
|
||||
- How recently it was modified (from `lastModified` field)
|
||||
|
||||
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:update <other>`).
|
||||
|
||||
2. **Get the change's artifacts**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand current state. The response includes:
|
||||
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
|
||||
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
|
||||
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
|
||||
|
||||
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
|
||||
|
||||
3. **Understand the request**
|
||||
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
|
||||
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
|
||||
|
||||
4. **Read and reconcile**
|
||||
- Read the artifact(s) the request touches and the change's other existing artifacts.
|
||||
- Apply the requested edit. Then check every other existing artifact against it - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
|
||||
- Note everything that is now inconsistent, missing, or contradictory.
|
||||
- Revise only files that already exist (`existingOutputPaths`). Do NOT create artifacts that don't exist yet, and do NOT invent new files under a glob artifact - note them and point the user to `/opsx:continue` to create them.
|
||||
- If the change is already coherent, say so and make no edits.
|
||||
|
||||
5. **Confirm and apply, one artifact at a time**
|
||||
- Show each proposed revision and why. Write only after the user confirms.
|
||||
- If the user rejects a revision, do not write it - leave that artifact unchanged.
|
||||
- When a substantial rewrite is needed, get that artifact's rules and template first:
|
||||
```bash
|
||||
openspec instructions "<artifact-id>" --change "<name>" --json
|
||||
```
|
||||
|
||||
6. **Point to the next step (guidance only - NEVER act on it)**
|
||||
- Artifacts still missing -> suggest `/opsx:continue` to create them.
|
||||
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/opsx:apply` to carry the delta into code.
|
||||
- Everything done and implemented -> suggest `/opsx:archive`.
|
||||
|
||||
**Output**
|
||||
|
||||
After each invocation, show:
|
||||
- Which artifacts were revised (and which proposed revisions were rejected)
|
||||
- Anything deferred to `/opsx:continue` (not-yet-created artifacts or files)
|
||||
- Where the change stands and the recommended next command
|
||||
|
||||
**Guardrails**
|
||||
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/opsx:apply`.
|
||||
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
|
||||
- Edit only the concrete files in `existingOutputPaths`; never write to a glob `resolvedOutputPath`.
|
||||
- Do not advance the build frontier: no new artifacts, no new files under glob artifacts - that is `/opsx:continue`'s job.
|
||||
- Confirm every edit with the user before writing.
|
||||
- If the request changes the change's *intent* rather than refining it, first verify whether the expanded-profile `/opsx:new` workflow is available. If it is, recommend starting fresh with `/opsx:new` (the "Update vs. Start Fresh" heuristic). If it is unavailable, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead.
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
set -uo pipefail
|
||||
|
||||
ROOT="${CLAUDE_PROJECT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}"
|
||||
PAYLOAD=$(cat)
|
||||
FILE=$(printf '%s' "$PAYLOAD" | /usr/bin/python3 -c 'import json,sys
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
except Exception:
|
||||
sys.exit(0)
|
||||
t = d.get("tool_input") or {}
|
||||
r = d.get("tool_response") or {}
|
||||
p = r.get("filePath") or t.get("file_path") or ""
|
||||
print(p)
|
||||
' 2>/dev/null)
|
||||
|
||||
case "$FILE" in
|
||||
"") exit 0 ;;
|
||||
*.py) ;;
|
||||
*) exit 0 ;;
|
||||
esac
|
||||
|
||||
case "$FILE" in
|
||||
"$ROOT"/src/*) ;;
|
||||
src/*) FILE="$ROOT/$FILE" ;;
|
||||
*) exit 0 ;;
|
||||
esac
|
||||
|
||||
[ -f "$FILE" ] || exit 0
|
||||
[ -x "$ROOT/.venv/bin/ruff" ] || exit 0
|
||||
|
||||
OUT=$(
|
||||
cd "$ROOT" || exit 0
|
||||
"$ROOT/.venv/bin/ruff" check --fix --quiet "$FILE" 2>&1
|
||||
"$ROOT/.venv/bin/ruff" format --quiet "$FILE" 2>&1
|
||||
if [ -x "$ROOT/.venv/bin/ty" ]; then
|
||||
"$ROOT/.venv/bin/ty" check --quiet "$FILE" 2>&1 | grep -v "^All checks passed" || true
|
||||
fi
|
||||
)
|
||||
|
||||
if [ -n "$OUT" ]; then
|
||||
printf 'ruff/ty по %s:\n%s\n' "${FILE#"$ROOT"/}" "$OUT" >&2
|
||||
exit 2
|
||||
fi
|
||||
exit 0
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit|NotebookEdit",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/lint-python.sh",
|
||||
"timeout": 60,
|
||||
"statusMessage": "ruff + ty по src/"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
---
|
||||
name: openspec-apply-change
|
||||
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.8.0"
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
- Optional `context`: current required project instruction input from the selected root
|
||||
- Optional `operationGuidance`: current advisory guidance for apply
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue` (if it is not installed, run `openspec status --change "<name>" --json` to see the next artifact and `openspec instructions <artifact-id> --change "<name>" --json` for how to create it)
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
Treat `context` as a required prompt-level input. Read and consider it, and
|
||||
apply relevant project facts, conventions, and constraints while implementing.
|
||||
Treat `operationGuidance` as optional additive advice. Read and consider every
|
||||
entry, and follow entries that are applicable and compatible with the built-in
|
||||
workflow.
|
||||
|
||||
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
|
||||
progress, `contextFiles`, and the built-in `instruction`. They are not
|
||||
evidence of task completion, do not replace the built-in instruction, and do
|
||||
not permit bypassing a blocked state. If context conflicts with the built-in
|
||||
instruction, an explicit user choice, or a CLI-controlled value, report the
|
||||
conflict and preserve the controlling value. If guidance is inapplicable or
|
||||
conflicts with those controlling inputs, do not follow it and explain why.
|
||||
These are prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
Do not copy `context` or `operationGuidance` verbatim into implementation
|
||||
files or planning artifacts unless the user separately asks for that content.
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! You can archive this change with `/opsx:archive`.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
- Do not use context or operation guidance as proof that a task is complete
|
||||
- Apply relevant project context; report conflicts with controlling workflow inputs
|
||||
- Consider every guidance entry; explain any inapplicable or conflicting advice
|
||||
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
|
||||
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
@@ -0,0 +1,182 @@
|
||||
---
|
||||
name: openspec-archive-change
|
||||
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.8.0"
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:archive <other>`).
|
||||
|
||||
**Load current archive inputs before the existing archive checks:**
|
||||
|
||||
After resolving the selected change and planning root, run:
|
||||
```bash
|
||||
openspec instructions archive --change "<name>" --json
|
||||
```
|
||||
Keep the same selected-root flags on this command. This lookup is advisory and
|
||||
optional: it only supplies extra prompt inputs, so it must never block archiving.
|
||||
If it exits non-zero or returns invalid JSON — for example on an older CLI that
|
||||
does not support this command yet — continue the archive workflow with no
|
||||
context and no operation guidance. Do not report an error and do not stop.
|
||||
|
||||
A successful response may omit both optional fields. Treat `context` as a
|
||||
required prompt-level input: read and consider it, and apply relevant project
|
||||
facts, conventions, and constraints. Treat `operationGuidance` as optional
|
||||
additive advice: read and consider every entry, and follow entries that are
|
||||
applicable and compatible with the built-in archive workflow.
|
||||
|
||||
Keep both fields separate from built-in steps, explicit user choices, resolved
|
||||
paths, CLI checks, and command contracts. If context conflicts with one of those
|
||||
controlling inputs, report the conflict and preserve the controlling value. If
|
||||
guidance is inapplicable or conflicts with a controlling input, do not follow it
|
||||
and explain why. Do not infer replacement paths, skipped prompts, or flags from
|
||||
either field, and do not copy their text verbatim into specs, change artifacts,
|
||||
or archive summaries unless the user separately asks for it. These are
|
||||
prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
|
||||
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
|
||||
|
||||
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
|
||||
- Display warning listing incomplete artifacts
|
||||
- Ask the user to confirm they want to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||
|
||||
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Ask the user to confirm they want to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
|
||||
delta-spec source. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
|
||||
delta specs from other artifacts.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Show a combined summary before prompting
|
||||
|
||||
**Prompt options:**
|
||||
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
Route on the answer:
|
||||
- "Cancel" — stop, do not archive
|
||||
- "Archive without syncing" or "Archive now" — proceed to archive
|
||||
- "Sync now" or "Sync anyway" — sync, then verify (below)
|
||||
- Anything else — ask again rather than archiving
|
||||
|
||||
Before a selected sync writes any main spec, run
|
||||
`openspec instructions specs --change "<name>" --json` once with the same
|
||||
selected-root flags. Require a zero exit status and valid artifact-instruction
|
||||
JSON. If the lookup fails or returns invalid JSON, report the error and stop
|
||||
before writing any main spec or moving the change. A valid response with omitted
|
||||
`rules` is the no-rules case. Apply returned `rules` only to the content and
|
||||
form of main specs produced by this merge; do not use them as archive guidance,
|
||||
change CLI behavior, or copy the rule text into any output file.
|
||||
|
||||
Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
|
||||
|
||||
Then re-run the comparison from the top of this step against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
|
||||
- ADDED requirements present
|
||||
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
|
||||
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty; a spec the sync deliberately kept and reported is also a match
|
||||
- RENAMED requirements present under the new name and absent under the old one
|
||||
|
||||
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p "<planningHome.changesDir>/archive"
|
||||
```
|
||||
|
||||
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move `changeRoot` to the archive directory
|
||||
|
||||
```bash
|
||||
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Whether specs were synced (if applicable)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">
|
||||
|
||||
<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Announce the selected change; prompt for selection when it is ambiguous
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, run the `openspec-sync-specs` workflow inline (agent-driven)
|
||||
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
|
||||
- Consider every guidance entry and explain any inapplicable or conflicting advice
|
||||
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
|
||||
- Artifact rules constrain only the specs being written and are never operation guidance
|
||||
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
|
||||
@@ -0,0 +1,308 @@
|
||||
---
|
||||
name: openspec-explore
|
||||
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.8.0"
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing. For a new change, scaffold it first as described below.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Use ASCII diagrams liberally │
|
||||
├─────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────┐ ┌────────┐ │
|
||||
│ │ State │────────▶│ State │ │
|
||||
│ │ A │ │ B │ │
|
||||
│ └────────┘ └────────┘ │
|
||||
│ │
|
||||
│ System diagrams, state machines, │
|
||||
│ data flows, architecture sketches, │
|
||||
│ dependency graphs, comparison tables │
|
||||
│ │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names, schemas, and status
|
||||
- What the user might be working on
|
||||
|
||||
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
|
||||
- `context`: project background - tech stack, conventions, constraints
|
||||
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
|
||||
|
||||
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
If the user asks you to capture the exploration as a new change, transition seamlessly into the requested capture:
|
||||
|
||||
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
|
||||
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
|
||||
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.
|
||||
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
|
||||
|
||||
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status.
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Resolve and read existing artifacts for context**
|
||||
- Run `openspec status --change "<name>" --json`.
|
||||
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
|
||||
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|----------------------------|-------------------------------------|
|
||||
| New requirement discovered | `specs/<capability-path>/spec.md` |
|
||||
| Requirement changed | `specs/<capability-path>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Handling Different Entry Points
|
||||
|
||||
**User brings a vague idea:**
|
||||
```
|
||||
User: I'm thinking about adding real-time collaboration
|
||||
|
||||
You: Real-time collab is a big space. Let me think about this...
|
||||
|
||||
COLLABORATION SPECTRUM
|
||||
════════════════════════════════════════════
|
||||
|
||||
Awareness Coordination Sync
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌────────┐ ┌────────┐ ┌────────┐
|
||||
│Presence│ │Cursors │ │ CRDT │
|
||||
│ "3 │ │ Multi │ │Conflict│
|
||||
│online" │ │ select │ │ free │
|
||||
└────────┘ └────────┘ └────────┘
|
||||
│ │ │
|
||||
trivial moderate complex
|
||||
|
||||
Where's your head at?
|
||||
```
|
||||
|
||||
**User brings a specific problem:**
|
||||
```
|
||||
User: The auth system is a mess
|
||||
|
||||
You: [reads codebase]
|
||||
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ CURRENT AUTH FLOW │
|
||||
└─────────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────┼─────────────┐
|
||||
▼ ▼ ▼
|
||||
┌─────────┐ ┌─────────┐ ┌─────────┐
|
||||
│ Google │ │ GitHub │ │ Email │
|
||||
│ OAuth │ │ OAuth │ │ Magic │
|
||||
└────┬────┘ └────┬────┘ └────┬────┘
|
||||
│ │ │
|
||||
└─────────────┼─────────────┘
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Session │
|
||||
└─────┬─────┘
|
||||
│
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Perms │
|
||||
└───────────┘
|
||||
|
||||
I see three tangles. Which one's burning?
|
||||
```
|
||||
|
||||
**User is stuck mid-implementation:**
|
||||
```
|
||||
User: /opsx:explore add-auth-system
|
||||
The OAuth integration is more complex than expected
|
||||
|
||||
You: [reads change artifacts]
|
||||
|
||||
You're on task 4: "Implement OAuth flow"
|
||||
|
||||
Let me trace what's involved...
|
||||
|
||||
[draws diagram, explores options, suggests paths]
|
||||
|
||||
Want to update the design to reflect this?
|
||||
Or add a spike task to investigate?
|
||||
```
|
||||
|
||||
**User wants to compare options:**
|
||||
```
|
||||
User: Should we use Postgres or SQLite?
|
||||
|
||||
You: Generic answer is boring. What's the context?
|
||||
|
||||
User: A CLI tool that tracks local dev environments
|
||||
|
||||
You: That changes everything.
|
||||
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ CLI TOOL DATA STORAGE │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
Key constraints:
|
||||
• No daemon running
|
||||
• Must work offline
|
||||
• Single user
|
||||
|
||||
SQLite Postgres
|
||||
Deployment embedded ✓ needs server ✗
|
||||
Offline yes ✓ no ✗
|
||||
Single file yes ✓ no ✗
|
||||
|
||||
SQLite. Not even close.
|
||||
|
||||
Unless... is there a sync component?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When it feels like things are crystallizing, you might summarize:
|
||||
|
||||
```
|
||||
## What We Figured Out
|
||||
|
||||
**The problem**: [crystallized understanding]
|
||||
|
||||
**The approach**: [if one emerged]
|
||||
|
||||
**Open questions**: [if any remain]
|
||||
|
||||
**Next steps** (if ready):
|
||||
- Create a change proposal
|
||||
- Keep exploring: just keep talking
|
||||
```
|
||||
|
||||
But this summary is optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
@@ -0,0 +1,149 @@
|
||||
---
|
||||
name: openspec-propose
|
||||
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.8.0"
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
|
||||
|
||||
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
|
||||
- proposal.md (what & why)
|
||||
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
When the user is ready to implement, they must start the apply workflow explicitly.
|
||||
|
||||
---
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Understand the request and clarify material ambiguity**
|
||||
|
||||
If no clear input is provided, ask the user (open-ended, no preset options):
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
|
||||
|
||||
2. **Determine the workflow schema**
|
||||
|
||||
Use the configured default schema unless the user explicitly requests a different workflow.
|
||||
|
||||
**Use a different schema only if the user:**
|
||||
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
|
||||
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; `schemas` does not accept `--store`. If context reports only `no_openspec_root`, run `openspec schemas --json` from the current working directory instead. Do not use this fallback for invalid or unavailable stores.
|
||||
|
||||
Otherwise, omit `--schema` to preserve the configured default.
|
||||
|
||||
3. **Create the change directory**
|
||||
|
||||
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
|
||||
|
||||
Using the configured default:
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
|
||||
Using an explicitly requested schema:
|
||||
```bash
|
||||
openspec new change "<name>" --schema "<schema-name>"
|
||||
```
|
||||
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
|
||||
|
||||
4. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
5. **Create every artifact in the required set**
|
||||
|
||||
Use a todo list to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
|
||||
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
|
||||
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
|
||||
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
|
||||
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
|
||||
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
|
||||
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
|
||||
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
|
||||
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
|
||||
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Ask the user to clarify
|
||||
- Then continue with creation
|
||||
|
||||
6. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
|
||||
- What's ready: "All artifacts needed for implementation are ready."
|
||||
- Prompt: "The artifacts are ready for review. When you are ready, run `/opsx:apply` or ask me to apply this change."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
|
||||
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
|
||||
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
|
||||
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
|
||||
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
@@ -0,0 +1,262 @@
|
||||
---
|
||||
name: openspec-sync-specs
|
||||
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.8.0"
|
||||
---
|
||||
|
||||
Sync delta specs from a change to main specs.
|
||||
|
||||
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show changes that have delta specs (under `specs/` directory).
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:sync <other>`).
|
||||
|
||||
2. **Resolve change context**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
|
||||
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
|
||||
|
||||
3. **Find delta specs**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
|
||||
only source of delta spec paths. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, report that there are no delta specs to sync,
|
||||
do not infer them from other artifacts, and stop without requesting artifact
|
||||
instructions or writing a main spec.
|
||||
|
||||
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
|
||||
A caller narrows it by naming an explicit list of complete entries from
|
||||
`existingOutputPaths` — copy those absolute values verbatim. Archive does
|
||||
this inline, and a user can too (for example, by selecting the entry ending
|
||||
in `/specs/billing/invoices/spec.md`).
|
||||
Then sync only the named paths and leave the remaining delta specs untouched:
|
||||
bulk archive excludes a delta whose implementation it could not find, and
|
||||
syncing it anyway would write a main spec the caller deliberately withheld.
|
||||
Carry that narrowed selection through step 4; never widen it back to the full
|
||||
list. If a named path is not in `existingOutputPaths`, do not sync it —
|
||||
report it and stop, rather than dropping it silently. If the named list is
|
||||
empty, report that there is nothing to sync and stop without writing a main
|
||||
spec.
|
||||
|
||||
Each delta spec file contains sections like:
|
||||
- `## ADDED Requirements` - New requirements to add
|
||||
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||
- `## REMOVED Requirements` - Requirements to remove
|
||||
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||
|
||||
If no delta specs found, inform user and stop.
|
||||
|
||||
4. **For each delta spec, apply changes to main specs**
|
||||
|
||||
Before the first main-spec write, obtain one current specs-rule snapshot:
|
||||
- If archive invoked this workflow inline and supplied a valid snapshot from
|
||||
`openspec instructions specs --change "<name>" --json`, reuse it and do not
|
||||
fetch the same instructions again.
|
||||
- Otherwise run that command once now with the same selected-root flags.
|
||||
- If the direct lookup exits non-zero or returns invalid artifact-instruction
|
||||
JSON, report the error and stop before writing any main spec. Do not treat the
|
||||
failure as an absent rule set.
|
||||
- A valid response with omitted `rules` means no artifact rules are configured
|
||||
and the existing semantic merge continues.
|
||||
|
||||
Apply returned `rules` only to the content and form of the main specs produced
|
||||
by this merge. Artifact rules are not operation guidance and cannot change
|
||||
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
|
||||
constraints without copying it verbatim into a main spec or summary.
|
||||
|
||||
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
|
||||
|
||||
a. **Read the delta spec** to understand the intended changes
|
||||
|
||||
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
|
||||
|
||||
c. **Apply changes intelligently**:
|
||||
|
||||
**ADDED Requirements:**
|
||||
- If requirement doesn't exist in main spec → add it
|
||||
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||
|
||||
**MODIFIED Requirements:**
|
||||
- Find the requirement in main spec
|
||||
- Apply the changes - this can be:
|
||||
- Adding new scenarios the main spec does not have yet
|
||||
- Modifying existing scenarios
|
||||
- Changing the requirement description
|
||||
- Preserve scenarios/content not mentioned in the delta
|
||||
|
||||
**REMOVED Requirements:**
|
||||
- Remove the entire requirement block from main spec
|
||||
- Retiring the capability. Delete the whole `spec.md` - and the directory once
|
||||
nothing else is left in it - only when ALL of these hold:
|
||||
1. removing the requirements *this run* left no requirement blocks;
|
||||
2. the rest of the spec is well-formed (it still has a `## Purpose`);
|
||||
3. the main spec was not already empty before this sync - if you removed
|
||||
nothing, change nothing;
|
||||
4. every other nonblank line in the whole file is accounted for as the
|
||||
title, Purpose, Requirements header, or a canonical requirement's
|
||||
statement, scenarios, or fenced examples;
|
||||
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
|
||||
6. the `spec.md` resolves inside the real specs root (do not follow a
|
||||
capability-directory symlink to delete an external file).
|
||||
If removing the selected requirements would leave no requirement blocks and
|
||||
any retirement condition is not satisfied, do not modify the main spec. Stop
|
||||
the sync for that capability, report the blocking condition, and tell the user
|
||||
how to resolve it. Never write or leave an empty `## Requirements` section.
|
||||
When only the marker is missing, say that too - it is the one thing the user
|
||||
can add to make the retirement go through.
|
||||
- Deleting the file also deletes its `## Purpose`; any other section blocks
|
||||
retirement. Name Purpose when you report the retirement. Include a pasteable
|
||||
`git checkout` only when the spec lived in the caller's checkout;
|
||||
otherwise give checkout-scoped recovery guidance.
|
||||
|
||||
**RENAMED Requirements:**
|
||||
- Find the FROM requirement, rename to TO
|
||||
|
||||
**`## Purpose` in the delta:**
|
||||
- The main spec already has one and it is authoritative - leave it alone
|
||||
(this is what `openspec archive` does; it warns and moves on)
|
||||
|
||||
d. **Create new main spec** if capability doesn't exist yet:
|
||||
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
|
||||
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
|
||||
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
|
||||
- Add Requirements section with the ADDED requirements
|
||||
- Follow the **Main Spec Format Reference** below
|
||||
|
||||
5. **Validate updated main specs**
|
||||
|
||||
Run `openspec validate --specs` with the same selected-root flags used earlier.
|
||||
If validation fails, report the problems and do not claim the sync succeeded.
|
||||
|
||||
6. **Show summary**
|
||||
|
||||
After applying all changes, summarize:
|
||||
- Which capabilities were updated
|
||||
- What changes were made (requirements added/modified/removed/renamed)
|
||||
- Any new main spec left with a TBD Purpose placeholder, so it gets written
|
||||
now rather than lingering
|
||||
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
|
||||
either a pasteable `git checkout` or checkout-scoped recovery guidance
|
||||
|
||||
**Delta Spec Format Reference**
|
||||
|
||||
```markdown
|
||||
## Purpose
|
||||
|
||||
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Existing Feature
|
||||
The system SHALL keep doing the existing thing, now also handling A.
|
||||
|
||||
#### Scenario: Scenario the main spec already has
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
#### Scenario: New scenario to add
|
||||
- **WHEN** user does A
|
||||
- **THEN** system does B
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: Deprecated Feature
|
||||
|
||||
## RENAMED Requirements
|
||||
|
||||
- FROM: `### Requirement: Old Name`
|
||||
- TO: `### Requirement: New Name`
|
||||
```
|
||||
|
||||
**Main Spec Format Reference**
|
||||
|
||||
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
|
||||
|
||||
```markdown
|
||||
# <capability> Specification
|
||||
|
||||
## Purpose
|
||||
Short description of what this capability does and why it exists.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
```
|
||||
|
||||
**Key Principle: Intelligent Merging**
|
||||
|
||||
Unlike programmatic merging, you merge rather than overwrite:
|
||||
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
|
||||
- Keep anything the delta does not mention, in the main spec's existing order
|
||||
- Use your judgment to merge changes sensibly
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Specs Synced: <change-name>
|
||||
|
||||
Updated main specs:
|
||||
|
||||
**<capability-1>**:
|
||||
- Added requirement: "New Feature"
|
||||
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||
|
||||
**<capability-2>**:
|
||||
- Created new spec file
|
||||
- Added requirement: "Another Feature"
|
||||
|
||||
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Read both delta and main specs before making changes
|
||||
- Preserve existing content not mentioned in delta
|
||||
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
|
||||
- If something is unclear, ask for clarification
|
||||
- Show what you're changing as you go
|
||||
- The operation should be idempotent - running twice should give same result
|
||||
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
|
||||
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
|
||||
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
|
||||
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
|
||||
- Artifact rules constrain only the specs being written and are never copied into output files
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
name: openspec-update-change
|
||||
description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Never edits code.
|
||||
allowed-tools: Bash(openspec:*)
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.8.0"
|
||||
---
|
||||
|
||||
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
`/opsx:continue` is an expanded-profile workflow and may not be installed. Before suggesting it anywhere below, verify that it is available. If it is unavailable, `openspec status --change "<name>" --json` shows the next artifact and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to create it.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one
|
||||
|
||||
When prompting, present the top 3-4 most recently modified changes as options, showing:
|
||||
- Change name
|
||||
- Schema (from `schema` field if present, otherwise "spec-driven")
|
||||
- Status (e.g., "0/5 tasks", "complete", "no tasks")
|
||||
- How recently it was modified (from `lastModified` field)
|
||||
|
||||
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:update <other>`).
|
||||
|
||||
2. **Get the change's artifacts**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand current state. The response includes:
|
||||
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
|
||||
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
|
||||
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
|
||||
|
||||
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
|
||||
|
||||
3. **Understand the request**
|
||||
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
|
||||
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
|
||||
|
||||
4. **Read and reconcile**
|
||||
- Read the artifact(s) the request touches and the change's other existing artifacts.
|
||||
- Apply the requested edit. Then check every other existing artifact against it - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
|
||||
- Note everything that is now inconsistent, missing, or contradictory.
|
||||
- Revise only files that already exist (`existingOutputPaths`). Do NOT create artifacts that don't exist yet, and do NOT invent new files under a glob artifact - note them and point the user to `/opsx:continue` to create them.
|
||||
- If the change is already coherent, say so and make no edits.
|
||||
|
||||
5. **Confirm and apply, one artifact at a time**
|
||||
- Show each proposed revision and why. Write only after the user confirms.
|
||||
- If the user rejects a revision, do not write it - leave that artifact unchanged.
|
||||
- When a substantial rewrite is needed, get that artifact's rules and template first:
|
||||
```bash
|
||||
openspec instructions "<artifact-id>" --change "<name>" --json
|
||||
```
|
||||
|
||||
6. **Point to the next step (guidance only - NEVER act on it)**
|
||||
- Artifacts still missing -> suggest `/opsx:continue` to create them.
|
||||
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/opsx:apply` to carry the delta into code.
|
||||
- Everything done and implemented -> suggest `/opsx:archive`.
|
||||
|
||||
**Output**
|
||||
|
||||
After each invocation, show:
|
||||
- Which artifacts were revised (and which proposed revisions were rejected)
|
||||
- Anything deferred to `/opsx:continue` (not-yet-created artifacts or files)
|
||||
- Where the change stands and the recommended next command
|
||||
|
||||
**Guardrails**
|
||||
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/opsx:apply`.
|
||||
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
|
||||
- Edit only the concrete files in `existingOutputPaths`; never write to a glob `resolvedOutputPath`.
|
||||
- Do not advance the build frontier: no new artifacts, no new files under glob artifacts - that is `/opsx:continue`'s job.
|
||||
- Confirm every edit with the user before writing.
|
||||
- If the request changes the change's *intent* rather than refining it, first verify whether the expanded-profile `/opsx:new` workflow is available. If it is, recommend starting fresh with `/opsx:new` (the "Update vs. Start Fresh" heuristic). If it is unavailable, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead.
|
||||
@@ -14,7 +14,33 @@ backups
|
||||
*.pfx
|
||||
*.jks
|
||||
.venv
|
||||
venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
.pytest_cache
|
||||
.ruff_cache
|
||||
.mypy_cache
|
||||
.ty_cache
|
||||
node_modules
|
||||
evidence
|
||||
openspec
|
||||
student-tests
|
||||
tests
|
||||
scripts
|
||||
examples
|
||||
contracts
|
||||
infra
|
||||
*.md
|
||||
!README.md
|
||||
Makefile
|
||||
Dockerfile*
|
||||
compose*.yaml
|
||||
.dockerignore
|
||||
.gitignore
|
||||
.DS_Store
|
||||
lab.json
|
||||
requirements-dev.txt
|
||||
.claude
|
||||
|
||||
.verification/
|
||||
|
||||
@@ -9,3 +9,57 @@ DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
S3_ENDPOINT=http://s3:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
# Solution-specific: published LB ports, replica limits, workers and pool per replica,
|
||||
# LB queue per replica, drain window before closing the listener on SIGTERM, PostgreSQL
|
||||
# limits, load generator limits (profile bench), cursor key file. API_PORT/SHORTTTL_PORT of lab2 are gone:
|
||||
# only the load balancer is published.
|
||||
LB_HTTP_PORT=8080
|
||||
LB_STATS_PORT=8404
|
||||
API_CPUS=1
|
||||
API_MEMORY=512m
|
||||
WEB_CONCURRENCY=2
|
||||
DB_POOL_MAX_SIZE=8
|
||||
API_SERVER_MAXCONN=64
|
||||
DRAIN_SECONDS=2
|
||||
PG_MAX_CONNECTIONS=200
|
||||
PG_CPUS=2
|
||||
PG_MEMORY=1g
|
||||
K6_CPUS=2
|
||||
K6_MEMORY=512m
|
||||
CURSOR_SECRET_FILE=/run/secrets/cursor_secret
|
||||
# Solution-specific for lab4: S3 client timeouts (connect + read, two attempts stay below
|
||||
# REQUEST_TIMEOUT_SECONDS=8), parallel image checks per worker, RustFS memory limit.
|
||||
S3_CONNECT_TIMEOUT_SECONDS=1
|
||||
S3_READ_TIMEOUT_SECONDS=2
|
||||
IMAGE_CHECK_CONCURRENCY=2
|
||||
S3_MEMORY=512m
|
||||
# Solution-specific for lab4 grade 4: upload bodies buffered at once per worker, grace period
|
||||
# before an abandoned pending upload is swept, sweep interval and rows per sweep pass.
|
||||
UPLOAD_CONCURRENCY=3
|
||||
UPLOAD_GRACE_SECONDS=900
|
||||
UPLOAD_SWEEP_INTERVAL_SECONDS=30
|
||||
UPLOAD_SWEEP_BATCH=100
|
||||
# Fixed glibc mmap threshold for the API: buffers above 128 KiB are returned to the system on free.
|
||||
MALLOC_MMAP_THRESHOLD_=131072
|
||||
# Minimal client transfer rate, bytes/s: every body byte moved in either direction extends the
|
||||
# request deadline by 1/rate, so slow but steady uploads and downloads outlive REQUEST_TIMEOUT_SECONDS.
|
||||
MIN_TRANSFER_RATE_BYTES=131072
|
||||
# Solution-specific for lab4 track 2: limits of the one-off reconciler (profile reconcile), its S3
|
||||
# read timeout for listing pages, optional CPU pinning of the measured services (empty = no pinning)
|
||||
# and the CPU limit of RustFS (make reconcile-cost raises it with its memory for the 100k point).
|
||||
RECONCILE_CPUS=1
|
||||
RECONCILE_MEMORY=256m
|
||||
RECONCILE_S3_READ_TIMEOUT_SECONDS=10
|
||||
RECONCILE_CPUSET=
|
||||
S3_CPUSET=
|
||||
PG_CPUSET=
|
||||
S3_CPUS=1
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
## Лабораторная 2
|
||||
## Лабораторная 4
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
name: Application
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Линт, типы и собственные тесты
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
- run: uv sync --locked --group dev
|
||||
- run: make lint VENV=.venv
|
||||
- run: make student-test VENV=.venv
|
||||
|
||||
acceptance:
|
||||
name: Стенд Compose с RustFS за HAProxy, smoke, вложения, отказ реплики, рестарт и отказы зависимостей
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
- run: uv sync --locked --group dev
|
||||
|
||||
- name: Поднять стенд из чистого clone
|
||||
run: make up
|
||||
|
||||
- name: Публичный smoke через балансировщик
|
||||
run: make test
|
||||
|
||||
- name: Вложение после остановки принявшей его реплики и при недоступном S3
|
||||
run: |
|
||||
make scenario SCENARIO=failover-upload
|
||||
make scenario SCENARIO=s3-outage
|
||||
|
||||
- name: Приватный bucket, ограниченный ключ API и повторный bootstrap
|
||||
run: make s3-check
|
||||
|
||||
- name: Негативный suite вложений, компенсация, уборка после grace, обрыв и зависание загрузки
|
||||
run: make upload-faults
|
||||
|
||||
- name: Несколько реплик на одном токене и гонка одного ключа
|
||||
run: make lb-check
|
||||
|
||||
- name: Повтор неподтверждённой записи после потерянного ответа и убитой реплики
|
||||
run: make retry-check
|
||||
|
||||
- name: Остановка реплики под запросами, затем возврат
|
||||
run: |
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
docker compose ps -a api
|
||||
make restore
|
||||
|
||||
- name: Рестарт LB, API и хранилищ с сохранением volumes
|
||||
run: make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
|
||||
- name: Отказы Valkey и PostgreSQL, гонка и rollback
|
||||
run: make test-faults
|
||||
|
||||
- name: Лимиты, порты, секреты, volumes и сети по политике
|
||||
run: make limits
|
||||
|
||||
- name: Время обнаружения отказа балансировщиком (SIGTERM, kill, pause, PostgreSQL)
|
||||
run: make detection
|
||||
|
||||
- name: Наружу опубликован только балансировщик
|
||||
run: |
|
||||
docker compose ps --format '{{.Service}} {{.Ports}}' | awk '$2 != "" && $1 != "lb" {print; bad=1} END {exit bad}'
|
||||
|
||||
- name: Процессы работают не от root
|
||||
run: |
|
||||
for id in $(docker compose ps -q); do
|
||||
docker top "$id" -eo pid,uid,comm | awk 'NR>1 && $2==0 {print; bad=1} END {exit bad}' || exit 1
|
||||
done
|
||||
|
||||
- name: Одноразовые сервисы не от root
|
||||
run: |
|
||||
for service in migrate s3-init; do
|
||||
user=$(docker inspect -f '{{.Config.User}}' "$(docker compose ps -aq "$service")")
|
||||
echo "$service: $user"
|
||||
case "${user%%:*}" in ""|0|root) exit 1 ;; esac
|
||||
done
|
||||
|
||||
- name: Корректная остановка реплик API по SIGTERM
|
||||
run: |
|
||||
start=$(date +%s)
|
||||
docker compose kill --signal SIGTERM api
|
||||
codes=$(docker wait $(docker compose ps -aq api) | sort -u)
|
||||
elapsed=$(( $(date +%s) - start ))
|
||||
echo "остановка за ${elapsed} с, коды завершения ${codes}"
|
||||
test "$elapsed" -le 10 && test "$codes" = "0"
|
||||
|
||||
- name: Журналы стенда
|
||||
if: always()
|
||||
run: docker compose logs --tail 80
|
||||
+10
@@ -30,3 +30,13 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
# Тулчейн студенческой реализации
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.ty_cache/
|
||||
|
||||
# Локальные настройки агента
|
||||
.claude/settings.local.json
|
||||
|
||||
.verification/
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
## Что это за репозиторий
|
||||
|
||||
Skeleton лабораторной 4 курса «Мессенджер под нагрузкой» (МТУСИ, 7 независимых лаб) и решение в ветке `solution/bpi2303-kostylev`. Skeleton даёт задание (`README.md`), нормативный контракт (`contracts/`) и публичные black-box проверки (`tests/`). Реализация API, Dockerfile, compose-стенд, конфигурация балансировщика и S3, миграции, хуки отказов и собственные тесты — студенческие; решение лабы 4 построено переносом решения лабы 3.
|
||||
|
||||
Лаба 4: вложения-изображения в сообщениях. Метаданные вложений живут в PostgreSQL, байты — в приватном bucket S3-совместимого хранилища **RustFS** внутри стенда, а не в БД и не на диске реплики. `POST /api/v1/chats/{chat_id}/attachments` принимает сырые байты одного PNG/JPEG (≤10 MiB, ≤40 млн пикселей, тип по содержимому) и отвечает `201 ready` только после записи объекта и фиксации метаданных; скачивание идёт только через API участникам чата. Сообщение несёт `attachment_ids`. Остаётся всё из лабы 3: HAProxy перед ≥2 репликами, `X-Instance-Id`, обязательный `Idempotency-Key`, хуки остановки реплики и рестарта стенда.
|
||||
|
||||
## Команды
|
||||
|
||||
```sh
|
||||
make check # offline: структура skeleton, JSON, локальные $ref, синтаксис Python, версия 1.4.0
|
||||
make validate # полная валидация OpenAPI 3.1: openapi-spec-validator из .venv (make install); PYTHON= — свой интерпретатор
|
||||
make install # uv sync --group dev
|
||||
make lint # ruff check + ruff format --check + ty check; обязательно перед commit
|
||||
make student-test # собственные тесты (поднимают одноразовые PostgreSQL, Valkey и RustFS в Docker)
|
||||
make student-test PYTEST_ARGS='-v -k drain' # выборка тестов с именами
|
||||
|
||||
make secrets # локальные secrets/* (включая root и API-ключи S3) и .env из .env.example
|
||||
make up # docker compose up -d --build --wait: postgres, valkey, s3 → migrate, s3-init → api ×2 → lb; затем ждёт все реплики UP в LB
|
||||
make test # публичный smoke через LB (BASE_URL по умолчанию — docker compose port lb 8080, без стенда http://localhost:8080)
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh # рестарт lb, api, postgres, valkey, s3 с сохранением volumes
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh # остановка реплики TARGET_INSTANCE_ID под запросами
|
||||
make test-faults # тесты стенда через LB (make faults-evidence → evidence/faults.txt)
|
||||
make restore # вернуть остановленные реплики и дождаться их в ротации LB
|
||||
make limits # лимиты, порты, секреты, volumes и сети всех сервисов против политики → evidence/limits.txt
|
||||
make lb-check # один токен на обеих репликах и 20 гонок одного Idempotency-Key через LB
|
||||
make retry-check # потерянный ответ (запись ждёт блокировку чата) на живой и на убитой реплике, повтор тем же ключом
|
||||
make scenario SCENARIO=failover-upload # upload → стоп обслужившей реплики → download через другую, SHA-256
|
||||
make scenario SCENARIO=s3-outage # S3 остановлен: upload/download 503, тексты работают
|
||||
make s3-check # приватный bucket вне API, ограниченные ключи API и сверки, консоль, повторный bootstrap
|
||||
make upload-faults # «4»: негативный suite через LB, компенсация, уборка после grace, обрыв и зависание тела
|
||||
make upload-memory ARGS='--out evidence/upload-memory/run1' # «4»: пик памяти реплик и LB при 10/20/40 загрузках 1 и 10 MiB
|
||||
make load-evidence # tests/load.py ×3 клиентом-контейнером в сети edge → evidence/load.txt, evidence/load/
|
||||
make overload-leftovers # после upload-memory: намерения от 503, сверка и уборка после grace → evidence/overload-leftovers.txt
|
||||
make clean-clone-evidence # блок «Запуск из чистого clone» REPORT.md в свежем клоне рядом → evidence/clean-clone.txt
|
||||
make reconcile ARGS="--apply" # трек 2: сверка PostgreSQL ↔ S3 (без ARGS — dry-run), one-off сервис reconciler
|
||||
make reconcile-demo # трек 2: внедрение ошибок, dry-run/apply/повтор, безопасность, нагрузка → evidence/reconcile/
|
||||
make reconcile-cost # трек 2: стоимость обхода 1k/10k/30k/100k × 3 (чистый стенд) → evidence/reconcile/cost/
|
||||
make down # остановка без удаления данных (с профилями bench, tools, reconcile); make reset-data — удаление volumes
|
||||
```
|
||||
|
||||
`tests/*.py` и `scripts/*.py` — только stdlib, синтаксис Python 3.9 (`make check` разбирает их системным `python3`). Проверки сами не поднимают стенд. Хуки `scripts/stop-one.sh` и `scripts/restart.sh` запускаются тестом без shell, поэтому исполняемые и с shebang. Данные не удаляются автоматически: каждый прогон smoke создаёт новых синтетических пользователей и вложения.
|
||||
|
||||
## Архитектура skeleton
|
||||
|
||||
- `lab.json` — единственный источник номера лабы (4). От него зависят `scripts/check_contract.py` (`info.version == 1.4.0`, путь `/api/v1/attachments/{attachment_id}`, `X-Instance-Id` во всех ответах) и `tests/client.py` (ветки `LAB>=4`: upload `tests/fixtures/sample.png`, сообщение с `attachment_ids`, скачивание вторым участником, `404` постороннему).
|
||||
- `tests/client.py` шлёт `Accept: application/json` на каждый запрос, включая скачивание картинки, и считает любой `30x` ошибкой: content negotiation и redirect на S3 не делаются.
|
||||
- `tests/resilience.py`: перед хуком загружается `sample.png`; после `persistence` метаданные и `/content` запрашиваются **один раз** без повторов с таймаутом 2 с, поэтому хук рестарта ждёт здоровья S3. В `failover` `TARGET_INSTANCE_ID` — реплика, обслужившая первое **сообщение**, а не upload; остановку реплики, принявшей upload, доказывает `scripts/lab4_scenarios.py failover-upload`.
|
||||
- `contracts/infrastructure.json` — роли `api` (≥2, без локального состояния), `postgres` (метаданные, persistent volume), `load_balancer`, `s3` (приватный bucket, persistent volume), опциональный `redis_or_valkey`. `compose.example.yaml` — только worksheet ролей.
|
||||
|
||||
## Ключевые правила контракта (lab4)
|
||||
|
||||
- Upload: `POST /api/v1/chats/{chat_id}/attachments?filename=…`, тело — сырые байты (не multipart), `Content-Type: image/png|image/jpeg`. Сначала `401`, затем объявленный `Content-Length` (`413`). Дедлайн запроса продлевается переданными байтами тела по `MIN_TRANSFER_RATE_BYTES` (128 KiB/s): медленный, но идущий upload и скачивание не обрываются. `>10485760` байт или `>40 000 000` пикселей — `413`; тип по содержимому не совпал, битый файл, иной `Content-Type` — `415`; `filename` пустой, пробельный, длиннее 255 code points или с `/`, `\`, NUL, управляющими символами — `400`. Object key назначает сервер. `201 Attachment` (`status=ready`, `variants=[]`, `error_code=null`, lowercase `sha256`, `size_bytes` оригинала) — только после записи в S3 и `COMMIT` метаданных. Кода `409` у upload нет.
|
||||
- `GET /api/v1/attachments/{id}` и `/content?variant=original` — только участникам чата вложения, посторонний и неизвестный id — `404`. Скачивание отдаёт исходные байты с истинным `Content-Type`, без redirect, с `X-Request-Id` и `X-Instance-Id`.
|
||||
- `Message.attachment_ids` обязателен в каждом ответе (`[]` у текстовых, в том числе в replay и истории). `CreateMessage.attachment_ids` — 0–10 уникальных UUID (иначе `400`), только вложения этого чата (иначе `404`); `text=""` допустим только с вложением. Отсутствующий `attachment_ids` и `[]` — одно тело для `Idempotency-Key`.
|
||||
- Сохраняются правила lab3 (`X-Instance-Id`, `Idempotency-Key`, LB не повторяет `POST /users`, `/chats`, upload), lab2 (`Basic` только на входе, `Bearer` дальше, `WWW-Authenticate` по пути, logout `204`, TTL) и lab1 (формат ошибки, посторонний → `404`, keyset `(created_at, id)`, время RFC 3339 с `Z`).
|
||||
|
||||
## Правила работы с репозиторием
|
||||
|
||||
- Поздние исправления ЛР3 перенесены из immutable snapshot `ba78cf6da439a4ec60fd59389583b38285b0b2b1`; диапазон от `f591fa64e525679a31c9db7f942d36c789e1a12f` и применимость evidence описаны в `evidence/forward-port.md`.
|
||||
- Только свой Compose project `mtusi2026lab4` либо `hlpipe-lab4-*` под разрешённым working_dir; HTTP 18084, остальные host-порты 24000–24999. `NO_PROXY` и `no_proxy`: localhost,127.0.0.1,::1. Чужие контейнеры не останавливать, WIP и volumes сохранять. Совместный Docker допустим; эксклюзивность только в финальном release.
|
||||
- Runner управляет этапами и агентами: реализация 3→4→5 и evidence → review/fix при major → report → нагрузка/публикация. Самостоятельных агентов, push и Telegram нет; runner/state не менять. Публикация только в разрешённой фазе в private MTUCI-Labs.
|
||||
- Исправлять критичное: major — доказанная угроза безопасности, данным, доступности или неработающий обязательный сценарий. Прочие minor остаются в findings и ограничениях REPORT и не блокируют этап. Пригодные измерения сохраняются; повторяется только затронутая или признанная непригодной серия с указанной причиной и фоном нагрузки.
|
||||
- Не менять и не ослаблять `contracts/`, `tests/`, `README.md`, `COURSE.md`, рубрику. Расхождение оформляется вопросом преподавателю.
|
||||
- Код — `src/messenger/`, миграции — `alembic/versions/NNNN_*.py`, конфигурация LB, нагрузки и S3 — `infra/`, хуки и обвязка стенда — `scripts/`, собственные тесты — `student-tests/`, обезличенные доказательства — `evidence/`.
|
||||
- PostgreSQL — SQLAlchemy 2 async с asyncpg как драйвером; ORM-модели внутри зон, Alembic принимает legacy-схему только после сверки журнала и каталога.
|
||||
- Без комментариев в коде; отступы — пробелы (`[tool.ruff.format]`); Python 3.14 без `from __future__ import annotations` и `TYPE_CHECKING`.
|
||||
- Порты реплик API и S3 наружу не публикуются: только LB. Нет `container_name`, `hostname` и общего `INSTANCE_ID` у сервиса `api`. Root-ключи S3 есть только у `s3`, `s3-init` и `s3-cli`; API получает отдельный ключ только на объекты bucket (`Get/Put/DeleteObject`), сверка — свой ключ (`ListBucket`, `Get/DeleteObject`). `s3-init` и `s3-cli` работают от uid 65534, `migrate` и `reconciler` — с `init: true`.
|
||||
- `REPORT.md`: команды из чистого clone, архитектура, таблица «критерий → команда → наблюдение → файл», таблица отказов. PASS без команды не доказательство; для отказов — какой контейнер реально остановлен (`docker ps -a`).
|
||||
- Ветка `solution/bpi2303-kostylev`, коммиты на английском, перед каждым — `make lint`. Никогда не коммитить `.env`, `secrets/`, токены, ключи S3, volumes, дампы.
|
||||
|
||||
## Уровни оценки
|
||||
|
||||
Решение заявлено на **«5»** с треком 2 «Согласованность двух хранилищ (reconciler)»; таблица доказательств — в `REPORT.md`, индекс файлов с командой и коммитом каждого — `evidence/README.md`. Доказательства снимаются на стенде из чистого состояния (`make reset-data`, `make up`); при изменении кода приложения или стенда их нужно снять заново.
|
||||
|
||||
- **3** — RustFS и приватный bucket в общем стенде, метаданные в PostgreSQL; upload `201 ready` после записи и `COMMIT`, побайтное скачивание вторым участником, `404` постороннему, `403` анонимному GET в S3; лимиты 10 MiB / 40 MP, тип по содержимому, опасные `filename`; upload → стоп обслужившей реплики → download через другую; restart с volumes; недоступный S3 → `503` при работающих текстах; минимум lab3 сохранён.
|
||||
- **4** — негативные тесты файлов без `500`; компенсация сбоя между S3 и БД под блокировкой строки и фоновая уборка намерений `pending` старше `UPLOAD_GRACE_SECONDS` (`SKIP LOCKED`, объект раньше строки); слоты загрузки на воркер, ограниченные буферы сокетов LB и API, фиксированный порог `mmap` glibc и замер ≥10 одновременных загрузок; идемпотентный bootstrap, ограниченные ключи API, закрытая консоль, проверка приватности вне API.
|
||||
- **5** — трек 2: one-off `reconciler` (`python -m messenger.attachments.entrypoints.reconcile`, по умолчанию `--dry-run`) сливает отсортированный листинг bucket и keyset-страницы `attachments` по `object_key` (O(N) по времени, O(страница) по памяти); объект без строки старше grace + skew удаляется после повторной проверки строки, готовые строки без объекта или с другими байтами уходят в карантин (миграция `0004`, `/content` → `404`) и не удаляются, `pending` старше grace удаляется (объект, затем строка), карантин снимается только после совпавшего SHA-256 объекта (и без `--deep`); удаление намерения — `audit.attachment_discarded reason=reconcile`; SQL-страниц `⌈N/страница⌉`; один проход за раз (`pg_try_advisory_lock`); повторный `--apply` — 0 действий; стоимость обхода 1k/10k/30k/100k объектов с закреплёнными CPU и отбраковкой прогонов с чужой нагрузкой (`evidence/reconcile/`).
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
FROM python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS builder
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.9.7@sha256:ba4857bf2a068e9bc0e64eed8563b065908a4cd6bfb66b531a9c424c8e25e142 /uv /usr/local/bin/uv
|
||||
|
||||
ENV UV_COMPILE_BYTECODE=1 \
|
||||
UV_LINK_MODE=copy \
|
||||
UV_PYTHON_DOWNLOADS=never \
|
||||
UV_PROJECT_ENVIRONMENT=/opt/venv
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
COPY pyproject.toml uv.lock README.md ./
|
||||
RUN uv sync --locked --no-dev --no-install-project --no-editable
|
||||
|
||||
COPY src ./src
|
||||
RUN uv sync --locked --no-dev --no-editable
|
||||
|
||||
|
||||
FROM python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS runtime
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PATH="/opt/venv/bin:$PATH" \
|
||||
HOST=0.0.0.0 \
|
||||
PORT=8080 \
|
||||
LOG_LEVEL=INFO \
|
||||
WEB_CONCURRENCY=2 \
|
||||
REQUEST_TIMEOUT_SECONDS=8 \
|
||||
DRAIN_SECONDS=2 \
|
||||
SHUTDOWN_TIMEOUT_SECONDS=6
|
||||
|
||||
RUN groupadd --system --gid 10001 messenger \
|
||||
&& useradd --system --uid 10001 --gid messenger --no-create-home --shell /usr/sbin/nologin messenger
|
||||
|
||||
COPY --from=builder --chown=root:root /opt/venv /opt/venv
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --chown=root:root alembic.ini ./
|
||||
COPY --chown=root:root alembic ./alembic
|
||||
|
||||
USER 10001:10001
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD ["python", "-c", "import urllib.request,sys;sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/live',timeout=2).status==200 else 1)"]
|
||||
|
||||
CMD ["python", "-m", "gunicorn", \
|
||||
"--config", "python:messenger.gunicorn_conf", \
|
||||
"messenger.main:create_app()"]
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
# Памятка преподавателю — лабораторная 2
|
||||
# Памятка преподавателю — лабораторная 4
|
||||
|
||||
## Что подготовлено
|
||||
|
||||
|
||||
@@ -1,17 +1,53 @@
|
||||
PYTHON ?= python3
|
||||
BASE_URL ?= http://localhost:8080
|
||||
BASE_URL ?= http://$(shell docker compose port lb 8080 2>/dev/null || echo localhost:8080)
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence
|
||||
VENV ?= .venv
|
||||
UV ?= uv
|
||||
COMPOSE ?= docker compose
|
||||
RATE ?= 100
|
||||
FROM_REV ?=
|
||||
SHIFT ?= 0
|
||||
SCRIPTS_PY = scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py \
|
||||
scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
|
||||
SCENARIO ?= failover-upload
|
||||
PSQL = $(COMPOSE) exec -T postgres psql -U messenger -d messenger -X -q
|
||||
PYTEST_ARGS ?=
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover \
|
||||
install lint format typecheck student-test \
|
||||
secrets up down reset-data migrate ps logs restore lb-check failover-evidence stack-evidence \
|
||||
persistence-evidence storage-evidence cache-evidence test-faults faults-evidence seed explain retry-check \
|
||||
limits detection failover-each rolling-update level4 \
|
||||
scenario s3-check attachments-evidence upload-faults upload-memory \
|
||||
reconcile reconcile-demo reconcile-cost load-evidence clean-clone-evidence overload-leftovers
|
||||
|
||||
.NOTPARALLEL:
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "install/lint/typecheck/student-test: студенческий тулчейн"
|
||||
@echo "secrets/up/down/migrate/ps/logs: стенд Docker Compose; reset-data: намеренное удаление volumes"
|
||||
@echo "restore: вернуть остановленные реплики; lb-check: реплики на одном токене и 20 гонок одного ключа"
|
||||
@echo "retry-check: потерянный ответ на живой и на убитой реплике, повтор тем же ключом"
|
||||
@echo "level4 = limits, lb-check, detection, failover-each, rolling-update [FROM_REV=<коммит>]; RATE=$(RATE) rps"
|
||||
@echo "scenario SCENARIO=failover-upload|s3-outage → evidence/<сценарий>.json; s3-check; attachments-evidence"
|
||||
@echo "upload-faults: негативный suite, компенсация, уборка, обрыв и зависание загрузки против стенда"
|
||||
@echo "upload-memory ARGS='--out evidence/upload-memory/runN': пик памяти реплик при 10/20/40 загрузках 1 и 10 MiB"
|
||||
@echo "load-evidence: tests/load.py ×3 клиентом-контейнером в сети edge стенда → evidence/load.txt, evidence/load/"
|
||||
@echo "overload-leftovers: после upload-memory — намерения от 503, сверка и уборка после grace → evidence/overload-leftovers.txt"
|
||||
@echo "clean-clone-evidence: блок «Запуск из чистого clone» в свежем клоне рядом → evidence/clean-clone.txt"
|
||||
@echo "reconcile ARGS='--apply --deep': сверка PostgreSQL ↔ S3 (без ARGS — dry-run); трек 2:"
|
||||
@echo "reconcile-demo: внедрение ошибок, dry-run/apply/повтор, безопасность, нагрузка → evidence/reconcile/"
|
||||
@echo "reconcile-cost: стоимость обхода 1k/10k/30k/100k объектов × 3 прогона на чистом стенде → evidence/reconcile/cost/"
|
||||
@echo "BASE_URL=$(BASE_URL) (порт lb из docker compose); failover-evidence SHIFT=1 — сдвиг round robin на вторую реплику"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
|
||||
validate: PYTHON := $(if $(wildcard $(VENV)/bin/python),$(VENV)/bin/python,$(PYTHON))
|
||||
validate:
|
||||
$(PYTHON) scripts/validate_openapi.py
|
||||
|
||||
@@ -24,3 +60,152 @@ load:
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
install:
|
||||
$(UV) sync --group dev
|
||||
|
||||
lint:
|
||||
$(VENV)/bin/ruff check src student-tests $(SCRIPTS_PY)
|
||||
$(VENV)/bin/ruff format --check src student-tests $(SCRIPTS_PY)
|
||||
$(VENV)/bin/ty check src student-tests alembic
|
||||
|
||||
format:
|
||||
$(VENV)/bin/ruff check --fix src student-tests $(SCRIPTS_PY)
|
||||
$(VENV)/bin/ruff format src student-tests $(SCRIPTS_PY)
|
||||
|
||||
typecheck:
|
||||
$(VENV)/bin/ty check src student-tests alembic
|
||||
|
||||
student-test:
|
||||
$(VENV)/bin/pytest $(PYTEST_ARGS)
|
||||
|
||||
secrets:
|
||||
sh scripts/secrets.sh
|
||||
|
||||
up: secrets
|
||||
$(COMPOSE) up -d --build --wait
|
||||
scripts/lb-wait.sh
|
||||
|
||||
down:
|
||||
$(COMPOSE) --profile bench --profile tools --profile reconcile down
|
||||
|
||||
reset-data:
|
||||
@echo "Удаляются volumes с учебными данными стенда"
|
||||
$(COMPOSE) --profile bench --profile tools --profile reconcile down -v --remove-orphans
|
||||
|
||||
migrate:
|
||||
$(COMPOSE) run --rm migrate
|
||||
|
||||
ps:
|
||||
$(COMPOSE) ps
|
||||
|
||||
logs:
|
||||
$(COMPOSE) logs --tail 200
|
||||
|
||||
restore:
|
||||
scripts/restore.sh
|
||||
|
||||
lb-check:
|
||||
$(PYTHON) scripts/probe.py check --rounds 20 --out evidence/lb-check.json
|
||||
|
||||
retry-check:
|
||||
$(PYTHON) scripts/probe.py retry --out evidence/retry.json
|
||||
|
||||
limits:
|
||||
$(PYTHON) scripts/limits.py --out evidence/limits.txt
|
||||
|
||||
detection:
|
||||
rm -rf evidence/detection
|
||||
for run in 1 2 3; do sh scripts/detection.sh evidence/detection/run$$run || exit 1; done
|
||||
|
||||
failover-each:
|
||||
RATE=$(RATE) sh scripts/failover-each.sh evidence/failover-each
|
||||
|
||||
rolling-update:
|
||||
ifneq ($(FROM_REV),)
|
||||
git archive "$(FROM_REV)" | docker build -q -t "mtusi-messenger:$(FROM_REV)" -
|
||||
API_IMAGE="mtusi-messenger:$(FROM_REV)" $(COMPOSE) up -d --no-deps --force-recreate --wait api
|
||||
scripts/lb-wait.sh
|
||||
endif
|
||||
$(COMPOSE) build -q api
|
||||
RATE=$(RATE) $(PYTHON) scripts/probe.py load --expect replace --duration 90 \
|
||||
--out evidence/rolling$(if $(FROM_REV),-from-$(FROM_REV)) \
|
||||
-- scripts/rolling-update.sh
|
||||
|
||||
level4: limits lb-check detection failover-each rolling-update
|
||||
|
||||
scenario:
|
||||
$(PYTHON) scripts/lab4_scenarios.py $(SCENARIO) --base-url "$(BASE_URL)" --restore --output evidence/$(SCENARIO).json
|
||||
scripts/lb-wait.sh
|
||||
|
||||
s3-check:
|
||||
sh scripts/s3-check.sh > evidence/s3-security.txt; status=$$?; cat evidence/s3-security.txt; exit $$status
|
||||
|
||||
attachments-evidence:
|
||||
sh scripts/evidence-attachments.sh
|
||||
|
||||
upload-faults:
|
||||
{ echo "date: $$(date -u +%FT%TZ) commit: $$(git rev-parse --short HEAD) BASE_URL=$(BASE_URL)"; \
|
||||
BASE_URL="$(BASE_URL)" $(VENV)/bin/pytest -m stack -v -s --no-header --tb=short \
|
||||
-p no:cacheprovider student-tests/stack/test_attachment_faults.py; } > evidence/upload-faults.txt; \
|
||||
status=$$?; cat evidence/upload-faults.txt; exit $$status
|
||||
|
||||
upload-memory:
|
||||
$(PYTHON) scripts/upload_memory.py --base-url "$(BASE_URL)" $(ARGS)
|
||||
|
||||
load-evidence:
|
||||
sh scripts/load-evidence.sh
|
||||
|
||||
overload-leftovers:
|
||||
sh scripts/overload-leftovers.sh
|
||||
|
||||
clean-clone-evidence:
|
||||
sh scripts/clean-clone.sh
|
||||
|
||||
reconcile:
|
||||
$(COMPOSE) run --rm --no-deps reconciler $(ARGS)
|
||||
|
||||
reconcile-demo:
|
||||
$(PYTHON) scripts/reconcile_track.py demo --base-url "$(BASE_URL)" $(ARGS)
|
||||
|
||||
reconcile-cost:
|
||||
$(PYTHON) scripts/reconcile_track.py cost $(ARGS)
|
||||
|
||||
failover-evidence:
|
||||
sh scripts/failover-evidence.sh "$(BASE_URL)" "$(SHIFT)"
|
||||
|
||||
stack-evidence:
|
||||
sh scripts/evidence-stack.sh
|
||||
|
||||
persistence-evidence:
|
||||
sh scripts/persistence-evidence.sh "$(BASE_URL)" > evidence/persistence.txt
|
||||
cat evidence/persistence.txt
|
||||
|
||||
storage-evidence:
|
||||
sh scripts/evidence-storage.sh
|
||||
|
||||
cache-evidence:
|
||||
sh scripts/evidence-cache.sh > evidence/cache.txt
|
||||
cat evidence/cache.txt
|
||||
|
||||
test-faults:
|
||||
BASE_URL="$(BASE_URL)" $(VENV)/bin/pytest -m stack -v -s student-tests/stack
|
||||
|
||||
faults-evidence:
|
||||
{ echo "date: $$(date -u +%FT%TZ) commit: $$(git rev-parse --short HEAD)"; echo "\$$ make test-faults"; \
|
||||
$(MAKE) --no-print-directory test-faults 2>&1; } | sed 's#$(CURDIR)#<repo>#g' > evidence/faults.txt
|
||||
cat evidence/faults.txt
|
||||
grep -qE '^=+ [0-9]+ passed in' evidence/faults.txt
|
||||
|
||||
seed:
|
||||
$(PSQL) -f - < scripts/sql/seed-history.sql
|
||||
|
||||
explain: seed
|
||||
{ echo "date: $$(date -u +%FT%TZ) commit: $$(git rev-parse --short HEAD)"; \
|
||||
echo "\$$ make explain # scripts/sql/explain-history.sql"; \
|
||||
$(PSQL) -f - < scripts/sql/explain-history.sql; } > evidence/explain-history.txt
|
||||
cat evidence/explain-history.txt
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Лабораторная 2. PostgreSQL, сессии и Redis/Valkey
|
||||
# Лабораторная 4. S3-хранилище и вложения
|
||||
|
||||
Перенести состояние в постоянное хранилище и связать запросы с аутентифицированным пользователем. Подтверждённые сообщения и действующие сессии переживают перезапуск.
|
||||
Разделить метаданные и бинарное содержимое, добавить изображения в сообщения и сохранить доступ к ним при переключении API-реплики.
|
||||
|
||||
Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен.
|
||||
|
||||
@@ -8,41 +8,41 @@
|
||||
|
||||
## Откуда начинаем
|
||||
|
||||
Перенесите собственный минимум lab1. Изменения API: password при регистрации, Basic для создания сессии, Bearer вместо X-User-Id для бизнес-запросов.
|
||||
Перенесите минимум lab3. Дополняются поля сообщения и endpoint вложений; прежние текстовые POST остаются валидными.
|
||||
|
||||
**Архитектура:** Клиент → API → PostgreSQL; на 4 появляется Redis ИЛИ Valkey для сессий/кэша.
|
||||
**Архитектура:** Клиент → LB → API × 2+ → PostgreSQL (метаданные) + приватное S3-хранилище (байты).
|
||||
|
||||
## Что сделать
|
||||
|
||||
1. Опишите таблицы, ограничения, индексы и транзакционные границы до написания запросов. Добавьте версионируемые миграции.
|
||||
2. Перенесите пользователей, чаты, членство и сообщения в PostgreSQL. Не используйте SQLite как замену PostgreSQL в принимаемом стенде.
|
||||
3. Реализуйте регистрацию с password KDF, вход через Basic, opaque Bearer-сессию, expiry и logout. Действующие сессии тоже должны сохраняться.
|
||||
4. Подготовьте единый локальный запуск API и БД (Compose рекомендуется уже здесь), подключите именованные volumes.
|
||||
5. Пройдите smoke и тест полного перезапуска. На 4 добавьте Redis/Valkey с конкретной ролью и повторите эксперимент отказа.
|
||||
1. Выберите один S3-совместимый сервер: MinIO, SeaweedFS или RustFS. Закрепите проверенную версию образа и опишите создание приватного bucket.
|
||||
2. Спроектируйте Attachment и связь с чатом/сообщением. S3 object key назначает сервер, filename используется только для отображения.
|
||||
3. Реализуйте синхронный binary upload PNG/JPEG с ограничениями, сохранение метаданных и авторизованный download через API.
|
||||
4. Включите S3 и persistent volumes в общий Compose/Swarm. Проверьте, что другая API-реплика скачивает файл после остановки загрузившей.
|
||||
5. Проверьте недоступность S3, чужой чат и restart всего стенда.
|
||||
|
||||
## Оценка «3»: работающий минимум
|
||||
|
||||
- Минимум lab1 сохранён с объявленным переходом на новую аутентификацию. Все обязательные данные и ещё действующие сессии переживают рестарт API и хранилищ без удаления volumes.
|
||||
- PostgreSQL содержит пользователей, чаты, участников и сообщения. Есть первичные/внешние ключи, уникальность username и миграции с нуля. Составная операция создания чата выполняется атомарно.
|
||||
- Basic применяется только на POST /auth/sessions, остальные endpoint требуют Bearer. Есть срок жизни сессии и отзыв; X-User-Id не даёт доступ. Пароли уже хешируются password KDF.
|
||||
- make test и make test-persistence ACTION_SCRIPT=scripts/restart.sh проходят. Миграции повторно запускаются без дублирования данных. Secrets/volumes не попадают в Git.
|
||||
- Все обязательные возможности lab3 сохранены. S3-сервер находится в общем стенде; метаданные вложений живут в PostgreSQL, байты — в приватном bucket, не в БД или локальном каталоге API.
|
||||
- POST вложения возвращает 201 ready после сохранения; оригинал скачивается побайтно. Message с attachment_ids читается участниками чата. Публичный smoke проверяет checksum и отсутствие доступа у постороннего.
|
||||
- Принимаются реальные PNG/JPEG ≤10 MiB и ≤40 млн пикселей; MIME проверяется по содержимому, опасные filename отклоняются, лимиты применяются до неограниченного чтения/декодирования.
|
||||
- Upload → остановка обслужившей API-реплики → download через другую возвращает тот же файл. Restart с сохранением volumes сохраняет метаданные и оригинал.
|
||||
|
||||
## Оценка «4»: уровень стажёра/джуна
|
||||
|
||||
Весь уровень 3 **и все** пункты ниже:
|
||||
|
||||
- Redis ИЛИ Valkey реально используется для сессий с TTL либо осмысленного кэша. Опишите источник истины, политику expiry и инвалидации. Если это единственное хранилище сессий, включите persistence, выдерживающее проверяемый рестарт; один TTL не сохраняет данные.
|
||||
- Используются параметризованные запросы/безопасный ORM, ограниченный connection pool и таймауты. Проверены гонка регистрации одинакового username и rollback составной операции.
|
||||
- Индекс истории обоснован запросом и EXPLAIN (ANALYZE, BUFFERS) на ≥10 000 сообщениях; пагинация не использует полный scan всей истории на каждую страницу.
|
||||
- Есть автоматическая проверка expiry при коротком SESSION_TTL_SECONDS, logout, неверного пароля и недоступности Redis/БД. При потере сервиса приложение возвращает ограниченную ошибку/корректно обходит кэш, не принимает запрос от анонимного пользователя как доверенный.
|
||||
- Тесты покрывают слишком большой файл, повреждённое изображение, подмену MIME, чужое attachment_id и привязку файла другого чата. Пользовательская ошибка не превращается в 500.
|
||||
- Прерывание загрузки и отказ между записью S3/БД не оставляют вечных неучтённых объектов: есть документированный механизм компенсации/сверки/очистки с безопасным grace period.
|
||||
- Лимиты/таймауты и потоковая обработка не позволяют одной загрузке занять неограниченную RAM. Проведён эксперимент ≥10 одновременных загрузок с измерением пика памяти.
|
||||
- Bucket bootstrap идемпотентен; API использует отдельные S3 credentials с ограниченными правами. Административная консоль не открыта в общей сети. Есть проверка private bucket вне API.
|
||||
|
||||
## Оценка «5»: исследование и доказанный результат
|
||||
|
||||
Весь уровень 4 **и один законченный трек на выбор**. Приведите гипотезу, повторяемую методику, результаты и ограничения.
|
||||
|
||||
**Трек 1. Согласованность кэша.** Покажите на конкурентном сценарии stale read или cache stampede, реализуйте защиту и измерьте число SQL-запросов/latency до и после. Докажите read-after-write из контракта и восстановление после рестарта кэша; одной установки Redis недостаточно.
|
||||
**Трек 1. Прямой upload.** Добавьте отдельный безопасный presigned-upload flow: короткая подпись, уникальный ключ, проверка принадлежности, размера/checksum при complete, обработка незавершённой загрузки. Сохраните обязательный proxy endpoint. Сравните трафик и RAM API при ≥2 размерах файлов, покажите негативные сценарии.
|
||||
|
||||
**Трек 2. План запроса и восстановление.** Исследуйте ≥100 000 сообщений с неравномерными размерами чатов, сравните ≥2 индекса/запроса и стоимость записи. Сделайте backup → восстановление в новое хранилище → сверку количества и выбранных сообщений. Обсудите время восстановления и границы потери данных.
|
||||
**Трек 2. Согласованность двух хранилищ.** Разработайте повторяемый reconciler для orphan/missing объектов и метаданных. Внедрите ошибки на обеих сторонах, покажите обнаружение и безопасное исправление с dry-run/повторным запуском. Докажите, что свежие и используемые вложения не удаляются; измерьте стоимость обхода.
|
||||
|
||||
## Как начать и проверить
|
||||
|
||||
@@ -78,28 +78,28 @@ Smoke не выставляет оценку автоматически. Про
|
||||
|
||||
## Сценарий защиты
|
||||
|
||||
1. Применить миграции к пустому volume, создать пользователей, войти, отправить сообщение.
|
||||
2. Запустить persistence-сценарий: он держит токен только в памяти тестового процесса; action script перезапускает API и все используемые хранилища, сохраняя volumes.
|
||||
3. После готовности тот же токен читает те же данные; после logout — 401. Повторить с отдельным коротким TTL для проверки expiry.
|
||||
4. Для 4: показать роль Redis/Valkey, план SQL и ошибку зависимости. Для 5: выполнить выбранный эксперимент.
|
||||
1. Загрузить fixture, отправить message с attachment_ids, скачать как второй участник и сравнить SHA-256.
|
||||
2. С третьим пользователем получить 404 для метаданных и bytes; direct unauthenticated S3 GET не отдаёт объект.
|
||||
3. Выполнить persistence и failover: общий тест начиная с lab4 сохраняет и повторно читает оригинал через API.
|
||||
4. Показать, что на API нет обязательного локального файла оригинала. Для 4/5 — отказы и эксперименты.
|
||||
|
||||
## Что должно быть в PR
|
||||
|
||||
Исходники, Dockerfile, миграции, compose.yaml либо эквивалентный воспроизводимый запуск, scripts/restart.sh, собственные тесты и отчёт.
|
||||
Дополненный стенд, настройка bucket/политики, миграции Attachment, тесты файлов, описание согласованности БД/S3 и результаты.
|
||||
|
||||
Заполните `REPORT.md` и [шаблон PR](.github/pull_request_template.md), укажите целевую оценку/трек. Не меняйте обязательный контракт и публичные tests ради зелёного результата. Сохраняйте возможности предыдущих лабораторных в пределах [объявленных переходов](COURSE.md).
|
||||
|
||||
## Вопросы на защите
|
||||
|
||||
- Что подтверждает COMMIT и какие гарантии зависят от настройки durability?
|
||||
- Где хранятся сессии и что будет после flush/restart Redis?
|
||||
- Чем аутентификация отличается от доступа к конкретному чату?
|
||||
- Почему hash пароля и быстрый checksum имеют разные задачи?
|
||||
- Почему файл в Docker volume одной API-реплики не равен объектному хранилищу?
|
||||
- Когда можно честно вернуть 201?
|
||||
- Что произойдёт, если S3 PUT прошёл, а COMMIT в PostgreSQL — нет?
|
||||
- Почему случайный object key и приватный bucket не заменяют ACL приложения?
|
||||
|
||||
## Первичные материалы
|
||||
|
||||
- [PostgreSQL transactions](https://www.postgresql.org/docs/current/tutorial-transactions.html)
|
||||
- [PostgreSQL EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html)
|
||||
- [Valkey persistence](https://valkey.io/topics/persistence/)
|
||||
- [Redis persistence](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/)
|
||||
- [Basic authentication](https://www.rfc-editor.org/info/rfc7617/)
|
||||
- [S3 object uploads](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)
|
||||
- [Presigned URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html)
|
||||
- [MinIO](https://github.com/minio/minio)
|
||||
- [SeaweedFS](https://github.com/seaweedfs/seaweedfs)
|
||||
- [RustFS](https://docs.rustfs.com/)
|
||||
|
||||
@@ -1,37 +1,670 @@
|
||||
# Отчёт — лабораторная 2
|
||||
# Отчёт — лабораторная 4
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Костылев Артём, БПИ2303
|
||||
- Целевая оценка: **5**; трек «5» — **трек 2 «Согласованность двух хранилищ (reconciler)»**
|
||||
- Состояние на 2026-11-06: перенос SQLAlchemy/Alembic выполнен из immutable snapshot
|
||||
`f591fa64e525679a31c9db7f942d36c789e1a12f`, код переноса —
|
||||
`8e4532f6f5c05d902b6e2c310f54320d95585904`. Текущие проверки уровня 3:
|
||||
[новая матрица](evidence/sqlalchemy-2026-11-06/grade3/NOTES.md), полный SHA каждой команды в raw-выводе.
|
||||
Новые проверки уровня4: [протокол и память](evidence/sqlalchemy-2026-11-06/grade4/NOTES.md).
|
||||
Штатные3слота: 840/840 успешных загрузок в18точках штатной конфигурации (36точек вместе с контролем), максимум API448MiB,
|
||||
OOM 0; clean-clone cf41f7c прошёл и сохранил volumes. Штатная уборка сняла все 30 pending,
|
||||
после неё 1669 строк/объектов без расхождений. Трек2:13 проверок корректности PASS и27 замеров до100k;
|
||||
[методика и ограничения](evidence/sqlalchemy-2026-11-06/track5/NOTES.md);
|
||||
итоговую редакцию отчёта подготовит этап после ревью.
|
||||
**Таблицы и численные результаты ниже, ссылающиеся на evidence вне sqlalchemy-2026-11-06,
|
||||
относятся к исторической реализации asyncpg и не подтверждают текущий SQLAlchemy-код.**
|
||||
Финально: check/validate/lint, 410 собственных тестов и smoke PASS;
|
||||
[все свои стенды остановлены, volumes сохранены](evidence/sqlalchemy-2026-11-06/track5/shutdown-state.txt).
|
||||
Публикация в этой фазе не выполняется.
|
||||
- Использованные источники, библиотеки и помощь ИИ: FastAPI, gunicorn + uvicorn-worker, dishka, pydantic,
|
||||
structlog, SQLAlchemy 2 async, Alembic, asyncpg (драйвер), argon2-cffi, redis-py, aiobotocore/botocore, Pillow, pytest, ruff, ty (версии —
|
||||
`evidence/environment.txt` и `uv.lock`); RustFS 1.0 и `rc` (IAM-политики, anonymous access, lifecycle), Amazon S3
|
||||
User Guide (PutObject, GetObject, ListObjectsV2, политики bucket), botocore Config (таймауты, повторы, checksum),
|
||||
Pillow (`Image.open`, `verify`, `draft`, защита от decompression bomb), спецификация PNG (чанки и CRC),
|
||||
HAProxy 3.2 Configuration Manual, документация Docker Compose (secrets, `depends_on`, профили). Решение
|
||||
перенесено из моей лабы 3; в текущем этапе использован Codex. Код, стенд и отказы проверены прогонами,
|
||||
перечисленными ниже.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Параметры текущего стенда: `COMPOSE_PROJECT_NAME=hlpipe-lab4-<имя>`, `LB_HTTP_PORT=18084`,
|
||||
`LB_STATS_PORT=24844`, `NO_PROXY=localhost,127.0.0.1,::1`. Скрипт `scripts/clean-clone.sh`
|
||||
создаёт отдельный clone внутри `.verification/`, останавливает только его project и сохраняет volumes.
|
||||
Старый протокол ниже описывает прежний прогон; команды удаления данных больше не выполняются.
|
||||
|
||||
Требуются Docker с Compose v2, `make` и системный Python 3.9+ (только для публичных проверок и сценариев).
|
||||
Образы сторонних сервисов закреплены версией и digest, API собирается из исходников.
|
||||
|
||||
```sh
|
||||
git clone <repo> mtusi2026lab4 && cd mtusi2026lab4 && git checkout solution/bpi2303-kostylev
|
||||
|
||||
make secrets # secrets/*: пароли PostgreSQL и Valkey, DATABASE_URL, CACHE_URL, ключ курсора,
|
||||
# root-ключи S3 и отдельный ключ API S3; .env из .env.example (существующее не перезаписывает)
|
||||
docker compose --env-file .env config --quiet
|
||||
make up # docker compose up -d --build --wait: postgres, valkey, s3 → migrate, s3-init → api ×2 → lb;
|
||||
# затем ждёт обе реплики UP в статистике LB
|
||||
make test # публичный smoke через балансировщик (BASE_URL — порт lb из docker compose, иначе :8080)
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
make restore # вернуть остановленную реплику и дождаться её в ротации LB
|
||||
make scenario SCENARIO=failover-upload # upload → стоп принявшей реплики → download через другую, SHA-256
|
||||
make scenario SCENARIO=s3-outage # S3 остановлен: upload/download 503, тексты и метаданные работают
|
||||
make s3-check # приватность bucket вне API, права ключа API, консоль, повторный bootstrap
|
||||
make reconcile # трек 2: сверка PostgreSQL ↔ S3, по умолчанию dry-run; ARGS="--apply --deep" — исправить
|
||||
make migrate # повторный запуск миграций: up to date
|
||||
|
||||
make down # безопасная остановка: контейнеры удаляются, volumes pgdata, valkeydata, s3data остаются
|
||||
```
|
||||
|
||||
Каждая строка этого блока выполнена в свежем clone (`evidence/clean-clone.txt`; клон назван `mtusi2026lab4-clean`,
|
||||
чтобы у него были свои compose-проект и volumes): `make up` за 11 с (образ из кэша слоёв), все сервисы
|
||||
`healthy`, `migrate` применил `0001`–`0004`, `s3-init` вывел `bucket=messenger-attachments anonymous=private
|
||||
policy=messenger-api`, smoke, persistence и failover `PASS`, повторный `migrate` — `up to date`, после `make down`
|
||||
три volume на месте, после `make reset-data` — ни одного. Отступление от инструкции одно: на машине параллельно
|
||||
работали стенды других лаб, поэтому в `.env` стояли `LB_HTTP_PORT=18084`, `LB_STATS_PORT=24084` (цели `make` берут
|
||||
`BASE_URL` из `docker compose port lb 8080`). Наружу публикуются только порты `lb` на `127.0.0.1`.
|
||||
|
||||
Длинные сценарии уровней «4» и трека запускаются на поднятом стенде так же, без ручных шагов:
|
||||
|
||||
```sh
|
||||
make install # .venv для pytest-сценариев (uv sync --group dev)
|
||||
make upload-faults # «4»: негативный suite через LB, компенсация, уборка после grace, обрыв и зависание тела
|
||||
series="evidence/run-$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
make upload-memory ARGS="--out $series/memory/run1"
|
||||
make reconcile-demo ARGS="--out $series/demo"
|
||||
make reconcile-cost ARGS="--out $series/measurements"
|
||||
EVIDENCE_DIR="$series" make load-evidence
|
||||
```
|
||||
|
||||
Каждой серии нужен новый каталог: повтор в существующий отклоняется до нагрузки.
|
||||
Demo и cost выполняются последовательно на отдельных новых Compose projects; существующие данные не удаляются.
|
||||
Для трёх повторов памяти используются `run1`, `run2`, `run3`.
|
||||
|
||||
`make up` ждёт `healthy` всех долгоживущих сервисов и успешного завершения одноразовых `migrate` (миграции под
|
||||
advisory lock) и `s3-init` (bucket, анонимный доступ `private`, политика и пользователь API, lifecycle). Оба
|
||||
повторяемы: повторный `make up`, `make migrate` или `restart.sh` проходит без изменений состояния.
|
||||
|
||||
Собственные проверки и тулчейн:
|
||||
|
||||
```sh
|
||||
make install # uv sync --group dev (Python 3.14 и зависимости из uv.lock)
|
||||
make lint # ruff check + ruff format --check (src, student-tests, scripts/*.py стенда) + ty check
|
||||
make student-test # собственные тесты; поднимают одноразовые PostgreSQL, Valkey и RustFS того же образа в Docker
|
||||
make check # офлайн-проверка skeleton
|
||||
make validate # полная валидация OpenAPI: openapi-spec-validator 0.7.2 из .venv
|
||||
make stack-evidence # сервисы, порты, hostname ↔ X-Instance-Id, лимиты, сети, версии
|
||||
make limits # лимиты CPU/RAM, порты, секреты, volumes и сети всех сервисов против политики
|
||||
make storage-evidence # \d+ схемы, повтор миграций, префикс KDF, правила ignore
|
||||
make attachments-evidence # где лежат байты: \d attachments, bucket, сверка вне API, read_only реплик
|
||||
make failover-evidence # docker inspect реплик до/после, make test-failover, логи остановленной, restore
|
||||
make persistence-evidence # persistence-тест + StartedAt всех контейнеров до и после
|
||||
make lb-check # один токен на обеих репликах; 20 гонок одного Idempotency-Key через LB
|
||||
make retry-check # потерянный ответ на живой и на убитой реплике, повтор тем же ключом
|
||||
make faults-evidence # все проверки стенда под маркером stack (лабы 2–3 и уровень «4»)
|
||||
```
|
||||
|
||||
**Версии и стенд:** Python 3.14.7 в образе `python:3.14-slim-trixie@sha256:51dafde8…`,
|
||||
`rustfs/rustfs:1.0.4@sha256:ed9210d6…`, `rustfs/rc:v0.1.36@sha256:ab024bfe…`,
|
||||
`haproxy:3.2.26-alpine@sha256:58938405…`, `postgres:17.11-alpine@sha256:266d3c25…`,
|
||||
`valkey/valkey:8.1.11-alpine@sha256:2602ace2…`, uv 0.9.7 по digest; aiobotocore 3.10.0 (botocore 1.43.117),
|
||||
Pillow 13.0.0; Docker 28.3.2, Compose 2.38.2. Машина — Apple M4 Max, 16 CPU, 48 ГБ RAM, macOS 15.1; VM Docker
|
||||
Desktop — 16 CPU, 7.65 ГиБ (`evidence/environment.txt`).
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
┌── api (gunicorn, 2 × UvicornWorker) ─┐ SQLAlchemy async engine ┌▶ postgres (метаданные, pgdata)
|
||||
клиент ──HTTP──▶ lb (HAProxy 3.2) ────┤ X-Instance-Id = hostname ├────────────────────┼▶ valkey (кэш сессий, AOF)
|
||||
127.0.0.1:8080 round robin, └── api (gunicorn, 2 × UvicornWorker) ─┘ aiobotocore └▶ s3: RustFS (байты, s3data)
|
||||
httpchk /health/ready migrate (образ api, один раз) ──▶ postgres
|
||||
s3-init (rc, один раз) ──▶ s3: bucket private, пользователь и политика API
|
||||
сеть edge ─────── lb ─────── сеть backend (internal): lb, api, migrate, postgres, valkey, s3, s3-init, s3-cli
|
||||
```
|
||||
|
||||
**Источник истины.** PostgreSQL — для всего, что знает API о вложении: владелец, чат, отображаемое имя, тип по
|
||||
содержимому, размер, SHA-256, размеры в пикселях, ключ объекта, статус и связи с сообщениями. S3 (RustFS) — только
|
||||
для байтов оригинала под ключом `attachments/<uuid7>`, который назначает сервер. Реплика API не хранит файлов:
|
||||
корень только для чтения, `tmpfs /tmp` нужен лишь heartbeat gunicorn, volume у `api` нет
|
||||
(`evidence/storage-layout.txt`).
|
||||
|
||||
**Перенесено из лабы 3 без изменения поведения:** зоны `identity` и `messaging`, порты и адаптеры, UoW, шина
|
||||
событий с журналом аудита, ASGI-конвейер, Basic → Bearer, Argon2id, сессии в PostgreSQL с кэшем в Valkey,
|
||||
подписанный курсор, порядок истории под блокировкой строки чата, `X-Instance-Id`, обязательный
|
||||
`Idempotency-Key` в одной транзакции с сообщением, HAProxy с проверкой готовности и политикой повторов, окно
|
||||
вывода реплики из ротации по `SIGTERM`, хуки `stop-one.sh`, `restore.sh`, `lb-wait.sh`, проверки уровня «4» лабы 3
|
||||
(на итоговом коде прогнаны `make limits`, `lb-check`, `retry-check`, `test-faults`). Перенос шёл двумя шагами:
|
||||
решение лабы 3 на `61c0c28` (`bf8e4e3`), затем её исправления после ревью (`e927afd`): отправка сообщения одной
|
||||
командой SQL под блокировкой строки чата (улучшение трека 1 лабы 3), `503` в формате контракта для запроса,
|
||||
прерванного остановкой, готовность за портом `Readiness`, счёт реально полученных байтов тела в конвейере.
|
||||
**Изменено:** новая зона `attachments`; `attachment_ids` в сообщениях — ссылки пишутся той же командой SQL, что и
|
||||
сообщение; миграции `0003` и `0004`; лимит тела в конвейере зависит от маршрута; S3-сервисы и `reconciler` в
|
||||
`compose.yaml`; `restart.sh` перезапускает и S3; политика `scripts/limits.py` знает S3-сервисы.
|
||||
|
||||
**Зона `attachments` и её связь с `messaging`.** Зона владеет агрегатом `Attachment` (`pending` → `ready`),
|
||||
значением `Filename`, своими ошибками, событием `AttachmentStored`, командой `UploadAttachment`, запросами
|
||||
`GetAttachment`/`OpenAttachment`, портами `ObjectStorage`, `ImageInspector`, `ChatMembership` и HTTP-слоем. Ей нужен
|
||||
один ответ от `messaging` — «входит ли пользователь в чат»; его даёт адаптер `MessagingMembership` над
|
||||
`ChatDirectory`, который собирает `main.py`. Зоны не импортируют друг друга, SQL каждой зоны читает только свои
|
||||
таблицы (оба правила проверяет тест `test_bounded_contexts.py`). Целостность между зонами держат внешние
|
||||
ключи: `attachments (chat_id, owner_id) → chat_members` и `message_attachments (attachment_id, chat_id) →
|
||||
attachments (id, chat_id) ON DELETE RESTRICT` — сообщение может сослаться только на вложение своего чата,
|
||||
нарушение превращается в `404` и откатывает всю отправку вместе с ключом идемпотентности, а используемое
|
||||
вложение нельзя удалить.
|
||||
|
||||
**Схема** (`alembic/versions/0003_attachments.py`, `evidence/schema.txt`): `attachments` без `bytea`, `CHECK` на тип, размер
|
||||
1..10485760, формат SHA-256, статус; `object_key text COLLATE "C" UNIQUE` (байтовый порядок, как у листинга S3);
|
||||
частичный индекс `(created_at) WHERE status = 'pending'`; `message_attachments` с PK `(message_id, position)`,
|
||||
`UNIQUE (message_id, attachment_id)` и индексом по `attachment_id`. `messages_text_check` ослаблен до `≤ 4000`:
|
||||
пустой текст с вложением легален, пустой без вложений по-прежнему отсекает домен (`400`). История и повтор
|
||||
читают `attachment_ids` подзапросом по PK `message_attachments`, без N+1 запросов. Отсутствующий
|
||||
`attachment_ids` и `[]` дают один отпечаток тела для `Idempotency-Key`, другой порядок — `409`. Миграция `0004` (трек 2)
|
||||
аддитивно добавляет `quarantine_reason` (`missing`, `size_mismatch`, `sha_mismatch`) и `quarantined_at`, обе NULL или
|
||||
обе заданы.
|
||||
|
||||
**Upload: где применяется каждый лимит.** Тело читается потоком, FastAPI его не разбирает.
|
||||
|
||||
1. `401` — guard конвейера: он читает только заголовок `Authorization` и сессию, тело не трогает;
|
||||
2. объявленный `Content-Length` > лимита маршрута → `413` в конвейере, тело не читается (лимит 10 MiB только у
|
||||
маршрута upload, у JSON остаётся 1 MiB); конвейер считает и реально полученные байты тела против того же лимита;
|
||||
3. членство в чате → `404` (раньше любых проверок содержимого);
|
||||
4. `filename` после percent-decode: 1–255 code points, не пробельный, без `/`, `\` и символов категории `Cc`
|
||||
(NUL, `\x01`, `\x7f`, перевод строки…) → иначе `400`; используется только для отображения;
|
||||
5. `Content-Type` без параметров и регистра ∈ {`image/png`, `image/jpeg`} → иначе `415`;
|
||||
6. слот загрузки: не больше `UPLOAD_CONCURRENCY=3` тел в памяти воркера, остальные ждут, не читая тело (uvicorn
|
||||
приостанавливает чтение сокета после 64 KiB), ожидание ограничено таймаутом запроса;
|
||||
7. поток копится со счётчиком и инкрементальным SHA-256; байт `MAX_UPLOAD_BYTES + 1` → `413`, дальше не читаем
|
||||
(так закрыт и chunked без `Content-Length`); обрыв клиента посреди тела → `400` в журнале, не `500`;
|
||||
8. проверка изображения в потоке под семафором (`IMAGE_CHECK_CONCURRENCY=2` на воркер): `Image.open` только
|
||||
PNG/JPEG читает заголовок; формат ≠ заявленному → `415` (подмена MIME); `width × height > MAX_IMAGE_PIXELS` →
|
||||
`413` до декодирования (decompression bomb 100 000 × 100 000 весом 300 байт отклоняется по заголовку); PNG —
|
||||
`verify()` (все чанки, CRC, `IEND`, без распаковки пикселей), JPEG — `draft` в 1/8 + `load()` (полное
|
||||
декодирование потока, ≈1/64 памяти); ошибка → `415`;
|
||||
9. запись (ниже); буфер тела освобождается до перевода в `ready`.
|
||||
|
||||
**Порядок записи PostgreSQL ↔ S3.** `INSERT attachments (status='pending')` и `COMMIT` → `PutObject` →
|
||||
`UPDATE … SET status='ready'` и `COMMIT` → `201`. Намерение фиксируется до `PUT`, поэтому у любого объекта под
|
||||
`attachments/` есть строка с тем же ключом; `pending` не видно ни в метаданных, ни в скачивании, а сослаться на него
|
||||
нельзя — id отдаётся только в `201`.
|
||||
|
||||
| Сбой | Что остаётся | Ответ клиенту |
|
||||
| --- | --- | --- |
|
||||
| обрыв клиента, `413`, `415`, `400`, `404` | ничего: строка пишется только после чтения и проверки | ошибка или обрыв |
|
||||
| `INSERT pending` | ничего | `503` |
|
||||
| `PutObject` (S3 недоступен, таймаут) | невидимая строка `pending`, объект возможен (отложенная запись) | `503`; уборка после grace |
|
||||
| `UPDATE ready` отклонён | компенсация сразу: объект и строка удалены | `503` |
|
||||
| процесс убит между `PUT` и `COMMIT` | невидимая строка `pending` и объект | обрыв (`502` от LB); уборка после grace |
|
||||
| после `COMMIT ready` | готовое вложение | `201` |
|
||||
|
||||
**Компенсация и уборка (уровень «4»).** Инвариант: пока объект под `attachments/` существует, существует и строка с
|
||||
его ключом; строка-намерение удаляется только после объекта.
|
||||
|
||||
- *Компенсация.* Если `UPDATE … SET status='ready'` не зафиксирован, обработчик в новой транзакции берёт строку
|
||||
`SELECT … FOR UPDATE`: `ready` (фиксация на самом деле прошла) — не трогает; `pending` — `DeleteObject`, затем
|
||||
`DELETE … AND status='pending'`, `COMMIT`; строки нет — удаляет объект. Блокировка держится на время одного
|
||||
`DeleteObject` (≤ 6 с < `idle_in_transaction_session_timeout` 10 с) и не даёт задержавшемуся `UPDATE ready`
|
||||
проскочить между удалением объекта и строки. `UPDATE ready`, не нашедший строки (намерение уже убрано), даёт
|
||||
`503` и удаление объекта, а не `201`. Сбой самого `PUT` и отмена по таймауту сразу не компенсируются: исход
|
||||
`PUT` неизвестен, объект может появиться позже.
|
||||
- *Уборка.* В каждом воркере `UploadSweeper` раз в `UPLOAD_SWEEP_INTERVAL_SECONDS=30` выбирает по одной строке
|
||||
`WHERE status='pending' AND created_at < now − UPLOAD_GRACE_SECONDS ORDER BY created_at LIMIT 1 FOR UPDATE SKIP
|
||||
LOCKED` (частичный индекс `attachments_pending_idx`), удаляет объект, затем строку, до `UPLOAD_SWEEP_BATCH=100` за
|
||||
проход; `SKIP LOCKED` делит работу между 4 воркерами стенда, ошибка S3 откладывает строку до следующего прохода.
|
||||
Каждое удаление — событие `audit.attachment_discarded` с причиной `compensation` или `abandoned`.
|
||||
- *Grace period* `UPLOAD_GRACE_SECONDS=900` (минимум 60 в настройках): жизнь загрузки от `INSERT pending` до
|
||||
`UPDATE ready` ограничена таймаутом запроса 8 с, отложенный `PUT` — таймаутами S3 6 с; запас больше 50 раз,
|
||||
включая расхождение часов реплик одного хоста. Готовые строки и вложения в сообщениях не выбираются условием
|
||||
`status='pending'`, а `message_attachments` ссылается на них с `ON DELETE RESTRICT`.
|
||||
- *Незавершённый multipart* (сервер им не пользуется) удаляет lifecycle-правило bucket через сутки.
|
||||
|
||||
**Сверка хранилищ (трек 2).** Одноразовый сервис `reconciler` (образ API, профиль `reconcile`, ключ API S3)
|
||||
сливает отсортированный листинг bucket и keyset-страницы `attachments` по `object_key` и находит то, что уборка
|
||||
уровня «4» не видит: объект без строки, готовую строку без объекта или с другими байтами. По умолчанию только
|
||||
отчёт; `--apply` удаляет старые объекты без строки и брошенные намерения, а готовые строки с расхождением не
|
||||
удаляет, а помещает в карантин (миграция `0004`), `/content` такого вложения отвечает `404`. Подробно — раздел
|
||||
трека ниже.
|
||||
|
||||
Платформа: откат транзакции раньше стирал все события команды, а шина не публиковала их при исключении — журнал
|
||||
терял удаления из компенсации и уборки. Теперь откат убирает только события своей транзакции.
|
||||
|
||||
**Скачивание.** Строка `ready` по PK → членство → `GetObject` **до** отправки заголовков (пропавший объект → `404` с
|
||||
событием `attachment.object_missing` в журнале, недоступный S3 → `503`) → `StreamingResponse` кусками 64 KiB с
|
||||
`Content-Type` из метаданных, `Content-Length` из S3, `X-Content-Type-Options: nosniff`, `Cache-Control: private,
|
||||
no-store`; `Accept` не учитывается, redirect нет, `X-Request-Id`/`X-Instance-Id` ставит конвейер. `variant` — только
|
||||
`original`, иное → `400`.
|
||||
|
||||
**Клиент S3.** Один клиент aiobotocore на воркер (scope `APP` dishka): path-style, SigV4, регион `S3_REGION`,
|
||||
`connect_timeout=1`, `read_timeout=2`, 2 попытки, checksum `when_required`. Обработчик botocore, добавлявший
|
||||
`Expect: 100-continue` к телу `PutObject`, снят: aiohttp ждал `100 Continue`, RustFS за прокси портов его не
|
||||
присылал, и запись висела до read timeout — это нашёл тест адаптера против настоящего RustFS. Ошибки соединения,
|
||||
таймауты и `5xx` → `503 unavailable`; ключи S3 в журнал и ответы не попадают.
|
||||
|
||||
**Готовность.** `/health/ready` от S3 не зависит. Если бы зависела, при падении S3 балансировщик вывел бы все
|
||||
реплики, отказали бы и тексты, а ответы LB не несут `X-Instance-Id`. Сейчас upload и скачивание получают `503` от
|
||||
приложения: в новой серии upload 0,828–5,039 с, download 0,510–1,397 с
|
||||
(граница проверки 6 с). Тексты и метаданные работают
|
||||
(`evidence/sqlalchemy-2026-11-06/grade3/s3-outage-{1,2,3}.json`).
|
||||
|
||||
**Память загрузок (уровень «4»).** Пик памяти держат три настройки по всей цепочке, найденные замером (ниже):
|
||||
слоты загрузки на воркер; буферы сокетов — HAProxy `tune.rcvbuf/sndbuf.client/server 65536`, у `api`
|
||||
`net.ipv4.tcp_rmem`/`tcp_wmem` с максимумом 256 KiB (иначе ядро растит буфер до 6 MiB на соединение, и ожидающие
|
||||
тела копятся в памяти контейнера LB); `MALLOC_MMAP_THRESHOLD_=131072` у `api` (иначе glibc после первого
|
||||
освобождения поднимает порог `mmap` до 32 MiB и держит освобождённые тела в куче). Буферы сокетов нашёл первый прогон
|
||||
замера, ещё без них: при 3 слотах и 40 загрузках по 10 MiB память сокетов HAProxy выросла до ≈ 110 MB, и LB с
|
||||
лимитом 128 MiB убил OOM (описано в коммите `a774a2f`; сырых данных того прогона в `evidence/` нет). Влияние порога
|
||||
`mmap` измерено отдельно (`evidence/upload-memory/mmap-32m/`).
|
||||
|
||||
**Цепочка таймаутов:** клиент smoke/resilience 10/2 с; LB `timeout server` 10 с > `REQUEST_TIMEOUT_SECONDS` 8 с >
|
||||
худшая операция S3 2 × (1 + 2) = 6 с и ожидание соединения PostgreSQL + оператор 1 + 2 с. LB не повторяет upload:
|
||||
`disable-l7-retry` снят только для `GET` и `POST …/messages` с ключом, повтор отказа соединения безопасен (запрос
|
||||
не ушёл). Дедлайн запроса в конвейере продлевается переданными байтами тела запроса и ответа: `min(now, start +
|
||||
moved / MIN_TRANSFER_RATE_BYTES) + 8 с`, по умолчанию 128 KiB/s (схема `mod_reqtimeout` с потолком). Медленная, но
|
||||
идущая передача не обрывается: upload 10 MiB может идти до 80 + 8 с. Зависшее или ползущее медленнее порога тело
|
||||
обрывается через 8 с плюс кредит уже переданных байтов (1 KiB даёт 8 мс). После последнего байта тела на обработку
|
||||
остаётся не больше 8 с. `timeout server`/`timeout client` HAProxy — таймауты простоя одной стороны, поэтому длинная
|
||||
идущая передача через LB не обрывается. Это проверено тестом стенда: 3 MiB вверх и вниз дольше 8 с.
|
||||
|
||||
**Роли и сервисы** (`compose.yaml`; сети `edge` и `backend` с `internal: true`):
|
||||
|
||||
| Роль | Сервис | Версия / digest | Health / readiness | Volume | Сеть / порт | Credentials |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| load_balancer | `lb` | `haproxy:3.2.26-alpine@sha256:58938405…`, uid 99, `read_only`, буферы сокетов 64 KiB | `/healthz` :8404; реплики — `GET /health/ready` | нет | `edge` + `backend`; `127.0.0.1:${LB_HTTP_PORT:-8080}`, `127.0.0.1:${LB_STATS_PORT:-8404}` | нет |
|
||||
| api ×`API_REPLICAS` | `api` | сборка из `Dockerfile`, uid 10001, `read_only` + `tmpfs /tmp`, `tcp_rmem`/`tcp_wmem` ≤ 256 KiB | `GET /health/ready` (PostgreSQL) | нет | `backend`, без портов | `database_url`, `cache_url`, `cursor_secret`, `s3_access_key_id`, `s3_secret_access_key` через `*_FILE` |
|
||||
| postgres (метаданные) | `postgres` | `postgres:17.11-alpine@sha256:266d3c25…`, uid 70 | `pg_isready` | `pgdata` | `backend` | `postgres_password` через `POSTGRES_PASSWORD_FILE` |
|
||||
| s3 | `s3` | `rustfs/rustfs:1.0.4@sha256:ed9210d6…`, uid 10001, `read_only`, `cap_drop: ALL`, консоль выключена | `curl /health/ready` | `s3data:/data` | `backend`, :9000 без публикации | root: `s3_root_user`, `s3_root_password` через `RUSTFS_*_FILE` |
|
||||
| bootstrap S3 | `s3-init` | `rustfs/rc:v0.1.36@sha256:ab024bfe…`, uid 65534, `read_only` | код выхода 0 | нет (`infra/s3` только для чтения) | `backend` | root-ключи, ключи API и сверки (создаёт пользователей) |
|
||||
| операторский CLI (профиль `tools`) | `s3-cli` | тот же `rc`, uid 65534 | нет | нет | `backend` | aliases `root`, `api`, `reconciler`, `anon` |
|
||||
| сессии (кэш) | `valkey` | `valkey/valkey:8.1.11-alpine@sha256:2602ace2…`, uid 999 | `valkey-cli ping` | `valkeydata` (AOF) | `backend` | `valkey.conf` |
|
||||
| bootstrap схемы | `migrate` | образ api, uid 10001, `init: true`, `restart: "no"` | код выхода 0 | нет | `backend` | `database_url` |
|
||||
| сверка PostgreSQL ↔ S3 (профиль `reconcile`) | `reconciler` | образ api, uid 10001, `init: true`, `read_only`, `entrypoint` — модуль сверки | код выхода 0 / 1 | нет | `backend` | `database_url`, `s3_reconciler_access_key_id`, `s3_reconciler_secret_access_key` через `S3_*_FILE` (свой ключ, не root и не ключ API) |
|
||||
| нагрузка (профиль `bench`) | `k6` | `grafana/k6:2.3.0@sha256:2dd4756e…` | нет | нет | `edge` | нет |
|
||||
|
||||
Приватный bucket создаёт `infra/s3/init.sh`: `rc bucket create --ignore-existing`, `rc bucket anonymous set private`,
|
||||
политика `messenger-api` из `infra/s3/api-policy.json` (только `GetObject`, `PutObject`, `DeleteObject` на
|
||||
`messenger-attachments/*`) и пользователь API, политика `messenger-reconciler` из `infra/s3/reconciler-policy.json`
|
||||
(`ListBucket` на bucket, `GetObject`, `DeleteObject` на объекты) и пользователь сверки — оба с ключами из
|
||||
`secrets/`. Дальше идёт lifecycle «незавершённый multipart старше суток удаляется» (он работает на стороне сервера,
|
||||
ключам multipart-действия не нужны), самопроверка анонимной политики и привязки обеих политик. Реплики API
|
||||
листинга bucket не делают и права на него не имеют, листинг есть только у ключа сверки. Root-ключи есть только у
|
||||
`s3`, `s3-init` и `s3-cli` (`evidence/storage-layout.txt`, `evidence/limits.txt`).
|
||||
MinIO не выбран: `minio/minio` удалён с Docker Hub, quay отдаёт 401, проект архивирован; SeaweedFS работает от
|
||||
root и не читает ключи из файлов. Лимиты: lb 1/128m, api 1/512m на реплику, s3 1/512m, s3-init и s3-cli
|
||||
0.5/64m, migrate 0.5/256m, reconciler 1/256m, postgres 2/1g, valkey 0.5/128m.
|
||||
|
||||
**Соответствие `.env.example` реальной конфигурации:**
|
||||
|
||||
| `.env.example` | В решении | Комментарий |
|
||||
| --- | --- | --- |
|
||||
| `APP_HOST`, `APP_PORT` | `HOST`, `PORT` | заданы в образе (`0.0.0.0:8080`); снаружи — порт LB |
|
||||
| `APP_ENV` | не используется | режимов окружения нет |
|
||||
| `SESSION_TTL_SECONDS`, `IDEMPOTENCY_TTL_SECONDS` | те же | 3600 и 86 400 |
|
||||
| `DATABASE_URL_FILE`, `CACHE_URL_FILE` | те же | любой параметр читается из `<ИМЯ>_FILE` |
|
||||
| `SESSION_STORE=postgres` | фиксировано | PostgreSQL — источник истины сессий, Valkey — кэш |
|
||||
| `API_REPLICAS` | `deploy.replicas: ${API_REPLICAS:-2}` | число реплик `api` |
|
||||
| `S3_ENDPOINT`, `S3_REGION`, `S3_BUCKET` | те же у `api`, `s3-init`, `s3-cli`; `RUSTFS_REGION` у `s3` | `http://s3:9000`, `us-east-1`, `messenger-attachments` |
|
||||
| `S3_ACCESS_KEY_ID_FILE`, `S3_SECRET_ACCESS_KEY_FILE` | те же | ключ API, не root |
|
||||
| `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` | те же | 10 485 760 и 40 000 000; больше контракта задать нельзя (валидация настроек) |
|
||||
| — | `S3_CONNECT_TIMEOUT_SECONDS`, `S3_READ_TIMEOUT_SECONDS` | 1 и 2 с; две попытки укладываются в 8 с запроса |
|
||||
| — | `IMAGE_CHECK_CONCURRENCY`, `S3_MEMORY` | параллельные проверки изображений на воркер; лимит памяти RustFS |
|
||||
| — | `UPLOAD_CONCURRENCY`, `UPLOAD_GRACE_SECONDS`, `UPLOAD_SWEEP_INTERVAL_SECONDS`, `UPLOAD_SWEEP_BATCH` | 3 тела на воркер; 900 с; 30 с; 100 строк за проход (уровень «4») |
|
||||
| — | `MALLOC_MMAP_THRESHOLD_` | 131 072: тела больше 128 KiB возвращаются системе при освобождении (уровень «4») |
|
||||
| — | `MIN_TRANSFER_RATE_BYTES` | 131 072 B/s: каждый переданный байт тела продлевает дедлайн запроса на 1/скорость |
|
||||
| — | `RECONCILE_CPUS`, `RECONCILE_MEMORY`, `RECONCILE_S3_READ_TIMEOUT_SECONDS` | 1, 256m, 10 с: лимиты сервиса сверки и таймаут чтения страницы листинга (трек 2) |
|
||||
| — | `S3_CPUS`, `S3_CPUSET`, `PG_CPUSET`, `RECONCILE_CPUSET` | 1 CPU у RustFS; пусто — без закрепления; `make reconcile-cost` задаёт 2 CPU / 3 GiB RustFS и отдельные ядра на время замеров (трек 2) |
|
||||
| — | `LB_HTTP_PORT`, `LB_STATS_PORT`, `API_CPUS`, `API_MEMORY`, `WEB_CONCURRENCY`, `DB_POOL_MAX_SIZE`, `API_SERVER_MAXCONN`, `DRAIN_SECONDS`, `PG_*`, `K6_*`, `CURSOR_SECRET_FILE` | как в лабе 3 |
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Таблица ниже — историческая серия asyncpg. Актуальные результаты: `evidence/sqlalchemy-2026-11-06/grade3/NOTES.md`
|
||||
и `grade4/NOTES.md`; результаты трека добавляются после его отдельного цикла. Файлы старых серий сохранены.
|
||||
|
||||
Уровни «3» и «4» сняты одной серией на стенде из чистого состояния (`make reset-data`, `make up`) на `81dd816`; порядок
|
||||
серии — в `evidence/README.md`. Трек 2 — на `5c3c238` и `b191623`, проверка уровней после трека — на `8cb5a66`.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Публичный smoke | `make test` | `PASS: lab4 public API scenario` (upload fixture → `201 ready`, сообщение `text=""` с `attachment_ids`, скачивание bob побайтно с `image/png`, eve `404` на метаданные и `/content`, весь минимум lab2–lab3) | `evidence/smoke.txt` |
|
||||
| Запуск из чистого clone | блок «Запуск из чистого clone» дословно в каталоге `mtusi2026lab4-clean` | `valid`; `make up` за 11 с: все сервисы `healthy`, `migrate` (`0001`–`0004`) и `s3-init` `Exited (0)`, обе реплики `UP` в LB; smoke, persistence и failover (первая запись через 2,95 с, 128 записей, 0 ошибок) — `PASS`; `failover-upload` и `s3-outage` — `ok`; 23 проверки S3 — `PASS`; сверка: 5 объектов, 6 строк, расхождений нет, одно свежее намерение от `s3-outage`; повтор `migrate` — `up to date`; после `make down` 3 volume, после `make reset-data` — 0 | `evidence/clean-clone.txt` |
|
||||
| `make check` / `make validate` | `make check`; `make validate` (`.venv` с `openapi-spec-validator` 0.7.2) | `PASS: offline skeleton structure…`; `PASS: full OpenAPI 3.1 and JSON Schema validation`; `git diff upstream/main` контракта, публичных тестов и задания пуст | `evidence/contract-checks.txt` |
|
||||
| Собственные тесты и линтер | `make lint`; `make student-test PYTEST_ARGS=-v` | ruff, формат, ty — `All checks passed!`; `342 passed` по именам (17 проверок стенда под маркером `stack` — отдельно, `faults.txt`) | `evidence/student-tests.txt` |
|
||||
| **3.1** S3 в общем стенде; метаданные в PostgreSQL, байты в приватном bucket, не в БД и не на API | `make attachments-evidence` (`ps`, `\d attachments`, `bytea` по схеме, листинг bucket, `docker inspect`); `make limits` | `s3` healthy без портов; `bytea` во всей схеме — только `sessions.token_hash` и `idempotency_keys.fingerprint`, строка `attachments` ≤ 264 B; 16 строк `ready` (и одна невидимая `pending` от `s3-outage`) и 16 объектов `attachments/<uuid>`; у реплик `ro=true`, только `tmpfs /tmp` и bind секретов; данные S3 — `volume:mtusi2026lab4_s3data:/data`; root-ключи S3 только у `s3`, `s3-init`, `s3-cli` | `evidence/storage-layout.txt`, `evidence/limits.txt` |
|
||||
| **3.2** `201 ready` только после записи объекта и `COMMIT`; побайтное скачивание вторым участником, SHA-256 | smoke; `make student-test` (`test_storage_failure_leaves_nothing_visible`, `test_member_uploads_and_another_member_downloads`); сверка вне API | S3 отказал при записи → `503`, строка `pending`, вложения не видно; sha256 и размер последней строки `ready` в PostgreSQL равны sha256 и размеру объекта, прочитанного `rc` из bucket (`99ea7533…`, 111 817) | `evidence/smoke.txt`, `evidence/student-tests.txt`, `evidence/storage-layout.txt` |
|
||||
| **3.3** Message с `attachment_ids` читается участниками; посторонний `404`; анонимный GET в S3 — `403` | smoke; `make student-test` (`test_message_attachments.py`, `test_attachments.py`); `make s3-check` | eve `404` на метаданные и `/content`; вложение другого чата и неизвестное → `404`, 11 и дубли → `400`, посторонний с 11 → `404`; одно вложение в нескольких сообщениях, порядок сохраняется; прямой HTTP GET объекта из отдельного контейнера → `403`, анонимные Head/List/Put → deny, политика `private` | `evidence/smoke.txt`, `evidence/student-tests.txt`, `evidence/s3-security.txt` |
|
||||
| **3.4** PNG/JPEG ≤10 MiB и ≤40 MP; MIME по содержимому; опасные `filename`; лимиты до неограниченного чтения/декодирования | `make student-test` (`test_attachments.py`, `test_attachments_domain.py`); `make upload-faults` | ровно 10 485 760 B → `201`, +1 B с `Content-Length` и chunked → `413` без строки; 8000×5000 → `201`, 8001×5000 и 100 000×100 000 → `413` по заголовку; JPEG/GIF/WebP/текст как PNG, PNG как JPEG, обрезанные PNG/JPEG, пустое тело, `application/octet-stream`, без `Content-Type` → `415`; `../a.png`, `a/b.png`, `a\b.png`, `%00`, `%01`, `%7F`, пустое, пробельное, 256 символов, без параметра → `400`; кириллица и 255 символов → `201`; те же случаи через LB — в 4.1 | `evidence/student-tests.txt`, `evidence/upload-faults.txt` |
|
||||
| **3.5** Upload → остановка обслужившей реплики → download через другую | `make scenario SCENARIO=failover-upload` | upload принят `899a952a5a21`, хук остановил её за 2,72 с, скачивание через `0cc3ee358e59` через 2,73 с от старта хука, SHA-256 равен, реплика возвращена | `evidence/failover-upload.json` |
|
||||
| **3.5** Остановка каждой реплики под записью (публичный хук) | `make failover-evidence`, затем `make failover-evidence SHIFT=1` | `899a952a5a21`: первая запись через 2,89 с, 129 записей, 0 ошибок; `0cc3ee358e59`: 2,88 с, 128, 0; target в `exited`, сосед `running`; в журнале target — сигнал, `service.draining` (2 с), readiness `503`, выход; вложение после отказа читается bob; `PASS: failover …`; после `restore` обе `running` | `evidence/failover-899a952a5a21.txt`, `evidence/failover-0cc3ee358e59.txt` |
|
||||
| **3.6** Restart с сохранением volumes сохраняет метаданные и оригинал | `make persistence-evidence` | `PASS: persistence …` (после хука один `GET` метаданных и один `/content` без повторов совпали); `StartedAt` у `lb`, обеих `api`, `postgres`, `valkey`, `s3`, `migrate`, `s3-init` новее, ID контейнеров те же | `evidence/persistence.txt` |
|
||||
| **3.7** Недоступность S3: ограниченная ошибка, тексты работают, политика readiness | `make scenario SCENARIO=s3-outage` | при остановленном `s3`: upload `503` за 2,23 с, `/content` `503` за 1,99 с, метаданные `200`, текст `201`, `/health/ready` `200`; S3 снова healthy за 5,8 с, файл скачивается с тем же SHA-256 | `evidence/s3-outage.json` |
|
||||
| **3.8** Закреплённая версия образа S3 и создание приватного bucket | `compose.yaml`, `infra/s3/init.sh`; `make up`; `make s3-check` | все образы по digest; `s3-init` пишет `bucket=messenger-attachments anonymous=private policy=messenger-api lifecycle=abort-incomplete-uploads`; 23/23 проверки `PASS`, включая двойной повторный bootstrap без изменений | `evidence/environment.txt`, `evidence/clean-clone.txt`, `evidence/s3-security.txt` |
|
||||
| **3.9** Перенос lab3: ≥2 реплики, одна точка входа, порты только у LB, схема и миграции, KDF, общая идемпотентность, секреты вне Git | `make stack-evidence`, `make limits`, `make storage-evidence`, `make lb-check`, `make retry-check` | 2 `api` без портов, `container_name` 0, LB видит `api1/api2 UP L7OK 200`, `X-Instance-Id` чередуется; политика лимитов, портов, секретов и сетей — `PASS`; миграции `0001`–`0004`, повтор `up to date` без изменения счётчиков (66 пользователей, 288 сообщений, 17 вложений); Argon2id у всех 66, хеши токенов по 32 B; один токен на обеих репликах — 20 + 20; 20 раундов × 8 параллельных POST одним ключом — 160 × `201`, по одной копии; потерянный ответ на живой и на убитой реплике — повтор `201` с тем же сообщением, одна копия; `git ls-files secrets .env` пуст | `evidence/stack.txt`, `evidence/limits.txt`, `evidence/schema.txt`, `evidence/migrations.txt`, `evidence/kdf.txt`, `evidence/secrets.txt`, `evidence/lb-check.json`, `evidence/retry.json` |
|
||||
| **4.1** Тесты: слишком большой файл, повреждённое изображение, подмена MIME, чужое `attachment_id`, вложение другого чата; пользовательская ошибка не даёт `500` | `make student-test` (`test_attachments.py`, `test_message_attachments.py`, `test_upload_consistency.py`); `make upload-faults` (`test_user_errors_never_become_500` через LB против PostgreSQL и RustFS) | `342 passed`; на стенде 36 ошибочных запросов: 16 × `400` (опасные и пустые `filename`, 11 и повторяющиеся `attachment_ids`, невалидный UUID, пустой текст без вложений, `variant=thumbnail`), 6 × `404` (upload, метаданные, `/content` и ссылка постороннего, вложение другого чата, неизвестное вложение), 4 × `413` (10 MiB + 1 с `Content-Length` — ответ до первого байта тела, chunked, бомба 100 000 × 100 000, 8001 × 5000), 10 × `415` (обрезанные PNG и JPEG, JPEG/GIF/WebP/текст как PNG, PNG как JPEG, пустое тело, чужой и отсутствующий `Content-Type`); тело ошибки по схеме, `request_id` равен заголовку; в журнале реплик за исторический прогон 53 ответа, из них `5xx` — 0; строк вложений в чате ровно 2 — по числу `201`; обрыв клиента посреди тела — `400`, не `500` | `evidence/student-tests.txt`, `evidence/upload-faults.txt` |
|
||||
| **4.2** Прерывание загрузки и отказ между записью S3 и БД не оставляют вечных неучтённых объектов: компенсация и уборка с grace period | `make upload-faults` (триггеры PostgreSQL на время теста, `docker kill -s KILL` реплики); `make student-test` (`test_upload_consistency.py`) | отказ `COMMIT` после `PUT` → `503`, сразу нет ни строки, ни объекта (`HEAD` 404), в журнале `audit.attachment_discarded reason=compensation`; реплика убита между `PUT` и `COMMIT` (обе по очереди, клиент получил `502` от LB) → остались `pending` и объект (`HEAD` 200); намерение, сдвинутое за grace, уборка удалила вместе с объектом через 24,7 с, свежее осталось (`pending`, `HEAD` 200) и ушло через 1,0 с после сдвига; готовое вложение в сообщении со сдвинутым `created_at` скачивается с тем же SHA-256; обрыв после 256 KiB из 5 MiB → `400` в журнале, намерение не создавалось; зависшее тело → `503` за 8,01 с, ничего не записано. API-тесты: снятое во время `PUT` намерение → `503` и удалённый объект, сбой `PUT` оставляет `pending` до конца grace, два параллельных прохода делят 5 намерений ровно, следующий проход удаляет 0 | `evidence/upload-faults.txt`, `evidence/student-tests.txt` |
|
||||
| **4.3** Лимиты, таймауты и потоковая обработка не дают одной загрузке занять неограниченную RAM; ≥10 одновременных загрузок с пиком памяти | `make upload-memory` трижды (`scripts/upload_memory.py --out evidence/upload-memory/runN`): слоты 64 и 3 × 1 и 10 MiB × 10, 20, 40 одновременных, по 2 загрузки на клиента, реплики и LB пересоздаются перед каждой точкой; отдельно порог `mmap` 32 MiB | при 3 слотах медиана пика реплики 297 / 321 / 334 MiB для 10 / 20 / 40 одновременных загрузок по 10 MiB, максимум трёх прогонов 345 MiB (простой 112–122, лимит 512), `oom_kill` 0, пик LB ≤ 31 MiB; без лимита слотов те же загрузки — 288 / 428 / 512 MiB, при 40 упор в лимит cgroup во всех трёх прогонах и 27 и 34 × `503` в двух из них; при 3 слотах и 40 клиентах p95 4,6–7,6 с, в одном прогоне 7 из 80 не уложились в таймаут 8 с (`503`); 1 MiB при любой настройке — 173–213 MiB; порог `mmap` 32 MiB — +12…35 MiB; таймауты: зависшее тело — `503` за 8,01 с (4.2), S3 — 2 × (1 + 2) с, LB `timeout server` 10 с | `evidence/upload-memory/run{1,2,3}/summary.txt` и JSON точек, `evidence/upload-memory/mmap-32m/` |
|
||||
| **4.4** Идемпотентный bootstrap; отдельные ключи API с ограниченными правами; консоль не открыта; приватность bucket вне API | `make s3-check` | 23/23 `PASS`: у `s3` нет host-портов, консоль :9001 не отвечает ни внутри контейнера, ни из отдельного контейнера сети стенда (`connection refused`); `s3-init` ещё дважды — код 0, снимок IAM и bucket не изменился; ключ API: Put/Head/Get/List/Delete объектов — разрешены, CreateBucket, DeleteBucket, публичная политика, импорт lifecycle, `admin user list`, запись и листинг чужого bucket — deny; анонимные Head/List/Put — deny, прямой HTTP GET объекта из отдельного контейнера — `403`, анонимная политика `private` | `evidence/s3-security.txt` |
|
||||
| Проверки стенда лаб 2–3 и «4» на итоговом коде | `make faults-evidence` (`pytest -m stack`) | `17 passed`: гонка регистрации, откат чата с неизвестным участником, одинаковый `Basic`-вызов, logout, Valkey остановлен (токен `200`, выход `503`), рестарт и `FLUSHALL` Valkey, PostgreSQL остановлен (`503` за ≤ 0,015 с и восстановление), рестарт API и всего стенда, срок сессии после рестарта, 5 сценариев вложений | `evidence/faults.txt` |
|
||||
| **5 (трек 2)** Повторяемый reconciler: обнаружение каждого класса в dry-run | `make reconcile-demo` (внедрение `scripts/reconcile-inject.sh` на обеих сторонах, `--dry-run --deep`) | найдено ровно внедрённое: `orphan_stale` 3, `missing` 3, `size_mismatch` 3, `sha_mismatch` 3, `pending_stale` 6, свежих 2 + 2; объекты (24), строки (27) и классы независимой проверки до и после dry-run те же | `evidence/reconcile/dry-run.json`, `check-before.json`, `demo.json` |
|
||||
| **5** Безопасное исправление, повторный запуск | `--apply --deep` дважды | 18 исправлений = найденному (3 удалённых объекта без строки, 9 строк в карантине, 6 намерений), ошибок 0; повтор — 0 действий | `evidence/reconcile/apply-1.json`, `apply-2.json` |
|
||||
| **5** Свежие и используемые вложения не удаляются, в том числе под нагрузкой | независимая проверка `scripts/reconcile_check.py --deep --expect-ready` (вне API); 75 проходов `--apply` за 75 с загрузок через LB | после `apply`: `lost_ready` 0, свежие на месте, 6 ссылок сообщений и 9 строк в карантине сохранены, метаданные `200`, `/content` `404`; под нагрузкой: 3 418 × `201`, исправлены только 10 остатков внедрения, объект идущей загрузки 247 раз выглядел объектом без строки и не тронут, все SHA-256 совпали, `lost_ready` 0 | `evidence/reconcile/check-after.json`, `under-load.json`, `check-under-load.json` |
|
||||
| **5** Карантин обратим, один проход за раз, отказ S3 | `make reconcile-demo` | возвращённый объект → `healed` 1, `/content` `200`; при занятой блокировке — `skipped`, код `0`; при остановленном `s3` — код `1` за 1,63 с, `reconcile.failed`, состояние то же | `evidence/reconcile/healed.json`, `lock-busy.json`, `s3-down.json` |
|
||||
| **5** Стоимость обхода | `make reconcile-cost` (1k / 10k / 30k × 3 прогона, закреплённые CPU, отбраковка чужой нагрузки) | без `--deep` 0,105 / 1,000 / 3,729 с, листингов `⌈N/1000⌉`, `HEAD`/`GET` 0, RSS 82,5–83,8 MiB; `--deep` 0,49 / 5,04 / 16,15 с; отбраковано 0 из 21 | `evidence/reconcile/cost/summary.txt`, `cost/*.json`, `cost/host-docker-stats.txt` |
|
||||
| **5** Тесты сверки | `make student-test` (`test_reconciler.py`, `test_s3_storage.py`) | каждый класс в dry-run без изменений, apply и повтор = 0, восстановленный объект выходит из карантина, строка после листинга сохраняет объект, второй проход пропущен, отказ хранилища посреди прохода → `Unavailable`; листинг RustFS страницами в байтовом порядке | `evidence/student-tests.txt` |
|
||||
| Уровни «3» и «4» после трека 2 | стенд из чистого состояния: `make test`, `test-persistence`, `test-failover`, `restore`, `make reconcile`, `lint`, `check`, `validate`, `student-test` | все `PASS`, failover — первая запись через 2,70 с, 128 записей, 0 ошибок; dry-run после этих сценариев: 3 объекта и 3 строки, расхождений 0 | `evidence/reconcile/after-checks.txt` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Стенд: 2 реплики `api` (1 CPU, 512 MiB, 2 воркера), RustFS 1 CPU / 512 MiB, PostgreSQL 2 CPU / 1 GiB, HAProxy
|
||||
1 CPU / 128 MiB, Valkey 0,5 CPU / 128 MiB (`evidence/limits.txt`); Docker Desktop VM 16 CPU, 7,65 ГиБ на Apple M4 Max
|
||||
(`evidence/environment.txt`). Во время нагрузки на VM кроме стенда работал один чужой контейнер — RabbitMQ
|
||||
стенда лабы 6 (`evidence/load.txt`). Данные синтетические: пользователи и чаты сценариев, fixture
|
||||
`sample.png` (111 817 B), для уровня «4» — PNG 1 и 10 MiB со случайными пикселями, для трека 2 — до 30 000 вложений
|
||||
по 264 B и 3 418 загрузок PNG 8 × 8; к концу серии уровней «3» и «4» в базе 70 839 сообщений и 1 769 готовых вложений. Повторы: память и
|
||||
нагрузка — по три прогона, отказы с бинарным критерием — по одному, остановка реплики под записью — по разу на каждую
|
||||
реплику плюс по прогону в чистом clone и после трека, всегда без неудачных записей.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Остановлена реплика, принявшая upload (`failover-upload`) | скачивание через другую реплику, тот же SHA-256 | upload через `899a952a5a21`, после её остановки download `200` через `0cc3ee358e59`, SHA-256 равен (`failover-upload.json`) | 2,73 с от старта хука; потерь нет |
|
||||
| Остановлена реплика под записью (`make test-failover`, по очереди обе) | запись восстанавливается ≤ 10 с, дублей нет, вложение читается | 2,89 и 2,88 с до первой записи, 0 неудачных попыток, 129 и 128 записей, история без дублей, вложение байт-в-байт; target `exited`, сосед `running` (`failover-*.txt`) | ≤ 2,9 с; потерь нет |
|
||||
| Перезапуск LB, API, PostgreSQL, Valkey, S3 с volumes (`restart.sh`) | метаданные, байты, сессия и история на месте | однократные `GET` метаданных и `/content` сразу после хука совпали; `StartedAt` всех контейнеров новее, ID те же (`persistence.txt`) | хук ждёт `healthy` S3; потерь нет |
|
||||
| `docker compose stop s3` | upload и `/content` → `503` за ограниченное время; тексты, метаданные, readiness работают | `503` за 2,23 и 1,99 с; текст `201`, метаданные и readiness `200` (`s3-outage.json`) | S3 healthy через 5,8 с; файл тот же; неудачный upload оставил одну невидимую строку `pending` |
|
||||
| `docker compose stop postgres` / `valkey` (`make faults-evidence`) | `503` без `500`; без Valkey проверка токенов через PostgreSQL | PostgreSQL: ready, me, login, register `503` за ≤ 0,015 с; Valkey: токен `200`, неизвестный `401`, вход `201`, выход `503` (`faults.txt`) | после `start` — без рестарта API; потерь нет |
|
||||
| Посторонний: метаданные, `/content`, upload в чужой чат, ссылка на чужое вложение | `404` без раскрытия | `404` во всех случаях, раньше проверок содержимого (`upload-faults.txt`) | — |
|
||||
| Анонимный клиент S3 из сети стенда | `403` | прямой GET `403`, Head/List/Put — deny (`s3-security.txt`) | — |
|
||||
| Тело 10 485 761 B (`Content-Length` и chunked), PNG 100 000 × 100 000 | `413` до чтения сверх лимита и до декодирования | `413`; строк и объектов не появилось | — |
|
||||
| Отказ `COMMIT` после записи объекта (триггер PostgreSQL, `55P03`) | `503`; объект и строка удалены сразу | `503`; строки нет, `HEAD` объекта 404, `audit.attachment_discarded reason=compensation` | сразу; вечных объектов нет |
|
||||
| Реплика убита `SIGKILL` между `PUT` и `COMMIT` (обе по очереди) | обрыв запроса; невидимый остаток уходит после grace | клиент — `502` от LB; `pending` и объект на месте; после сдвига за grace убраны через 24,7 с, свежий остаток не тронут до своего сдвига | grace 900 с (в тесте — сдвиг `created_at`); реплика возвращена `up --wait` |
|
||||
| Клиент оборвал тело после 256 KiB из 5 MiB | ничего не записано, не `500` | `400` в журнале реплики, намерения нет | — |
|
||||
| Тело зависло после 1 KiB | `503` не позже таймаута запроса | `503` за 8,01 с, ничего не записано | слот свободен, следующий upload `201` |
|
||||
| 36 ошибочных запросов к вложениям через LB | `4xx` по контракту, ни одного `5xx` | 16 × `400`, 6 × `404`, 4 × `413`, 10 × `415`; в журнале 0 × `5xx` | — |
|
||||
| Потерянный ответ: клиент сдался, запись ждёт блокировку чата; повтор тем же ключом (`make retry-check`) | `201` с тем же сообщением, одна копия | реплика жива — повтор через 1,53 с, тот же `id`; реплику убили, пока запрос ждал, — повтор через 1,54 с от соседа, тот же `id`, одна копия (`retry.json`) | потерь и дублей нет |
|
||||
| 40 одновременных загрузок по 10 MiB без лимита слотов (×3) | память растёт до лимита | пик 512,3 MiB = лимит cgroup во всех трёх прогонах; `201` — 53, 46 и 80 из 80, остальные `503` по таймауту запроса; `oom_kill` 0 | 67 из этих и следующих `503` оставили невидимые `pending` — см. строку ниже |
|
||||
| То же с 3 слотами на воркер (×3) | пик ограничен; ожидание слота укладывается в таймаут запроса | пик 333,7–344,6 MiB, LB ≤ 31 MiB, `oom_kill` 0; `201` — 73, 80 и 80 из 80: в первом прогоне 7 загрузок не уложились в 8 с (ожидание слота плюс запись) и получили `503` во время `PutObject`; p95 4,6–7,6 с | — |
|
||||
| Остатки `503` по таймауту после серии памяти | невидимы, сверка видит их свежими, уборка удаляет после grace | `make reconcile`: 1 794 объекта, 1 837 строк, `pending_fresh` 68 (67 от серии и 1 от `s3-outage`), прочих расхождений 0; уборка удалила все 68 (`audit.attachment_discarded reason=abandoned` × 68), после неё сверка: 1 769 объектов = 1 769 строк `ready`, расхождений 0 (`overload-leftovers.txt`) | grace 900 с: намерение `s3-outage` убрано через 903 с, последнее из серии — через 929 с после создания; готовые не тронуты |
|
||||
| Трек 2: мусор под префикс, удалённые и перезаписанные объекты, намерения без объекта и с объектом (старше grace) | dry-run находит, `apply` чинит, повтор — 0 | так и есть: 18 найдено, 18 исправлено, повтор 0; строки `ready` не удалены, а в карантине | один проход `apply` (0,11 с); байты 9 повреждённых вложений не восстановить — второго источника нет, карантин закрывает `/content` |
|
||||
| Трек 2: объект вложения в карантине вернули в bucket | карантин снят | `healed` 1, `/content` снова отдаёт исходные байты | следующий проход |
|
||||
| Трек 2: сверка при остановленном S3 | код `1` за ограниченное время, ничего не меняет | код `1` за 1,63 с, `EndpointConnectionError` в журнале | повторить после возврата S3 |
|
||||
| Трек 2: `--apply` подряд во время загрузок через LB | ни одно идущее или готовое вложение не удалено | 3 418 × `201`, все готовы с тем же SHA-256, `lost_ready` 0; 247 раз объект идущей загрузки выглядел объектом без строки и остался | потерь нет |
|
||||
|
||||
### Нагрузка записи сообщений (историческая серия asyncpg)
|
||||
|
||||
**Цель.** Проверить, что после переноса исправлений лабы 3 и добавления вложений запись сообщений под нагрузкой
|
||||
проходит без ошибок, и снять её профиль: RPS, задержки, CPU и память. Гипотеза о пределе заранее не ставилась.
|
||||
|
||||
**Методика** (`evidence/load.txt`). Публичный `tests/load.py`: закрытый контур, 64 потока, 8 с, все записи прогона —
|
||||
в один новый чат (одна строка `chats` под блокировкой), без повторов; 3 прогона с паузой 15 с, без прогрева
|
||||
(регистрация и чат создаются до окна замера). Клиент — одноразовый контейнер в сети `edge` стенда (2 CPU, 512 MiB,
|
||||
образ Python API по digest, `tests/` только для чтения, `tcp_tw_reuse`), адрес — `http://lb:8080`, как у k6 в лабе 3.
|
||||
Первая попытка с хоста macOS отброшена: `load.py` открывает соединение на каждый запрос, и через прокси Docker
|
||||
Desktop диапазон эфемерных портов хоста кончился (≈ 16 000 сокетов `TIME_WAIT`) — 10 045 и 6 398 клиентских ошибок
|
||||
соединения при том, что реплики ответили `201` на каждый дошедший запрос (`evidence/load/host-attempt.txt`). На 4-й
|
||||
секунде снимается `docker stats` стенда и клиента, после прогона — статусы `request.handled` реплик.
|
||||
|
||||
**Результаты** (медиана трёх прогонов, `evidence/load/run{1,2,3}.json`):
|
||||
|
||||
| Прогон | Успешных запросов | Ошибок | RPS | p50 / p95 / p99, мс |
|
||||
| --- | ---: | ---: | ---: | --- |
|
||||
| 1 | 17 199 | 0 | 2 100 | 25,9 / 68,5 / 96,6 |
|
||||
| 2 | 17 386 | 0 | 2 118 | 26,4 / 66,6 / 86,2 |
|
||||
| 3 | 17 332 | 0 | 2 106 | 26,6 / 67,0 / 88,4 |
|
||||
| медиана | — | 0 из 51 917 | 2 106 | 26,4 / 67,0 / 88,4 |
|
||||
|
||||
На репликах — только `201` и `200`, ни одного `4xx`/`5xx`. CPU в середине прогона: `api` 89–98 % каждая при лимите
|
||||
1 CPU, `postgres` 213–215 % при лимите 2 CPU, `lb` 79–81 %, клиент 102–106 % из 2 CPU, Valkey ≈ 6 %, RustFS < 4 %;
|
||||
память `api` 215–218 MiB из 512, `postgres` 165–186 MiB. Разброс RPS между прогонами — 0,9 %.
|
||||
|
||||
**Вывод.** Запись идёт без ошибок, а упирается в CPU: и реплики, и PostgreSQL работают у своих лимитов, поэтому
|
||||
2 100 RPS — пропускная способность этого распределения CPU для записи в один горячий чат, а не предел архитектуры.
|
||||
Задержки — только успешных запросов закрытого контура (согласованные пропуски, клиент на той же VM). Загрузки
|
||||
вложений нагружают другое — память и сеть, — их пропускная способность снята в эксперименте ниже: 13 загрузок по
|
||||
10 MiB в секунду (≈ 130 MiB/s через LB в S3) при 10 и 20 клиентах и 3 слотах на воркер.
|
||||
|
||||
### Эксперимент уровня «4»: память при одновременных загрузках
|
||||
|
||||
**Гипотеза** (D3 в `design.md` изменения `add-lab4-upload-resilience`). Без ограничения каждая загрузка 10 MiB в
|
||||
полёте держит в воркере несколько копий тела, и пик памяти реплики растёт с числом одновременных загрузок до лимита
|
||||
cgroup. С `UPLOAD_CONCURRENCY` слотами на воркер пик ограничен величиной «простой + 2 воркера × слоты × память
|
||||
загрузки» и от числа клиентов не зависит; лишние клиенты ждут слота — растёт задержка, а `503` получает только тот,
|
||||
чьё ожидание вместе с записью дольше таймаута запроса 8 с.
|
||||
|
||||
**Методика.** `scripts/upload_memory.py` (цель `make upload-memory`; генератор `scripts/lab4_seed.py`), три прогона
|
||||
всей матрицы подряд в `evidence/upload-memory/run{1,2,3}/`. Стенд `compose.yaml`: 2 реплики по 1 CPU и 512 MiB, 2
|
||||
воркера; LB 128 MiB; RustFS 1 CPU, 512 MiB. Перед каждой точкой реплики и LB пересоздаются (`memory.peak` cgroup v2
|
||||
на ядре Docker Desktop не сбрасывается) и проходит ожидание двух `UP` в LB. Затем c потоков на keep-alive
|
||||
соединениях с хоста через LB делают по 2 загрузки одного PNG 1024 × h со случайными пикселями (1 048 276 или
|
||||
10 485 256 B). Задержка — от отправки до ответа на клиенте, только по `201`; пик — `memory.peak` каждой реплики и LB
|
||||
после точки (включает страничный кэш и память сокетов), простой — `memory.current` перед ней, `oom_kill` — из
|
||||
`memory.events`. Конфигурации: 64 слота (фактически без лимита) и 3 слота; 1 и 10 MiB; c = 10, 20, 40; отдельно один
|
||||
прогон 3 слота × 10 MiB с порогом `mmap` 32 MiB (`evidence/upload-memory/mmap-32m/`).
|
||||
|
||||
**Исторические результаты asyncpg** (медиана трёх прогонов, в скобках — разброс;
|
||||
колонка LB — максимум трёх, округлённый вверх; простой реплики 112–122 MiB, лимит 512 MiB):
|
||||
|
||||
| Слоты | Размер | c | Ответы `201` из 2c в трёх прогонах | p50 / p95, мс | Пик реплики, MiB | Макс. пика LB из трёх, MiB |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| 64 | 1 MiB | 10 / 20 / 40 | все | 111 / 156 · 161 / 214 · 263 / 398 | 176 / 189 / 212 | ≤ 26 |
|
||||
| 64 | 10 MiB | 10 | 20, 20, 20 | 842 / 870 | 288 (278–291) | 24 |
|
||||
| 64 | 10 MiB | 20 | 40, 40, 40 | 2 663 / 2 906 | 428 (422–503) | 24 |
|
||||
| 64 | 10 MiB | 40 | 53, 46, 80 (27 и 34 × `503`) | 5 986 / 6 981 | **512 = лимит** во всех трёх | 26 |
|
||||
| 3 | 1 MiB | 10 / 20 / 40 | все | 106 / 157 · 142 / 250 · 230 / 390 | 173 / 180 / 185 | ≤ 28 |
|
||||
| 3 | 10 MiB | 10 | 20, 20, 20 | 822 / 1 402 | 297 (281–297) | 24 |
|
||||
| 3 | 10 MiB | 20 | 40, 40, 40 | 1 020 / 2 164 | 321 (314–321) | 27 |
|
||||
| 3 | 10 MiB | 40 | 73, 80, 80 (7 × `503`) | 3 644 / 7 310 | **334** (334–345) | 31 |
|
||||
| 3, `mmap` 32 MiB | 10 MiB | 10 / 20 / 40 | все (один прогон) | 802 / 1 290 · 2 324 / 3 613 · 3 139 / 5 373 | 321 / 356 / 346 | ≤ 31 |
|
||||
|
||||
**Вывод.** Гипотеза подтверждена, с оговоркой о верхней точке. Без лимита пик 10 MiB-загрузок растёт 288 → 428 →
|
||||
512 MiB и при 40 одновременных во всех трёх прогонах упирается в лимит cgroup: реплика отвечает `503` на 27, 34 и 0
|
||||
загрузок из 80 (OOM-убийства в этой серии не было, но память — у самого лимита). С тремя слотами пик держится на
|
||||
297–345 MiB (не больше 67 % лимита) при росте нагрузки вчетверо. Одна загрузка 10 MiB в полёте стоит ≈ 36 MiB
|
||||
((334 − 120) / 6 слотов на реплику): тело, склейка кусков, копии проверки изображения и клиента S3. Цена лимита —
|
||||
ожидание слота: при 40 клиентах p95 4,6–7,6 с, у самой границы таймаута запроса 8 с, и в одном прогоне из трёх 7
|
||||
загрузок из 80 не уложились в него и получили `503` — слоты защищают память, но очередь за ними ограничена
|
||||
таймаутом, и 40 одновременных загрузок по 10 MiB на две реплики — предел этой конфигурации. Для 1 MiB лимит не
|
||||
нужен: 173–213 MiB при любой одновременности. Порог `mmap` 32 MiB вместо 128 KiB добавляет к пику 12–35 MiB (321 /
|
||||
356 / 346 против 297 / 321 / 334); это один прогон, и при 40 клиентах эффект сравним с разбросом. `503` по таймауту, пришедшиеся на `PutObject` или `UPDATE`, оставили невидимые
|
||||
намерения — их судьба в таблице отказов выше.
|
||||
|
||||
**Ограничения.** Клиент, LB, API и RustFS делят один хост и CPU; клиент работает с хоста через прокси Docker Desktop;
|
||||
пик cgroup включает страничный кэш и память сокетов; распределение соединений между воркерами gunicorn
|
||||
неравномерно, отсюда разброс p95 до 2,6 раза между прогонами одной точки; порог `mmap` — один прогон.
|
||||
|
||||
### Трек 5 — трек 2 «Согласованность двух хранилищ (reconciler)»
|
||||
|
||||
**Что сделано.** Одноразовая команда `python -m messenger.attachments.entrypoints.reconcile` — сервис `reconciler`
|
||||
под профилем `reconcile` (`make reconcile ARGS=…`), по умолчанию `--dry-run`, `--apply` исправляет. Один проход
|
||||
сливает два отсортированных потока: листинг `ListObjectsV2(Prefix="attachments/", MaxKeys=1000)` (S3 отдаёт ключи в
|
||||
байтовом порядке) и keyset-страницы `SELECT … FROM attachments WHERE object_key > $1 ORDER BY object_key LIMIT 1000`
|
||||
(`Index Scan` по `attachments_object_key_key`, колонка `COLLATE "C"` — тот же порядок; выбирается страница плюс одна
|
||||
строка, чтобы не читать пустую последнюю страницу). Для каждой строки сначала
|
||||
идут все объекты с меньшим ключом (объекты без строки), затем пара или её отсутствие. Время O(N), в памяти — по
|
||||
странице каждой стороны. Порог «старого» — `now − grace − skew` (по умолчанию 3600 + 60 с, `grace` ≥ 60): по
|
||||
`LastModified` объекта и `created_at` строки.
|
||||
|
||||
| Класс | Условие | `--apply` |
|
||||
| --- | --- | --- |
|
||||
| `orphan_stale` / `orphan_fresh` | объект без строки старше / моложе порога | повторный `SELECT` по ключу; строки нет → `DeleteObject` / ничего |
|
||||
| `missing` | `ready`, объекта нет | `HEAD`: всё ещё 404 → карантин |
|
||||
| `size_mismatch` | `ready`, `Size ≠ size_bytes` | `HEAD`: размер всё ещё другой → карантин |
|
||||
| `sha_mismatch` | `--deep`: SHA-256 потока ≠ `sha256` | карантин |
|
||||
| `pending_stale` / `pending_fresh` | `pending` старше / моложе порога | `FOR UPDATE SKIP LOCKED`, всё ещё `pending` и старая → объект, затем строка / ничего |
|
||||
| `quarantined` / `healed` | в карантине и всё ещё расходится / размер снова совпал, и SHA-256 потока объекта равен `sha256` (хешируется и без `--deep`) | ничего / снять карантин |
|
||||
|
||||
Безопасность: готовая строка и её объект не удаляются никогда — строка уходит в карантин (миграция `0004`:
|
||||
`quarantine_reason`, `quarantined_at`), метаданные не меняются, `/content` отвечает `404` без запроса к S3, на строку
|
||||
по-прежнему ссылаются сообщения (`message_attachments → attachments ON DELETE RESTRICT`); карантин обратим, но
|
||||
снимается только после того, как объект прочитан и его SHA-256 совпал с метаданными. Объект той же длины с другими
|
||||
байтами строку из карантина не выпускает. Каждое действие предваряет повторная проверка той стороны, которую оно
|
||||
меняет (отказ — `rechecked`). Одновременно идёт один
|
||||
проход: `pg_try_advisory_lock(20260004)` на отдельном соединении на всё время прохода, второй отвечает `skipped` с
|
||||
кодом `0`. `--deep` читает каждый объект потоком и хеширует кусками по 64 KiB, не больше 8 в полёте. Отчёт — JSON в
|
||||
stdout (классы, исправленное, `rechecked`, до 20 примеров id, запросы, время, CPU, пик RSS), журнал — в stderr без
|
||||
ключей объектов и кредов. Код `1` — любая ошибка прохода (журнал `reconcile.failed` с типом ошибки, без трассировки)
|
||||
или не выполненное действие. Удаление брошенного намерения пишет `audit.attachment_discarded reason=reconcile`, как
|
||||
уборка и компенсация API: события UoW идут через `EventBus` в `AttachmentsJournal`, сервис собирает dishka из
|
||||
`PlatformProvider` и того же провайдера хранилища, что у API. Ключ S3 у сверки свой (`ListBucket`, `GetObject`,
|
||||
`DeleteObject`), ключа API и root-ключей у сервиса нет. `init: true`: `docker stop` идущего прохода завершает его
|
||||
сразу, advisory lock снимает PostgreSQL при закрытии соединения.
|
||||
|
||||
**Гипотезы** записаны в `design.md` изменения `add-lab4-storage-reconciler` в коммите предложения `148868b`, до первого
|
||||
прогона. H1 (корректность): слияние находит каждое внедрённое расхождение в его классе, `--apply` исправляет ровно
|
||||
найденное исправимое, повторный `--apply` — 0 действий; свежие объекты и намерения, готовые и используемые вложения
|
||||
не удаляются, в том числе во время загрузок. H2 (стоимость), дословно из `148868b`: время прохода без `--deep` растёт
|
||||
линейно (`t(100k)/t(10k) ≈ 10 ± 30 %`) и определяется числом страниц листинга; запросов листинга и SQL — `⌈N/1000⌉`,
|
||||
`HEAD`/`GET` — 0; пик RSS одинаков для 1k и 100k (разница < 10 %); `--deep` на порядок дороже на объект и линеен по
|
||||
объёму. История формулировки: после двух прерванных наполнений до 100k (`cost-aborted/`) H2 в `5ca2cdc` была
|
||||
переписана на 30k (`t(30k)/t(10k) = 3 ± 30 %`), и прошлая версия отчёта проверяла уже её. Точка 100k в прежней серии не является доказательством SQLAlchemy;
|
||||
текущий цикл повторяет исходную H2 из `148868b`. Соотношение 30k/10k приведено как дополнительное.
|
||||
|
||||
**Текущая методика и данные SQLAlchemy.** H1/H2/H3 повторно зафиксированы до измерений
|
||||
в предложении751aaed4b1baaa957c74bb8874adeb0eac4b0480. Полный протокол:
|
||||
[evidence/sqlalchemy-2026-11-06/track5/NOTES.md](evidence/sqlalchemy-2026-11-06/track5/NOTES.md).
|
||||
Два отдельных свежих project hlpipe-lab4-track-20261106 и hlpipe-lab4-cost-20261106,
|
||||
без удаления существующих volumes и остановки чужих контейнеров. Demo:18 явных upload
|
||||
плюс1 предварительного smoke, grace60/skew0, затем внедрение ошибок, dry/apply/повтор,
|
||||
независимая сверка и75 с загрузок. Cost:1k/10k/30k/100k, по3 shallow/deep и3 page100 на10k;
|
||||
PNG264 B, четыре параллельных PUT, SQLAlchemy INSERT. API/LB/Valkey во время cost остановлены.
|
||||
RustFS2CPU/3GiB на11–12, PG2CPU/1GiB на13–14, CLI1CPU/256MiB на15.
|
||||
Чужой CPU ограничен фильтром2ядраVM/0,25закреплённых; все27 принятых проходят его.
|
||||
Каждая команда, UTC, полный SHA и exit code сохранены; серии используют новый --out.
|
||||
|
||||
**H1: корректность.** 13/13 проверок PASS,256,958 с. Dry-run не изменил24 объекта/27 строк;
|
||||
найдены точные множества внедрённых id/key. Apply:3 orphan удалены,9 строк в карантине,
|
||||
6 pending удалены с6 audit reason=reconcile; повтор0. Все6 ссылок сообщений и9 строк
|
||||
с расхождениями сохранены. Возврат исходных байтов снял1 карантин без deep; другие байты
|
||||
той же длины карантин не сняли. SIGTERM:exit143 за0,14 с, следующий проход не skipped;
|
||||
занятая блокировка→skipped; S3 и PG outage→exit1/reconcile.failed, без traceback.
|
||||
Под нагрузкой3331×201,67 проходов, после3342 здоровых ready,8 карантинов, lost_ready=0.
|
||||
Видели201 orphan_fresh и52 pending_fresh; rechecked={missing:42} означает повторныйHEAD.
|
||||
Повторную проверку строки перед удалением отдельно подтверждает собственный тест
|
||||
`test_row_written_after_listing_keeps_the_object`; наблюдение grace не выдано за этот барьер.
|
||||
Файлы: track5/demo/*.json, demo-command.txt и pg-outage.txt новой серии.
|
||||
|
||||
**H2/H3: стоимость на SHA3402fd69d4922e500035a204d957be2cccaeb85a.**
|
||||
Медианы трёх повторов и диапазон времени; CPU и RSS также медианы. Последняя колонка —
|
||||
исторический asyncpg61dcb6b, не причинный A/B-тест. Raw: track5/measurements/cost/;
|
||||
`tools/summarize_reconciler.py` проверяет все27 raw и воспроизводит analysis.json.
|
||||
|
||||
| N | Режим | Проход, с: медиана [min–max] | CPU, с | Листинг / SQL, с | LIST / SQL / GET | RSS, MiB | asyncpg, с → отношение |
|
||||
| ---: | --- | --- | ---: | --- | --- | ---: | --- |
|
||||
| 1000 | shallow | 0.107 [0.105–0.113] | 0.560 | 0.087 / 0.011 | 1 / 1 / 0 | 109.8 | 0.108 → 0.991× |
|
||||
| 1000 | deep | 0.499 [0.498–0.536] | 0.995 | 0.088 / 0.012 | 1 / 1 / 1000 | 110.2 | 0.546 → 0.914× |
|
||||
| 10000 | shallow | 0.999 [0.996–1.077] | 0.865 | 0.907 / 0.079 | 10 / 10 / 0 | 110.9 | 1.032 → 0.968× |
|
||||
| 10000 | deep | 4.998 [4.972–5.041] | 4.808 | 0.932 / 0.081 | 10 / 10 / 10000 | 111.3 | 5.041 → 0.991× |
|
||||
| 10000 | page100 | 2.037 [2.035–2.113] | 0.942 | 1.897 / 0.127 | 100 / 100 / 0 | 107.9 | 2.031 → 1.003× |
|
||||
| 30000 | shallow | 3.601 [3.567–3.633] | 1.495 | 3.382 / 0.176 | 30 / 30 / 0 | 110.9 | 3.761 → 0.957× |
|
||||
| 30000 | deep | 15.665 [15.630–15.779] | 13.503 | 3.461 / 0.204 | 30 / 30 / 30000 | 111.6 | 15.903 → 0.985× |
|
||||
| 100000 | shallow | 20.215 [20.206–21.335] | 3.708 | 19.538 / 0.640 | 100 / 100 / 0 | 111.1 | 20.211 → 1.000× |
|
||||
| 100000 | deep | 110.910 [58.661–147.215] | 83.969 | 35.014 / 1.199 | 100 / 100 / 100000 | 111.4 | 60.637 → 1.829× |
|
||||
|
||||
H2 о времени отвергнута: t100k/t10k=20,235, вне[7,13]. Листинг занимает19,538 из20,215 с
|
||||
на100k, но причина роста внутри хранилища не установлена. LIST и SQL точно ceil(N/page),
|
||||
HEAD/GET=0 без deep; SQL здесь считает страницы, без служебных команд транзакций/пула.
|
||||
Память shallow109,8→111,1MiB (+1,18%) укладывается в<10%. Deep дороже по медианам
|
||||
в4,35–5,49 раза, не на порядок. H3 о страничности и памяти подтверждена в измеренной области.
|
||||
Абсолютный RSS после переноса выше исторического примерно на25–26%.
|
||||
|
||||
**Ограничения трека.** На100k deep получены147,215/110,910/58,661 с, разброс79,84%
|
||||
от медианы. Все три прошли заранее заданный CPU-фильтр; результаты не исключались
|
||||
по времени. Надёжного причинного вывода о влиянии SQLAlchemy на скорость deep нет.
|
||||
В остальных точках разброс0,95–8,11%. Один хост/VM, тёплые после наполнения данные,
|
||||
частоты/диск/нагрузка macOS не контролируются screen. PNG264 B не прогнозирует deep
|
||||
для10MiB; >100k не измерено, экстраполяции на миллион нет. Смещение часов не моделировалось.
|
||||
В demo grace60/skew0; штатная уборка API с grace900 проверена реальным ожиданием в grade4.
|
||||
Сверка не восстанавливает байты, работает вручную с префиксом attachments/; незавершённые
|
||||
multipart убирает lifecycle bucket. Следующий этап после ревью подготовит окончательную
|
||||
редакцию остальных исторических разделов отчёта по новым NOTES.
|
||||
|
||||
## Ответы на вопросы защиты
|
||||
|
||||
**Сценарий защиты README — чем он показывается.** (1) Fixture, сообщение с `attachment_ids`, скачивание вторым
|
||||
участником и сравнение SHA-256 — шаги `LAB ≥ 4` в `make test` и `make scenario SCENARIO=failover-upload`
|
||||
(`sha256_equal`). (2) Посторонний получает `404` на метаданные и байты — тот же smoke; прямой анонимный GET объекта
|
||||
из отдельного контейнера — `403` (`make s3-check`). (3) `make test-persistence ACTION_SCRIPT=scripts/restart.sh` и
|
||||
`make test-failover ACTION_SCRIPT=scripts/stop-one.sh` (оба после хука один раз читают оригинал через API). (4)
|
||||
Локального файла оригинала на API нет — `make attachments-evidence`: корень реплик только для чтения, единственный
|
||||
`tmpfs /tmp`, volume нет. Для «4» и «5» — `make upload-faults`, `make upload-memory`, `make reconcile-demo`.
|
||||
|
||||
**Почему файл в Docker volume одной API-реплики не равен объектному хранилищу?** Volume реплики видит только она.
|
||||
Round robin отправит скачивание на соседа, и тот файла не найдёт; остановка или пересоздание принявшей реплики
|
||||
уносит доступ к файлу вместе с ней; новая реплика начинает с пустым volume. Общий volume на одном хосте не решает
|
||||
этого: его не подключить к реплике на другом узле, у него нет атомарной публикации объекта целиком, политики
|
||||
доступа, листинга по префиксу и правил жизненного цикла, а запись в него из нескольких процессов ничем не согласована.
|
||||
Объектное хранилище — отдельный сервис с одним пространством ключей для всех реплик: `PutObject` либо создаёт
|
||||
объект целиком, либо нет, доступ задают ключи и политика bucket, а реплики API остаются без состояния. Здесь
|
||||
upload принят репликой `899a952a5a21`, хук остановил её за 2,72 с, и через 2,73 с от старта хука
|
||||
`0cc3ee358e59` отдала те же байты (`failover-upload.json`); у реплик `ro=true` и только `tmpfs /tmp`
|
||||
(`storage-layout.txt`), байты лежат в volume `s3data` сервиса `s3`.
|
||||
|
||||
**Когда можно честно вернуть `201`?** Только когда обе записи подтверждены: S3 ответил на `PutObject` успехом и
|
||||
зафиксирован `UPDATE … SET status='ready'` в PostgreSQL. До `PUT` объекта нет — скачивание дало бы `404`; после `PUT`,
|
||||
но до `COMMIT`, вложения нет для других реплик и для ссылок из сообщений, а после потери процесса на этом шаге
|
||||
клиенту нечего показать. Поэтому порядок — `INSERT pending` + `COMMIT` → `PutObject` → `UPDATE ready` + `COMMIT` →
|
||||
`201`, и id вложения клиент узнаёт только из `201`. Отказ S3 при записи даёт `503` и невидимую строку `pending`
|
||||
(`test_storage_failure_leaves_nothing_visible` в `student-tests.txt`), отказ `COMMIT` — `503` и немедленную
|
||||
компенсацию (`upload-faults.txt`). Оговорка: если потерян сам ответ `201`, повтор клиента создаст второе вложение —
|
||||
у upload нет `Idempotency-Key`, LB его не повторяет, контракт допускает дубль.
|
||||
|
||||
**Что произойдёт, если S3 PUT прошёл, а COMMIT в PostgreSQL — нет?** Объект не становится вечным сиротой, потому
|
||||
что его ключ записан в строке-намерении до `PUT`. Три исхода: (1) PostgreSQL отклонил `UPDATE ready` — обработчик
|
||||
сразу берёт строку `FOR UPDATE`, удаляет объект, затем строку, клиент получает `503` (триггер с `55P03`: строки нет,
|
||||
`HEAD` объекта `404`, в журнале `audit.attachment_discarded reason=compensation`); если фиксация на самом деле прошла
|
||||
и строка уже `ready`, компенсация её не трогает. (2) Процесс убит между `PUT` и `COMMIT` — клиент получает `502` от
|
||||
LB, остаются невидимая строка `pending` и объект; фоновая уборка удаляет их после `UPLOAD_GRACE_SECONDS=900`
|
||||
(объект, затем строка); в `upload-faults.txt` намерение, сдвинутое за grace, убрано через 24,7 с, свежее не тронуто.
|
||||
(3) Объект, о котором PostgreSQL не знает вовсе (ручная запись, ошибка, потерянная строка), находит reconciler
|
||||
трека 2 и удаляет только если он старше grace + skew и повторная проверка строки её не нашла.
|
||||
|
||||
**Почему случайный object key и приватный bucket не заменяют ACL приложения?** Решение «можно ли этому
|
||||
пользователю это вложение» зависит от членства в чате, и знает его только приложение (`chat_members` в
|
||||
PostgreSQL); S3 о пользователях мессенджера ничего не знает. Ключ — это предъявительский секрет: утёкший из журнала
|
||||
или ссылки, он работает для любого и не отзывается, когда человека удаляют из чата. Здесь ключ и не секрет: он равен
|
||||
`attachments/<id>`, а id видят все участники в `attachment_ids`. Приватный bucket закрывает только анонимный доступ —
|
||||
ключ API читает весь bucket. Поэтому скачивание идёт только через API, который при каждом запросе проверяет членство
|
||||
(eve — `404` на метаданные и `/content`, неотличимо от несуществующего вложения), а приватность bucket (`403`
|
||||
анонимному GET), отдельный ключ API на один bucket и закрытая консоль — второй рубеж на случай ошибки в приложении
|
||||
(`s3-security.txt`).
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Один Docker-host: RustFS работает одним узлом без parity, S3 и PostgreSQL — единственные точки отказа; это не HA.
|
||||
RustFS молод (GA 1.0.0 — 2026-09-16, `rc` 0.1.x), в 2025 у него были CVE; версия и digest закреплены.
|
||||
Community-образы MinIO недоступны, проект архивирован.
|
||||
- `verify()` для PNG проверяет структуру и CRC всех чанков, но не распаковывает пиксели: PNG с корректными CRC и
|
||||
испорченным zlib-потоком будет принят. Оригинал отдаётся побайтно, серверу это не вредит; полная распаковка
|
||||
стоила бы до 160 MB на 40 MP.
|
||||
- Уборка брошенных загрузок живёт в процессах API: если все реплики остановлены, намерения ждут их возвращения
|
||||
(невидимо для клиентов). Она находит только то, что начиналось с намерения в PostgreSQL; объекты без строки,
|
||||
`ready` без объекта и несовпадение байтов при нормальной работе не возникают и ищутся reconciler трека 2.
|
||||
- Компенсация не запускается при отмене запроса таймаутом посреди `PUT` или `UPDATE`: такие остатки ждут grace
|
||||
period (15 минут). Ответ в этом случае — `503`, повтор клиента создаёт новое вложение. После новой серии памяти и отказов S3 остались
|
||||
30 намерений (у 8 — объект). Штатная уборка удалила все после grace900с без сдвига возраста
|
||||
(`evidence/sqlalchemy-2026-11-06/grade4/overload-leftovers.txt`).
|
||||
- Слоты защищают память ценой ожидания: при 40 одновременных загрузках по10MiB на две реплики и3слотах
|
||||
новый p95 —4,48–6,51с; все80загрузок каждого из трёх повторов успешны, максимальный пик448MiB.
|
||||
Контроль64слота дал27×503. Это наблюдение выбранной матрицы, а не гарантия для любой нагрузки.
|
||||
Пик памяти снят на одном хосте, клиент и стенд делят CPU.
|
||||
- Тело всё ещё собирается в памяти целиком (≈ 36 MiB на загрузку 10 MiB с учётом копий проверки и клиента S3):
|
||||
потоковая запись в S3 без буфера потребовала бы multipart и проверки изображения после записи.
|
||||
- Ранний `413`/`404` до конца тела: клиент, ещё отправляющий 10 MiB, может получить reset вместо ответа; собственные
|
||||
тесты проверяют `413` через `Content-Length`. Токен проверяется раньше объявленного размера: анонимный клиент
|
||||
получает `401`, а не лимит маршрута.
|
||||
- Минимальная скорость клиента — `MIN_TRANSFER_RATE_BYTES` (128 KiB/s): медленнее этого upload и скачивание
|
||||
обрываются (`503` для upload, обрыв тела после заголовков для скачивания), быстрее — идут сколько нужно. Длинная
|
||||
передача держит слот загрузки и буфер тела: upload 10 MiB на пороговой скорости занимает слот до 88 с. При
|
||||
`SIGTERM` реплики передача, не успевшая за `SHUTDOWN_TIMEOUT_SECONDS`, прерывается.
|
||||
- Нагрузка записи снята закрытым контуром `tests/load.py` с клиентом на той же VM и всеми записями в один чат: это
|
||||
пропускная способность этого распределения CPU (реплики и PostgreSQL у своих лимитов), а не предел архитектуры;
|
||||
с хоста macOS тот же замер упирается в эфемерные порты.
|
||||
- Секреты лежат файлами в `secrets/` на хосте (каталог `0700`, файлы `0644`, чтобы их читали непривилегированные
|
||||
пользователи контейнеров) — учебное упрощение вместо менеджера секретов. Ключ API S3 статичен, ротации нет.
|
||||
- Сверка хранилищ (трек 2) запускается вручную и не восстанавливает байты: у повреждённого вложения нет второго
|
||||
источника, оно остаётся в карантине до ручного возврата объекта. Стоимость обхода измерена до100k объектов; за этой границей утверждений нет.
|
||||
Ограничения и большой разброс deep100k — в разделе трека.
|
||||
- Подтверждено прогонами: всё в таблице доказательств, включая уровень «4» и трек 2 (H1 подтверждена, H2 — в части
|
||||
страничности и постоянной памяти, но не линейного времени или десятикратной цены deep). Не измерены:
|
||||
поведение сверки выше100k, deep на вложениях10MiB и расхождение часов S3/CLI.
|
||||
- Процесс openspec: правило `config.yaml` «proposal в пределах 400 слов» нарушено в двух архивных циклах —
|
||||
`add-lab4-image-attachments` и `add-lab4-upload-resilience` (около 453 слов без разметки, 492 и 477 по `wc -w`);
|
||||
у `add-lab4-storage-reconciler` 406 по `wc -w` и 364 без разметки. Архив уже закоммичен, историю не переписываю.
|
||||
Proposal переноса `carry-over-lab3-review-fixes` ссылается на «пункт 4.1 (согласованные таймауты и `SIGTERM`)» —
|
||||
это нумерация рубрики лабы 3. В этом отчёте перенос закрывает строку 3.9 (минимум лабы 3), а таймауты и `SIGTERM`
|
||||
лабы 3 проверяются тестами стенда (`faults.txt`) и `make limits`; строка 4.1 здесь — тесты файлов.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
[alembic]
|
||||
script_location = %(here)s/alembic
|
||||
prepend_sys_path = %(here)s/src %(here)s/alembic
|
||||
path_separator = space
|
||||
@@ -0,0 +1,92 @@
|
||||
import asyncio
|
||||
|
||||
from alembic import context
|
||||
from alembic.script import ScriptDirectory
|
||||
from legacy import adopt_legacy
|
||||
from sqlalchemy import Connection, func, make_url, pool, select
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
from messenger.attachments.infrastructure.postgres import AttachmentRow
|
||||
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
|
||||
from messenger.messaging.infrastructure.postgres import (
|
||||
ChatMemberRow,
|
||||
ChatRow,
|
||||
IdempotencyKeyRow,
|
||||
MessageAttachmentRow,
|
||||
MessageRow,
|
||||
)
|
||||
from messenger.shared.config import PlatformSettings
|
||||
|
||||
LOCK_KEY = 20_260_002
|
||||
MODELS = (
|
||||
UserRow,
|
||||
SessionRow,
|
||||
ChatRow,
|
||||
ChatMemberRow,
|
||||
MessageRow,
|
||||
IdempotencyKeyRow,
|
||||
AttachmentRow,
|
||||
MessageAttachmentRow,
|
||||
)
|
||||
target_metadata = UserRow.metadata
|
||||
config = context.config
|
||||
|
||||
|
||||
def include_object(_obj, name, _type, _reflected, _compare_to):
|
||||
return name != "schema_migrations"
|
||||
|
||||
|
||||
def run_migrations(connection: Connection) -> None:
|
||||
with connection.engine.connect() as lock:
|
||||
lock.execute(select(func.pg_advisory_lock(LOCK_KEY)))
|
||||
lock.commit()
|
||||
try:
|
||||
with connection.begin():
|
||||
adopt_legacy(connection, ScriptDirectory.from_config(config))
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
transaction_per_migration=True,
|
||||
compare_type=True,
|
||||
include_object=include_object,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
finally:
|
||||
lock.execute(select(func.pg_advisory_unlock(LOCK_KEY)))
|
||||
lock.commit()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
dsn = config.attributes.get("database_url")
|
||||
if dsn is None:
|
||||
dsn = PlatformSettings().database_url.get_secret_value()
|
||||
engine = create_async_engine(
|
||||
make_url(dsn).set(drivername="postgresql+asyncpg"),
|
||||
poolclass=pool.NullPool,
|
||||
hide_parameters=True,
|
||||
connect_args={
|
||||
"timeout": 10,
|
||||
"server_settings": {"lock_timeout": "10000", "statement_timeout": "60000"},
|
||||
},
|
||||
)
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.run_sync(run_migrations)
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
context.configure(
|
||||
dialect_name="postgresql",
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
transaction_per_migration=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
elif config.attributes.get("connection") is not None:
|
||||
run_migrations(config.attributes["connection"])
|
||||
else:
|
||||
asyncio.run(run_async_migrations())
|
||||
@@ -0,0 +1,92 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
from alembic.script import ScriptDirectory
|
||||
from sqlalchemy import Connection, MetaData, Table, func, inspect, select, text
|
||||
from sqlalchemy.schema import CreateSchema
|
||||
|
||||
LEGACY = {
|
||||
"0001_init": "9a13618f078ae9056431391e2e5197a31b981ae1fff047a9b3421ac750d3fd0d",
|
||||
"0002_idempotency_keys": "d9159a35553249a1e51af5f2e4e7c39b014e97593c49748e13f3799839063dd0",
|
||||
"0003_attachments": "c4417f560538a083efba1c67f660147dc94532fcbb2fa91f3f3e8258a0f01f2e",
|
||||
"0004_attachment_quarantine": (
|
||||
"541f5399d87fac3584c4102b4e0bf92c23cd372cc20a7d56dad03e771773202c"
|
||||
),
|
||||
}
|
||||
SNAPSHOT = text("""
|
||||
WITH relations AS (
|
||||
SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = :schema AND c.relkind IN ('r', 'p')
|
||||
AND c.relname NOT IN ('schema_migrations', 'alembic_version')
|
||||
)
|
||||
SELECT 'table' AS kind, c.relname AS name,
|
||||
concat_ws('|', c.relkind, c.relpersistence,
|
||||
c.relrowsecurity, c.relforcerowsecurity) AS definition
|
||||
FROM relations c
|
||||
UNION ALL
|
||||
SELECT 'column', c.relname || '.' || a.attname,
|
||||
concat_ws('|', a.attnum, format_type(a.atttypid, a.atttypmod), a.attnotnull,
|
||||
a.attidentity, a.attgenerated, a.attcollation::regcollation,
|
||||
pg_get_expr(d.adbin, d.adrelid))
|
||||
FROM relations c JOIN pg_attribute a ON a.attrelid = c.oid
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
|
||||
WHERE a.attnum > 0 AND NOT a.attisdropped
|
||||
UNION ALL
|
||||
SELECT 'constraint', c.relname || '.' || k.conname,
|
||||
concat_ws('|', pg_get_constraintdef(k.oid), k.convalidated)
|
||||
FROM relations c JOIN pg_constraint k ON k.conrelid = c.oid
|
||||
UNION ALL
|
||||
SELECT 'index', c.relname || '.' || x.relname,
|
||||
concat_ws('|', pg_get_indexdef(i.indexrelid), i.indisvalid, i.indisready)
|
||||
FROM relations c JOIN pg_index i ON i.indrelid = c.oid
|
||||
JOIN pg_class x ON x.oid = i.indexrelid
|
||||
UNION ALL
|
||||
SELECT 'trigger', c.relname || '.' || t.tgname,
|
||||
concat_ws('|', pg_get_triggerdef(t.oid), t.tgenabled)
|
||||
FROM relations c JOIN pg_trigger t ON t.tgrelid = c.oid WHERE NOT t.tgisinternal
|
||||
ORDER BY kind, name
|
||||
""")
|
||||
|
||||
|
||||
def snapshot(connection: Connection, schema: str) -> list[tuple[str, str, str]]:
|
||||
return [
|
||||
(kind, name, definition.replace(f"{schema}.", ""))
|
||||
for kind, name, definition in connection.execute(SNAPSHOT, {"schema": schema})
|
||||
]
|
||||
|
||||
|
||||
def adopt_legacy(connection: Connection, scripts: ScriptDirectory) -> None:
|
||||
migration = MigrationContext.configure(connection)
|
||||
if migration.get_current_heads():
|
||||
return
|
||||
tables = set(inspect(connection).get_table_names(schema="public"))
|
||||
if tables <= {"alembic_version"}:
|
||||
return
|
||||
if "schema_migrations" not in tables:
|
||||
raise RuntimeError("Existing schema has no legacy migration journal")
|
||||
journal = Table("schema_migrations", MetaData(), schema="public", autoload_with=connection)
|
||||
applied = dict(connection.execute(select(journal.c.version, journal.c.checksum)).tuples().all())
|
||||
expected = dict(list(LEGACY.items())[: len(applied)])
|
||||
if applied != expected:
|
||||
raise RuntimeError("Unknown or changed legacy migrations")
|
||||
if not applied:
|
||||
if tables - {"schema_migrations", "alembic_version"}:
|
||||
raise RuntimeError("Existing schema has an empty migration journal")
|
||||
return
|
||||
revision = list(expected)[-1]
|
||||
actual = snapshot(connection, "public")
|
||||
reference = f"alembic_verify_{uuid4().hex}"
|
||||
savepoint = connection.begin_nested()
|
||||
try:
|
||||
connection.execute(CreateSchema(reference))
|
||||
connection.execute(select(func.set_config("search_path", reference, True)))
|
||||
with Operations.context(MigrationContext.configure(connection)):
|
||||
for script in reversed(list(scripts.walk_revisions(base="base", head=revision))):
|
||||
script.module.upgrade()
|
||||
wanted = snapshot(connection, reference)
|
||||
finally:
|
||||
savepoint.rollback()
|
||||
if actual != wanted:
|
||||
raise RuntimeError("Legacy schema differs from the recorded migrations")
|
||||
migration.stamp(scripts, revision)
|
||||
@@ -0,0 +1,16 @@
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,87 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0001_init"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"users",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column("username", sa.Text(), nullable=False),
|
||||
sa.Column("display_name", sa.Text(), nullable=False),
|
||||
sa.Column("password_hash", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("password_hash LIKE '$argon2id$%'", name="users_password_hash_check"),
|
||||
sa.CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="users_username_format"),
|
||||
sa.CheckConstraint(
|
||||
"char_length(display_name) BETWEEN 1 AND 100", name="users_display_name_check"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("username", name="users_username_key"),
|
||||
)
|
||||
op.create_table(
|
||||
"sessions",
|
||||
sa.Column("token_hash", sa.LargeBinary(), nullable=False),
|
||||
sa.Column("user_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("expires_at > created_at", name="sessions_check"),
|
||||
sa.CheckConstraint("octet_length(token_hash) = 32", name="sessions_token_hash_check"),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("token_hash"),
|
||||
)
|
||||
op.create_index("sessions_user_idx", "sessions", ["user_id"], unique=False)
|
||||
op.create_table(
|
||||
"chats",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column("title", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("last_message_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.CheckConstraint("char_length(title) BETWEEN 1 AND 100", name="chats_title_check"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_table(
|
||||
"chat_members",
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("user_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("position", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("chat_created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("position BETWEEN 1 AND 100", name="chat_members_position_check"),
|
||||
sa.ForeignKeyConstraint(["chat_id"], ["chats.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
["users.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("chat_id", "user_id"),
|
||||
)
|
||||
op.create_index(
|
||||
"chat_members_user_idx",
|
||||
"chat_members",
|
||||
["user_id", "chat_created_at", "chat_id"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_table(
|
||||
"messages",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("sender_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("text", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("char_length(text) BETWEEN 1 AND 4000", name="messages_text_check"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id", "sender_id"],
|
||||
["chat_members.chat_id", "chat_members.user_id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(
|
||||
"messages_history_idx", "messages", ["chat_id", "created_at", "id"], unique=False
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete application data")
|
||||
@@ -0,0 +1,33 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0002_idempotency_keys"
|
||||
down_revision = "0001_init"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"idempotency_keys",
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("user_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("key", sa.Text(), nullable=False),
|
||||
sa.Column("fingerprint", sa.LargeBinary(), nullable=False),
|
||||
sa.Column("message_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("key ~ '^[A-Za-z0-9._:-]{1,128}$'", name="idempotency_keys_key_check"),
|
||||
sa.CheckConstraint(
|
||||
"octet_length(fingerprint) = 32", name="idempotency_keys_fingerprint_check"
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id", "user_id"],
|
||||
["chat_members.chat_id", "chat_members.user_id"],
|
||||
),
|
||||
sa.ForeignKeyConstraint(["message_id"], ["messages.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("chat_id", "user_id", "key"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete application data")
|
||||
@@ -0,0 +1,77 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0003_attachments"
|
||||
down_revision = "0002_idempotency_keys"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_constraint("messages_text_check", "messages", type_="check")
|
||||
op.create_check_constraint("messages_text_check", "messages", "char_length(text) <= 4000")
|
||||
op.create_table(
|
||||
"attachments",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("owner_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("filename", sa.Text(), nullable=False),
|
||||
sa.Column("content_type", sa.Text(), nullable=False),
|
||||
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
|
||||
sa.Column("sha256", sa.Text(), nullable=False),
|
||||
sa.Column("width", sa.Integer(), nullable=False),
|
||||
sa.Column("height", sa.Integer(), nullable=False),
|
||||
sa.Column("object_key", sa.Text(collation="C"), nullable=False),
|
||||
sa.Column("status", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("object_key", name="attachments_object_key_key"),
|
||||
sa.UniqueConstraint("id", "chat_id", name="attachments_chat_key"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id", "owner_id"],
|
||||
["chat_members.chat_id", "chat_members.user_id"],
|
||||
name="attachments_owner_fkey",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"char_length(filename) BETWEEN 1 AND 255", name="attachments_filename_check"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"content_type IN ('image/png', 'image/jpeg')", name="attachments_content_type_check"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"size_bytes BETWEEN 1 AND 10485760", name="attachments_size_bytes_check"
|
||||
),
|
||||
sa.CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="attachments_sha256_check"),
|
||||
sa.CheckConstraint("width > 0", name="attachments_width_check"),
|
||||
sa.CheckConstraint("height > 0", name="attachments_height_check"),
|
||||
sa.CheckConstraint("status IN ('pending', 'ready')", name="attachments_status_check"),
|
||||
)
|
||||
op.create_index(
|
||||
"attachments_pending_idx",
|
||||
"attachments",
|
||||
["created_at"],
|
||||
postgresql_where=sa.text("status = 'pending'"),
|
||||
)
|
||||
op.create_table(
|
||||
"message_attachments",
|
||||
sa.Column("message_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("position", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("attachment_id", sa.Uuid(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("message_id", "position"),
|
||||
sa.UniqueConstraint("message_id", "attachment_id"),
|
||||
sa.CheckConstraint("position BETWEEN 0 AND 9", name="message_attachments_position_check"),
|
||||
sa.ForeignKeyConstraint(["message_id"], ["messages.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["attachment_id", "chat_id"],
|
||||
["attachments.id", "attachments.chat_id"],
|
||||
name="message_attachments_attachment_fkey",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
)
|
||||
op.create_index("message_attachments_attachment_idx", "message_attachments", ["attachment_id"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete application data")
|
||||
@@ -0,0 +1,28 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0004_attachment_quarantine"
|
||||
down_revision = "0003_attachments"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("attachments", sa.Column("quarantine_reason", sa.Text(), nullable=True))
|
||||
op.create_check_constraint(
|
||||
"attachments_quarantine_reason_check",
|
||||
"attachments",
|
||||
"quarantine_reason IN ('missing', 'size_mismatch', 'sha_mismatch')",
|
||||
)
|
||||
op.add_column(
|
||||
"attachments", sa.Column("quarantined_at", sa.DateTime(timezone=True), nullable=True)
|
||||
)
|
||||
op.create_check_constraint(
|
||||
"attachments_quarantine_check",
|
||||
"attachments",
|
||||
"(quarantine_reason IS NULL) = (quarantined_at IS NULL)",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete quarantine data")
|
||||
@@ -1,10 +1,12 @@
|
||||
# Topology worksheet, deliberately NOT a runnable stack (no application supplied).
|
||||
# Implement compose.yaml or stack.yaml; do not submit this empty file as deployment.
|
||||
# Service names below are logical roles, not imposed container names.
|
||||
x-lab-number: 2
|
||||
x-lab-number: 4
|
||||
x-required-roles:
|
||||
- api
|
||||
- postgres
|
||||
- load_balancer
|
||||
- s3
|
||||
# TODO: implement real images/builds, network wiring, volumes, healthchecks,
|
||||
# credentials and bootstrap. Details: contracts/infrastructure.json and README.md.
|
||||
services: {}
|
||||
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
x-app: &app
|
||||
image: ${API_IMAGE:-mtusi-messenger:${COMPOSE_PROJECT_NAME}}
|
||||
networks: [backend]
|
||||
|
||||
x-s3-env: &s3-env
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
S3_CONNECT_TIMEOUT_SECONDS: ${S3_CONNECT_TIMEOUT_SECONDS:-1}
|
||||
S3_READ_TIMEOUT_SECONDS: ${S3_READ_TIMEOUT_SECONDS:-2}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
IMAGE_CHECK_CONCURRENCY: ${IMAGE_CHECK_CONCURRENCY:-2}
|
||||
UPLOAD_CONCURRENCY: ${UPLOAD_CONCURRENCY:-3}
|
||||
UPLOAD_GRACE_SECONDS: ${UPLOAD_GRACE_SECONDS:-900}
|
||||
UPLOAD_SWEEP_INTERVAL_SECONDS: ${UPLOAD_SWEEP_INTERVAL_SECONDS:-30}
|
||||
UPLOAD_SWEEP_BATCH: ${UPLOAD_SWEEP_BATCH:-100}
|
||||
|
||||
x-s3-client: &s3-client
|
||||
image: rustfs/rc:v0.1.36@sha256:ab024bfebee49a750ce886b4c70963ccd9ddaa03f491704a90710641d7a26699
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=16m"]
|
||||
environment:
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
RC_CONFIG_DIR: /tmp/rc
|
||||
user: "65534:65534"
|
||||
volumes: ["./infra/s3:/s3:ro"]
|
||||
secrets:
|
||||
- s3_root_user
|
||||
- s3_root_password
|
||||
- s3_access_key_id
|
||||
- s3_secret_access_key
|
||||
- s3_reconciler_access_key_id
|
||||
- s3_reconciler_secret_access_key
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
restart: "no"
|
||||
networks: [backend]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 64m}
|
||||
|
||||
services:
|
||||
lb:
|
||||
image: haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b
|
||||
environment:
|
||||
API_SERVER_MAXCONN: ${API_SERVER_MAXCONN:-64}
|
||||
volumes: [./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro]
|
||||
ports:
|
||||
- "127.0.0.1:${LB_HTTP_PORT:-8080}:8080"
|
||||
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404"
|
||||
networks: [edge, backend]
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/healthz"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
start_interval: 1s
|
||||
sysctls:
|
||||
net.ipv4.ip_local_port_range: "10240 65535"
|
||||
net.ipv4.tcp_tw_reuse: "1"
|
||||
stop_signal: SIGUSR1
|
||||
stop_grace_period: 8s
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${LB_CPUS:-1}", memory: 128m}
|
||||
|
||||
api:
|
||||
<<: *app
|
||||
build: .
|
||||
environment:
|
||||
<<: *s3-env
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
CURSOR_SECRET_FILE: /run/secrets/cursor_secret
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
||||
DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-8}
|
||||
REQUEST_TIMEOUT_SECONDS: ${REQUEST_TIMEOUT_SECONDS:-8}
|
||||
MIN_TRANSFER_RATE_BYTES: ${MIN_TRANSFER_RATE_BYTES:-131072}
|
||||
DB_ACQUIRE_TIMEOUT_SECONDS: ${DB_ACQUIRE_TIMEOUT_SECONDS:-1}
|
||||
DB_COMMAND_TIMEOUT_SECONDS: ${DB_COMMAND_TIMEOUT_SECONDS:-2}
|
||||
DRAIN_SECONDS: ${DRAIN_SECONDS:-2}
|
||||
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-6}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||
MALLOC_MMAP_THRESHOLD_: ${MALLOC_MMAP_THRESHOLD_:-131072}
|
||||
secrets: [database_url, cache_url, cursor_secret, s3_access_key_id, s3_secret_access_key]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200)"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
start_interval: 200ms
|
||||
stop_grace_period: 8s
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs: [/tmp]
|
||||
sysctls:
|
||||
net.ipv4.tcp_rmem: "4096 65536 262144"
|
||||
net.ipv4.tcp_wmem: "4096 65536 262144"
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
valkey:
|
||||
condition: service_started
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: {cpus: "${API_CPUS:-1}", memory: "${API_MEMORY:-512m}"}
|
||||
|
||||
migrate:
|
||||
<<: *app
|
||||
pull_policy: never
|
||||
init: true
|
||||
command: ["alembic", "upgrade", "head"]
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||
secrets: [database_url]
|
||||
healthcheck:
|
||||
disable: true
|
||||
restart: "no"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256m}
|
||||
|
||||
postgres:
|
||||
image: postgres:17.11-alpine@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b
|
||||
user: "70:70"
|
||||
command:
|
||||
- postgres
|
||||
- -c
|
||||
- max_connections=${PG_MAX_CONNECTIONS:-200}
|
||||
- -c
|
||||
- shared_buffers=${PG_SHARED_BUFFERS:-256MB}
|
||||
- -c
|
||||
- shared_preload_libraries=pg_stat_statements
|
||||
- -c
|
||||
- pg_stat_statements.track=top
|
||||
- -c
|
||||
- track_io_timing=on
|
||||
- -c
|
||||
- idle_in_transaction_session_timeout=10s
|
||||
environment:
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets: [postgres_password]
|
||||
volumes: [pgdata:/var/lib/postgresql/data]
|
||||
shm_size: 256m
|
||||
cpuset: ${PG_CPUSET:-}
|
||||
healthcheck:
|
||||
test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "messenger", "-d", "messenger"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
start_period: 10s
|
||||
start_interval: 200ms
|
||||
stop_grace_period: 10s
|
||||
restart: unless-stopped
|
||||
networks: [backend]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${PG_CPUS:-2}", memory: "${PG_MEMORY:-1g}"}
|
||||
|
||||
valkey:
|
||||
image: valkey/valkey:8.1.11-alpine@sha256:2602ace2be6569bc2bbb06f873776516ab9089821525be34f4305c67eb9db02a
|
||||
user: "999:1000"
|
||||
command:
|
||||
- valkey-server
|
||||
- /run/secrets/valkey.conf
|
||||
- --appendonly
|
||||
- "yes"
|
||||
- --appendfsync
|
||||
- always
|
||||
- --maxmemory
|
||||
- 64mb
|
||||
- --maxmemory-policy
|
||||
- volatile-lru
|
||||
secrets: [valkey.conf]
|
||||
volumes: [valkeydata:/data]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)\" valkey-cli ping | grep -q PONG"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
stop_grace_period: 10s
|
||||
restart: unless-stopped
|
||||
networks: [backend]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128m}
|
||||
|
||||
s3:
|
||||
image: rustfs/rustfs:1.0.4@sha256:ed9210d6411d77ffceb70d94b964a3cb7d225983368bc25bebe01e995293dcc2
|
||||
environment:
|
||||
RUSTFS_ACCESS_KEY_FILE: /run/secrets/s3_root_user
|
||||
RUSTFS_SECRET_KEY_FILE: /run/secrets/s3_root_password
|
||||
RUSTFS_ADDRESS: ":9000"
|
||||
RUSTFS_CONSOLE_ENABLE: "false"
|
||||
RUSTFS_REGION: ${S3_REGION:-us-east-1}
|
||||
RUSTFS_OBS_LOG_DIRECTORY: ""
|
||||
RUSTFS_OBS_LOGGER_LEVEL: ${S3_LOG_LEVEL:-warn}
|
||||
secrets: [s3_root_user, s3_root_password]
|
||||
volumes: [s3data:/data]
|
||||
cpuset: ${S3_CPUSET:-}
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=64m"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "http://127.0.0.1:9000/health/ready"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
start_period: 20s
|
||||
stop_grace_period: 10s
|
||||
restart: unless-stopped
|
||||
networks: [backend]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${S3_CPUS:-1}", memory: "${S3_MEMORY:-512m}"}
|
||||
|
||||
reconciler:
|
||||
<<: *app
|
||||
pull_policy: never
|
||||
profiles: [reconcile]
|
||||
init: true
|
||||
entrypoint: ["python", "-m", "messenger.attachments.entrypoints.reconcile"]
|
||||
command: ["--dry-run"]
|
||||
environment:
|
||||
<<: *s3-env
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_reconciler_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_reconciler_secret_access_key
|
||||
S3_READ_TIMEOUT_SECONDS: ${RECONCILE_S3_READ_TIMEOUT_SECONDS:-10}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||
secrets: [database_url, s3_reconciler_access_key_id, s3_reconciler_secret_access_key]
|
||||
healthcheck:
|
||||
disable: true
|
||||
restart: "no"
|
||||
read_only: true
|
||||
cpuset: ${RECONCILE_CPUSET:-}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
s3:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${RECONCILE_CPUS:-1}", memory: "${RECONCILE_MEMORY:-256m}"}
|
||||
|
||||
s3-init:
|
||||
<<: *s3-client
|
||||
entrypoint: ["/bin/sh", "/s3/init.sh"]
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
|
||||
s3-cli:
|
||||
<<: *s3-client
|
||||
profiles: [tools]
|
||||
entrypoint: ["/bin/sh", "/s3/cli.sh"]
|
||||
|
||||
k6:
|
||||
image: grafana/k6:2.3.0@sha256:2dd4756ec6e14e62778916e1eb850108e4b499304c02df56760fa0bdb0fba0b8
|
||||
profiles: [bench]
|
||||
environment:
|
||||
BASE_URL: http://lb:8080
|
||||
volumes: [./infra/k6:/scripts:ro]
|
||||
networks: [edge]
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${K6_CPUS:-2}", memory: "${K6_MEMORY:-512m}"}
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
valkey.conf:
|
||||
file: ./secrets/valkey.conf
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
cursor_secret:
|
||||
file: ./secrets/cursor_secret
|
||||
s3_root_user:
|
||||
file: ./secrets/s3_root_user
|
||||
s3_root_password:
|
||||
file: ./secrets/s3_root_password
|
||||
s3_access_key_id:
|
||||
file: ./secrets/s3_access_key_id
|
||||
s3_secret_access_key:
|
||||
file: ./secrets/s3_secret_access_key
|
||||
s3_reconciler_access_key_id:
|
||||
file: ./secrets/s3_reconciler_access_key_id
|
||||
s3_reconciler_secret_access_key:
|
||||
file: ./secrets/s3_reconciler_secret_access_key
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
valkeydata:
|
||||
s3data:
|
||||
|
||||
networks:
|
||||
edge:
|
||||
backend:
|
||||
internal: true
|
||||
@@ -34,7 +34,8 @@
|
||||
"chat_id": "33333333-3333-4333-8333-333333333333",
|
||||
"sender_id": "11111111-1111-4111-8111-111111111111",
|
||||
"text": "Привет, Боб!",
|
||||
"created_at": "2026-09-01T12:00:00Z"
|
||||
"created_at": "2026-09-01T12:00:00Z",
|
||||
"attachment_ids": []
|
||||
},
|
||||
"MessagePage": {
|
||||
"items": [
|
||||
@@ -43,7 +44,8 @@
|
||||
"chat_id": "33333333-3333-4333-8333-333333333333",
|
||||
"sender_id": "11111111-1111-4111-8111-111111111111",
|
||||
"text": "Привет, Боб!",
|
||||
"created_at": "2026-09-01T12:00:00Z"
|
||||
"created_at": "2026-09-01T12:00:00Z",
|
||||
"attachment_ids": []
|
||||
}
|
||||
],
|
||||
"next_cursor": null
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"lab": 2,
|
||||
"lab": 4,
|
||||
"kind": "requirements, not runnable deployment",
|
||||
"required_for_grade_3": [
|
||||
{
|
||||
"role": "api",
|
||||
"count_min": 1,
|
||||
"count_min": 2,
|
||||
"student_implements": true,
|
||||
"persistent_local_state": false
|
||||
},
|
||||
@@ -12,6 +12,21 @@
|
||||
"role": "postgres",
|
||||
"purpose": "users/chats/membership/messages/metadata",
|
||||
"persistent_volume": true
|
||||
},
|
||||
{
|
||||
"role": "load_balancer",
|
||||
"public_entrypoint": true,
|
||||
"backend_readiness": true
|
||||
},
|
||||
{
|
||||
"role": "s3",
|
||||
"choose_one": [
|
||||
"MinIO",
|
||||
"SeaweedFS",
|
||||
"RustFS"
|
||||
],
|
||||
"private_bucket": true,
|
||||
"persistent_volume": true
|
||||
}
|
||||
],
|
||||
"optional_components": [
|
||||
|
||||
+1487
-7
File diff suppressed because it is too large
Load Diff
+72
-2
@@ -1,5 +1,75 @@
|
||||
# Текущая серия SQLAlchemy
|
||||
|
||||
Новые результаты находятся в [sqlalchemy-2026-11-06](sqlalchemy-2026-11-06/).
|
||||
Уровень 3: [критерии, команды, результаты](sqlalchemy-2026-11-06/grade3/NOTES.md).
|
||||
Уровень 4: [отказы, память и уборка](sqlalchemy-2026-11-06/grade4/NOTES.md).
|
||||
Трек 2: [корректность и стоимость SQLAlchemy](sqlalchemy-2026-11-06/track5/NOTES.md).
|
||||
Все 21 замечание: [проверяемые основания](sqlalchemy-2026-11-06/REVIEW-CLOSURE.md).
|
||||
Полные SHA, UTC, параметры и exit code — в новых raw *.txt; API-код перенесён из
|
||||
immutable `f591fa64e525679a31c9db7f942d36c789e1a12f`.
|
||||
Индекс ниже сохранён как исторический: результаты asyncpg не выдаются за новые измерения.
|
||||
|
||||
# Доказательства
|
||||
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
Обезличенные результаты прогонов лабы 4. Пользователи, чаты, тексты и изображения синтетические. Паролей, токенов,
|
||||
ключей S3, `.env`, содержимого `secrets/`, ключей объектов в журналах и дампов здесь нет. В первой строке каждого
|
||||
отчёта `*.txt` стоят дата (UTC) и коммит прогона. В JSON сценариев (`failover-upload.json`, `s3-outage.json`,
|
||||
`reconcile/demo.json`, `reconcile/cost/summary.json`) поля `date`/`started_at` и `commit` лежат внутри, у прочих
|
||||
JSON коммит указан в таблицах ниже. Проверки через балансировщик шли на порт 18084 (`LB_HTTP_PORT`, потому что 8080
|
||||
на машине занят стендами других лаб): цели `make` берут `BASE_URL` из `docker compose port lb 8080`. Hostname
|
||||
реплики = `X-Instance-Id`, ID контейнеров меняются между прогонами.
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
Код приложения последний раз менялся в `3de1dcd`, стенд (`compose.yaml`, `infra/`) — в `2891b37`, обвязка
|
||||
(`scripts/`, `Makefile`) — в `6ffb90d`. Всё ниже снято на этом коде.
|
||||
|
||||
Трек 2 снят 30.10 на `61dcb6b`, двумя свежими стендами (`make reset-data`, `make up`, `make test`): сначала
|
||||
`make reconcile-demo`, затем `make reconcile-cost`. Уровни «3» и «4» сняты после трека одной серией на `<SERIES>`.
|
||||
Порядок серии: `make reset-data`, `make up`, затем `make test`, `stack-evidence`, `limits`, `lb-check`,
|
||||
`scenario SCENARIO=failover-upload`, `failover-evidence`, `failover-evidence SHIFT=1`, `persistence-evidence`,
|
||||
`scenario SCENARIO=s3-outage`, `s3-check`, `retry-check`, `upload-faults`, `faults-evidence`, `attachments-evidence`,
|
||||
`storage-evidence`, три прогона `upload-memory` и `mmap-32m`, `overload-leftovers`, `load-evidence`. Без стенда сняты
|
||||
`contract-checks.txt` и `student-tests.txt`. `clean-clone.txt` снят в отдельном клоне со своим compose-проектом
|
||||
после серии, на `<CLONE>`.
|
||||
|
||||
## Уровень «3» и перенос лабы 3
|
||||
|
||||
| Файл | Что доказывает | Команда | Коммит |
|
||||
| --- | --- | --- | --- |
|
||||
| `clean-clone.txt` | запуск из свежего clone на пустых volumes: секреты, `config`, `make up` с миграциями `0001`–`0004` и `s3-init`, smoke, persistence, failover, `restore`, `failover-upload`, `s3-outage`, `s3-check`, `reconcile`, повтор миграций, `make down` (volumes остаются), `make reset-data` (volumes удалены); сырой вывод каждой команды | `make clean-clone-evidence LB_HTTP_PORT=18084 LB_STATS_PORT=24084` (`scripts/clean-clone.sh`) | `<CLONE>` |
|
||||
| `contract-checks.txt` | `make check`, `make validate` (`openapi-spec-validator` 0.7.2 из `.venv`); `git diff --stat upstream/main` контракта, публичных тестов и задания (пусто) и `.github` (только свой CI job) | команды внутри файла | `<SERIES>` |
|
||||
| `student-tests.txt` | `make lint` и все собственные тесты по именам, включая адаптер S3 против RustFS | `make student-test PYTEST_ARGS='-v --no-header'` | `<SERIES>` |
|
||||
| `smoke.txt` | публичный smoke через LB, ветка `LAB ≥ 4` | `make test` | `<SERIES>` |
|
||||
| `stack.txt` | сервисы, порты только у `lb`, `container_name` 0, `docker port` реплик пуст, hostname ↔ `X-Instance-Id`, лимиты, сети, uid, взгляд LB | `make stack-evidence` | `<SERIES>` |
|
||||
| `environment.txt` | host, Docker, образы по digest, версии Python, HAProxy, RustFS и пакетов, uid процессов | `make stack-evidence` | `<SERIES>` |
|
||||
| `limits.txt` | лимиты CPU/RAM всех сервисов (объявлены и применены), порты только у LB на `127.0.0.1`, секреты (root-ключи S3 только у `s3`, `s3-init`, `s3-cli`; у `reconciler` свой ключ), пользователь сервисов, volumes и сети по политике | `make limits` | `<SERIES>` |
|
||||
| `lb-check.json` | 40 `GET /users/me` одним токеном — 20 + 20 по репликам; 20 раундов × 8 параллельных POST с одним ключом — 160 × `201`, одна копия, `409` на другое тело | `make lb-check` | `<SERIES>` |
|
||||
| `failover-upload.json` | upload → остановка принявшей реплики → скачивание через другую, SHA-256; `docker inspect` обеих реплик в момент скачивания (target `exited`, сосед `running`, `StartedAt`/`FinishedAt`) и после возврата | `make scenario SCENARIO=failover-upload` | `<SERIES>` |
|
||||
| `failover-<id>.txt` (две) | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` для каждой реплики: `docker inspect` до/после, остановлен именно target, его журнал остановки, `restore` | `make failover-evidence`, затем `make failover-evidence SHIFT=1` | `<SERIES>` |
|
||||
| `persistence.txt` | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` и `StartedAt` всех контейнеров до и после | `make persistence-evidence` | `<SERIES>` |
|
||||
| `s3-outage.json` | S3 остановлен (`docker inspect` контейнера `s3` в это время): upload и `/content` `503` с временем ответа, метаданные, текст и readiness, возврат S3 и скачивание с тем же SHA-256 | `make scenario SCENARIO=s3-outage` | `<SERIES>` |
|
||||
| `storage-layout.txt` | `\d attachments` и `\d message_attachments`, `bytea` всей схемы, строки по статусам и объекты bucket, сверка SHA-256 вне API, `ro` и mounts реплик, volume `s3`, секреты сервисов | `make attachments-evidence` | `<SERIES>` |
|
||||
| `schema.txt`, `migrations.txt`, `kdf.txt`, `secrets.txt` | `\d+` всех таблиц и применённые миграции; повтор `migrate` → `up to date` при тех же счётчиках; Argon2id и 32-байтовые хеши токенов; секреты, `.env` и volumes не в Git | `make storage-evidence` | `<SERIES>` |
|
||||
| `retry.json` | потерянный ответ: запись ждёт блокировку строки чата дольше таймаута клиента, повтор тем же ключом через LB — на живой и на убитой реплике; `201`, одна копия | `make retry-check` | `<SERIES>` |
|
||||
|
||||
## Уровень «4»
|
||||
|
||||
| Файл | Что доказывает | Команда | Коммит |
|
||||
| --- | --- | --- | --- |
|
||||
| `upload-faults.txt` | 36 ошибочных запросов через LB без `5xx`; отказ `COMMIT` после `PUT` → немедленная компенсация; реплика убита между `PUT` и `COMMIT` → уборка после grace; обрыв и зависание тела | `make upload-faults` | `<SERIES>` |
|
||||
| `faults.txt` | все проверки стенда под маркером `stack`: тесты лаб 2–3 (гонка регистрации, остановка Valkey и PostgreSQL, рестарты, срок сессии) и `test_attachment_faults.py`, включая `401` раньше `413` и медленные upload и скачивание 3 MiB дольше таймаута запроса | `make faults-evidence` | `<SERIES>` |
|
||||
| `s3-security.txt` | нет host-портов у `s3`, консоль закрыта изнутри и из сети стенда, `s3-init` повторно дважды без изменений, права ключей API и сверки (разрешено и `AccessDenied`), анонимный доступ, снимок политик и пользователей без секретов и дат (валидный JSON) | `make s3-check` | `<SERIES>` |
|
||||
| `upload-memory/run{1,2,3}/` | три прогона матрицы: 64 и 3 слота × 1 и 10 MiB × 10/20/40 одновременных загрузок; `summary.txt` и JSON на точку (ответы, задержки, пик `memory.peak` реплик и LB, `oom_kill`) | `make upload-memory ARGS='--out evidence/upload-memory/runN'` | `<SERIES>` |
|
||||
| `upload-memory/mmap-32m/` | 3 слота, 10 MiB, порог `mmap` glibc 32 MiB вместо 128 KiB | `MALLOC_MMAP_THRESHOLD_=33554432 python3 scripts/upload_memory.py --slots 3 --sizes 10485760 --out evidence/upload-memory/mmap-32m` | `<SERIES>` |
|
||||
| `overload-leftovers.txt` | после серии памяти: невидимые намерения от `503` по таймауту, их вид в `make reconcile`, удаление уборкой после grace 900 с, сверка после | `make overload-leftovers` | `<SERIES>` |
|
||||
| `load.txt`, `load/run{1,2,3}.json` | нагрузка записи сообщений `tests/load.py` (64 потока, 8 с, 3 повтора) клиентом-контейнером в сети `<проект>_edge`: полная команда клиента, сырой вывод `load.py`, `docker stats` стенда и клиента, статусы `request.handled` реплик | `make load-evidence` | `<SERIES>` |
|
||||
| `load/host-attempt.txt` | отброшенная попытка той же нагрузки с хоста macOS (30.10, до этой серии): клиентские ошибки соединения при исчерпании эфемерных портов, ни одного `5xx` на репликах; строки перенесены из вывода консоли | команды внутри файла | `81dd816` |
|
||||
|
||||
## Трек 2 «Согласованность двух хранилищ»
|
||||
|
||||
`reconcile/` — сценарий трека и матрица стоимости; состав и поля — `reconcile/README.md`.
|
||||
|
||||
| Файл | Что доказывает | Команда | Коммит |
|
||||
| --- | --- | --- | --- |
|
||||
| `reconcile/demo.json` и файлы сценария | внедрение ошибок на обеих сторонах, dry-run (счёт и множества id), `apply` дважды с журналом аудита, независимая проверка, карантин, снятие карантина только при совпавшем SHA-256, занятая блокировка, `docker stop` идущего прохода, остановленный S3, 74 прохода под загрузками | `make reconcile-demo` | `61dcb6b` |
|
||||
| `reconcile/cost/` | стоимость обхода 1k/10k/30k/100k × 3 прогона, `--deep` на всех точках, закреплённые CPU, отбраковка чужой нагрузки | `make reconcile-cost` | `61dcb6b` |
|
||||
| `reconcile/cost-b191623/`, `reconcile/cost-2026-10-29/`, `reconcile/cost-aborted/` | прошлые серии 1k/10k/30k (`b191623` — с лишней SQL-страницей; `5ca2cdc` — без отбраковки) и прерванные попытки наполнить 100k в прежних конфигурациях | `make reconcile-cost` | `b191623`, `5ca2cdc`, до `5ca2cdc` |
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
date: 2026-10-30T04:27:15Z commit: 81dd816 dir: mtusi2026lab4-clean (свой compose-проект и volumes)
|
||||
# шаги — команды блока «Запуск из чистого clone» REPORT.md; строки с пометкой «наблюдение» — проверки между шагами
|
||||
$ git clone <repo> mtusi2026lab4-clean && cd mtusi2026lab4-clean && git checkout solution/bpi2303-kostylev
|
||||
HEAD 81dd816 Archive the storage reconciler change
|
||||
$ docker volume ls -q --filter label=com.docker.compose.project=mtusi2026lab4-clean | wc -l | tr -d ' ' # наблюдение, не шаг инструкции
|
||||
0
|
||||
$ make secrets
|
||||
sh scripts/secrets.sh
|
||||
создан secrets/postgres_password
|
||||
создан secrets/database_url
|
||||
создан secrets/cursor_secret
|
||||
создан secrets/valkey_password
|
||||
создан secrets/valkey.conf
|
||||
создан secrets/cache_url
|
||||
создан secrets/s3_root_user
|
||||
создан secrets/s3_root_password
|
||||
создан secrets/s3_access_key_id
|
||||
создан secrets/s3_secret_access_key
|
||||
создан .env из .env.example
|
||||
$ sed LB_HTTP_PORT=18084 LB_STATS_PORT=24084 .env # отступление: 8080 на этой машине занят стендами других лаб
|
||||
$ git status --short --ignored secrets .env # наблюдение, не шаг инструкции
|
||||
!! .env
|
||||
!! secrets/
|
||||
$ docker compose --env-file .env config --quiet && echo valid
|
||||
valid
|
||||
$ make up
|
||||
Container mtusi2026lab4-clean-postgres-1 Healthy
|
||||
Container mtusi2026lab4-clean-s3-1 Healthy
|
||||
Container mtusi2026lab4-clean-s3-init-1 Exited
|
||||
Container mtusi2026lab4-clean-migrate-1 Exited
|
||||
Container mtusi2026lab4-clean-postgres-1 Healthy
|
||||
Container mtusi2026lab4-clean-migrate-1 Exited
|
||||
Container mtusi2026lab4-clean-valkey-1 Healthy
|
||||
Container mtusi2026lab4-clean-s3-1 Healthy
|
||||
Container mtusi2026lab4-clean-s3-init-1 Exited
|
||||
Container mtusi2026lab4-clean-api-1 Healthy
|
||||
Container mtusi2026lab4-clean-api-2 Healthy
|
||||
Container mtusi2026lab4-clean-lb-1 Healthy
|
||||
make up: 11 s (сборка образа из кэша слоёв)
|
||||
$ docker compose ps -a --format '{{.Service}} {{.State}} {{.Status}} {{.Ports}}' # наблюдение, не шаг инструкции
|
||||
api running Up 4 seconds (healthy)
|
||||
api running Up 4 seconds (healthy)
|
||||
lb running Up 10 seconds (healthy) 127.0.0.1:18084->8080/tcp, 127.0.0.1:24084->8404/tcp
|
||||
migrate exited Exited (0) 8 seconds ago
|
||||
postgres running Up 10 seconds (healthy)
|
||||
s3 running Up 10 seconds (healthy)
|
||||
s3-init exited Exited (0) 4 seconds ago
|
||||
valkey running Up 10 seconds (healthy)
|
||||
$ docker compose logs --no-log-prefix migrate s3-init | grep -v '^$' | tail -8 # наблюдение, не шаг инструкции
|
||||
{"version":"0001_init","event":"migration.applied","level":"info","ts":"2026-10-30T04:27:18.183850Z"}
|
||||
{"version":"0002_idempotency_keys","event":"migration.applied","level":"info","ts":"2026-10-30T04:27:18.183962Z"}
|
||||
{"version":"0003_attachments","event":"migration.applied","level":"info","ts":"2026-10-30T04:27:18.184008Z"}
|
||||
{"version":"0004_attachment_quarantine","event":"migration.applied","level":"info","ts":"2026-10-30T04:27:18.184039Z"}
|
||||
{"reason":"applied","event":"migration.completed","level":"info","ts":"2026-10-30T04:27:18.184066Z"}
|
||||
s3-init: bucket=messenger-attachments anonymous=private policy=messenger-api lifecycle=abort-incomplete-uploads
|
||||
$ curl -s "http://$(docker compose port lb 8404)/stats;csv" | awk -F, '$1 == "api" && $2 != "BACKEND" {print $2, $18}' | grep -v MAINT # наблюдение, не шаг инструкции
|
||||
api1 UP
|
||||
api2 UP
|
||||
$ make test
|
||||
python3 tests/smoke.py --base-url "http://127.0.0.1:18084"
|
||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:18084"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
$ docker compose ps -a --format '{{.Service}} {{.State}} {{.RunningFor}} {{.Status}}' # наблюдение, не шаг инструкции
|
||||
api running 24 seconds ago Up 3 seconds (healthy)
|
||||
api running 24 seconds ago Up 3 seconds (healthy)
|
||||
lb running 24 seconds ago Up 8 seconds (healthy)
|
||||
migrate exited 24 seconds ago Exited (0) 7 seconds ago
|
||||
postgres running 24 seconds ago Up 9 seconds (healthy)
|
||||
s3 running 24 seconds ago Up 9 seconds (healthy)
|
||||
s3-init exited 24 seconds ago Exited (0) 3 seconds ago
|
||||
valkey running 24 seconds ago Up 9 seconds (healthy)
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18084"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 128, "failed_attempts": 0, "first_recovery_seconds": 2.948}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
$ docker compose ps -a --format '{{.Service}} {{.Name}} {{.State}} {{.Status}}' api # наблюдение, не шаг инструкции
|
||||
api mtusi2026lab4-clean-api-1 running Up 19 seconds (healthy)
|
||||
api mtusi2026lab4-clean-api-2 exited Exited (0) 12 seconds ago
|
||||
$ make restore
|
||||
scripts/restore.sh
|
||||
Container mtusi2026lab4-clean-api-1 Running
|
||||
Container mtusi2026lab4-clean-api-2 Starting
|
||||
Container mtusi2026lab4-clean-api-2 Started
|
||||
Container mtusi2026lab4-clean-api-1 Waiting
|
||||
Container mtusi2026lab4-clean-api-2 Waiting
|
||||
Container mtusi2026lab4-clean-api-1 Healthy
|
||||
Container mtusi2026lab4-clean-api-2 Healthy
|
||||
$ make scenario SCENARIO=failover-upload
|
||||
{'ok': True, 'upload_instance': 'b21945b926b7', 'download_instance': '6c9bf1e3b1a6', 'sha256_equal': True, 'hook_seconds': 2.713}
|
||||
$ make scenario SCENARIO=s3-outage
|
||||
{'ok': True, 'upload': 503, 'metadata': 200, 'download': 503, 'text_message': 201, 'health_ready': 200}
|
||||
$ make s3-check
|
||||
23
|
||||
== 2026-10-30T04:28:17Z S3 privacy and bootstrap checks
|
||||
== IAM/bucket snapshot (без секретов)
|
||||
$ make reconcile
|
||||
dry-run {'objects': 5, 'rows': 6} {'pending_fresh': 1} errors 0
|
||||
$ make migrate
|
||||
docker compose run --rm migrate
|
||||
{"reason":"up to date","event":"migration.completed","level":"info","ts":"2026-10-30T04:28:21.735485Z"}
|
||||
$ docker volume ls --format '{{.Name}}' --filter label=com.docker.compose.project=mtusi2026lab4-clean # наблюдение, не шаг инструкции
|
||||
mtusi2026lab4-clean_pgdata
|
||||
mtusi2026lab4-clean_s3data
|
||||
mtusi2026lab4-clean_valkeydata
|
||||
$ make down
|
||||
1 Container mtusi2026lab4-clean-api-1 Removed
|
||||
1 Container mtusi2026lab4-clean-api-2 Removed
|
||||
1 Container mtusi2026lab4-clean-lb-1 Removed
|
||||
1 Container mtusi2026lab4-clean-migrate-1 Removed
|
||||
1 Container mtusi2026lab4-clean-postgres-1 Removed
|
||||
1 Container mtusi2026lab4-clean-s3-1 Removed
|
||||
1 Container mtusi2026lab4-clean-s3-init-1 Removed
|
||||
1 Container mtusi2026lab4-clean-valkey-1 Removed
|
||||
1 Network mtusi2026lab4-clean_backend Removed
|
||||
1 Network mtusi2026lab4-clean_edge Removed
|
||||
$ docker volume ls --format '{{.Name}}' --filter label=com.docker.compose.project=mtusi2026lab4-clean # наблюдение, не шаг инструкции
|
||||
mtusi2026lab4-clean_pgdata
|
||||
mtusi2026lab4-clean_s3data
|
||||
mtusi2026lab4-clean_valkeydata
|
||||
$ make reset-data
|
||||
Volume mtusi2026lab4-clean_pgdata Removing
|
||||
Volume mtusi2026lab4-clean_s3data Removing
|
||||
Volume mtusi2026lab4-clean_valkeydata Removing
|
||||
Volume mtusi2026lab4-clean_pgdata Removed
|
||||
Volume mtusi2026lab4-clean_s3data Removed
|
||||
Volume mtusi2026lab4-clean_valkeydata Removed
|
||||
$ docker volume ls -q --filter label=com.docker.compose.project=mtusi2026lab4-clean | wc -l | tr -d ' ' # наблюдение, не шаг инструкции
|
||||
0
|
||||
@@ -0,0 +1,12 @@
|
||||
date: 2026-10-30T04:24:13Z commit: 81dd816
|
||||
$ make check
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
$ make validate # openapi-spec-validator 0.7.2 из .venv (make install)
|
||||
.venv/bin/python scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
$ git diff --stat upstream/main -- contracts tests README.md COURSE.md CONTRIBUTING.md MAINTAINERS.md lab.json compose.example.yaml Dockerfile.example # контракт, публичные тесты и задание не менялись
|
||||
(пусто)
|
||||
$ git diff --stat upstream/main -- .github # только свой CI job
|
||||
.github/workflows/application.yml | 93 +++++++++++++++++++++++++++++++++++++++
|
||||
1 file changed, 93 insertions(+)
|
||||
@@ -0,0 +1,41 @@
|
||||
date: 2026-10-30T04:29:05Z commit: 81dd816
|
||||
host: Apple M4 Max, 16 CPU, 48 GiB RAM, macOS 15.1
|
||||
docker: 28.3.2, VM: 16 CPU, 8217190400 bytes
|
||||
compose: 2.38.2-desktop.1
|
||||
images:
|
||||
image: ${API_IMAGE:-mtusi-messenger:${COMPOSE_PROJECT_NAME}}
|
||||
image: rustfs/rc:v0.1.36@sha256:ab024bfebee49a750ce886b4c70963ccd9ddaa03f491704a90710641d7a26699
|
||||
image: haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b
|
||||
image: postgres:17.11-alpine@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b
|
||||
image: valkey/valkey:8.1.11-alpine@sha256:2602ace2be6569bc2bbb06f873776516ab9089821525be34f4305c67eb9db02a
|
||||
image: rustfs/rustfs:1.0.4@sha256:ed9210d6411d77ffceb70d94b964a3cb7d225983368bc25bebe01e995293dcc2
|
||||
image: grafana/k6:2.3.0@sha256:2dd4756ec6e14e62778916e1eb850108e4b499304c02df56760fa0bdb0fba0b8
|
||||
FROM python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS builder
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.9.7@sha256:ba4857bf2a068e9bc0e64eed8563b065908a4cd6bfb66b531a9c424c8e25e142 /uv /usr/local/bin/uv
|
||||
FROM python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS runtime
|
||||
python in image: Python 3.14.7
|
||||
haproxy: HAProxy version 3.2.26-3e0f11a 2026/10/14 - https://haproxy.org/
|
||||
rustfs: rustfs 1.0.4
|
||||
packages (uv.lock):
|
||||
fastapi 0.141.1
|
||||
uvicorn 0.54.0
|
||||
uvicorn-worker 0.4.0
|
||||
gunicorn 26.2.0
|
||||
asyncpg 0.32.0
|
||||
argon2-cffi 25.1.0
|
||||
pydantic 2.13.5
|
||||
pydantic-settings 2.15.0
|
||||
dishka 1.10.1
|
||||
structlog 26.1.0
|
||||
redis 8.1.0
|
||||
aiobotocore 3.10.0
|
||||
botocore 1.43.117
|
||||
aiohttp 3.14.5
|
||||
pillow 13.0.0
|
||||
process users (service uid command):
|
||||
api 10001 python
|
||||
lb 99 haproxy
|
||||
postgres 70 postgres
|
||||
s3 10001 rustfs
|
||||
valkey 999 tini
|
||||
valkey 999 valkey-server
|
||||
@@ -0,0 +1,38 @@
|
||||
date: 2026-10-30T04:29:33Z commit: 81dd816
|
||||
== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt
|
||||
0cc3ee358e59 running started=2026-10-30T04:28:59.851144131Z finished=0001-01-01T00:00:00Z
|
||||
899a952a5a21 running started=2026-10-30T04:29:31.104320507Z finished=2026-10-30T04:29:18.153900709Z
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18084"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 128, "failed_attempts": 0, "first_recovery_seconds": 2.883}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
== after: api replicas
|
||||
0cc3ee358e59 exited started=2026-10-30T04:28:59.851144131Z finished=2026-10-30T04:29:36.57527926Z
|
||||
899a952a5a21 running started=2026-10-30T04:29:31.104320507Z finished=2026-10-30T04:29:18.153900709Z
|
||||
== stopped replica: 0cc3ee358e59; shutdown: signal, drain window with readiness 503, close, exit
|
||||
{"event":"Handling signal: term","level":"info","ts":"2026-10-30T04:29:34.045936Z"}
|
||||
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-10-30T04:29:34.072243Z"}
|
||||
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-10-30T04:29:34.126665Z"}
|
||||
{"method":"GET","route":"/health/ready","status":503,"request_id":"6362781446fb427cbee670871ce5ef51","duration_ms":1.463,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:34.446815Z"}
|
||||
{"method":"GET","route":"/health/ready","status":503,"request_id":"0d9cf1c47fca4ec98ed599b113cd93db","duration_ms":0.79,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:34.950067Z"}
|
||||
{"event":"Shutting down","level":"info","ts":"2026-10-30T04:29:36.079497Z"}
|
||||
{"event":"Shutting down","level":"info","ts":"2026-10-30T04:29:36.138465Z"}
|
||||
{"event":"service.stopped","level":"info","ts":"2026-10-30T04:29:36.188615Z"}
|
||||
{"event":"Finished server process [20]","level":"info","ts":"2026-10-30T04:29:36.188874Z"}
|
||||
{"event":"service.stopped","level":"info","ts":"2026-10-30T04:29:36.247500Z"}
|
||||
{"event":"Finished server process [19]","level":"info","ts":"2026-10-30T04:29:36.247910Z"}
|
||||
{"event":"Worker (pid:20) was sent SIGTERM!","level":"info","ts":"2026-10-30T04:29:36.250957Z"}
|
||||
{"event":"Worker (pid:19) was sent SIGTERM!","level":"info","ts":"2026-10-30T04:29:36.357386Z"}
|
||||
{"event":"Shutting down: Master","level":"info","ts":"2026-10-30T04:29:36.468491Z"}
|
||||
$ scripts/restore.sh
|
||||
Container mtusi2026lab4-api-2 Running
|
||||
Container mtusi2026lab4-api-1 Starting
|
||||
Container mtusi2026lab4-api-1 Started
|
||||
Container mtusi2026lab4-api-2 Waiting
|
||||
Container mtusi2026lab4-api-1 Waiting
|
||||
Container mtusi2026lab4-api-2 Healthy
|
||||
Container mtusi2026lab4-api-1 Healthy
|
||||
== after restore
|
||||
0cc3ee358e59 running started=2026-10-30T04:29:49.45750296Z finished=2026-10-30T04:29:36.57527926Z
|
||||
899a952a5a21 running started=2026-10-30T04:29:31.104320507Z finished=2026-10-30T04:29:18.153900709Z
|
||||
@@ -0,0 +1,39 @@
|
||||
date: 2026-10-30T04:29:14Z commit: 81dd816
|
||||
== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt
|
||||
0cc3ee358e59 running started=2026-10-30T04:28:59.851144131Z finished=0001-01-01T00:00:00Z
|
||||
899a952a5a21 running started=2026-10-30T04:29:11.286693179Z finished=2026-10-30T04:29:11.040183429Z
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18084"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 129, "failed_attempts": 0, "first_recovery_seconds": 2.885}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
== after: api replicas
|
||||
0cc3ee358e59 running started=2026-10-30T04:28:59.851144131Z finished=0001-01-01T00:00:00Z
|
||||
899a952a5a21 exited started=2026-10-30T04:29:11.286693179Z finished=2026-10-30T04:29:18.153900709Z
|
||||
== stopped replica: 899a952a5a21; shutdown: signal, drain window with readiness 503, close, exit
|
||||
{"event":"Handling signal: term","level":"info","ts":"2026-10-30T04:29:15.605798Z"}
|
||||
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-10-30T04:29:15.638898Z"}
|
||||
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-10-30T04:29:15.701830Z"}
|
||||
{"method":"GET","route":"/health/ready","status":503,"request_id":"b416afb071ad426a9dde141e952d697f","duration_ms":0.823,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:16.528606Z"}
|
||||
{"method":"GET","route":"/health/ready","status":503,"request_id":"3fe4a4c39cb24a219d3a393a1c0332f0","duration_ms":1.591,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:17.038813Z"}
|
||||
{"method":"GET","route":"/health/ready","status":503,"request_id":"152273913ad34012bf5eaf31432490ae","duration_ms":0.263,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:17.388797Z"}
|
||||
{"event":"Shutting down","level":"info","ts":"2026-10-30T04:29:17.642635Z"}
|
||||
{"event":"Shutting down","level":"info","ts":"2026-10-30T04:29:17.714902Z"}
|
||||
{"event":"service.stopped","level":"info","ts":"2026-10-30T04:29:17.757838Z"}
|
||||
{"event":"Finished server process [20]","level":"info","ts":"2026-10-30T04:29:17.758374Z"}
|
||||
{"event":"Worker (pid:20) was sent SIGTERM!","level":"info","ts":"2026-10-30T04:29:17.826021Z"}
|
||||
{"event":"service.stopped","level":"info","ts":"2026-10-30T04:29:17.832655Z"}
|
||||
{"event":"Finished server process [13]","level":"info","ts":"2026-10-30T04:29:17.833005Z"}
|
||||
{"event":"Worker (pid:13) was sent SIGTERM!","level":"info","ts":"2026-10-30T04:29:17.927620Z"}
|
||||
{"event":"Shutting down: Master","level":"info","ts":"2026-10-30T04:29:18.029723Z"}
|
||||
$ scripts/restore.sh
|
||||
Container mtusi2026lab4-api-1 Running
|
||||
Container mtusi2026lab4-api-2 Starting
|
||||
Container mtusi2026lab4-api-2 Started
|
||||
Container mtusi2026lab4-api-2 Waiting
|
||||
Container mtusi2026lab4-api-1 Waiting
|
||||
Container mtusi2026lab4-api-2 Healthy
|
||||
Container mtusi2026lab4-api-1 Healthy
|
||||
== after restore
|
||||
0cc3ee358e59 running started=2026-10-30T04:28:59.851144131Z finished=0001-01-01T00:00:00Z
|
||||
899a952a5a21 running started=2026-10-30T04:29:31.104320507Z finished=2026-10-30T04:29:18.153900709Z
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"ok": true,
|
||||
"scenario": "failover-upload",
|
||||
"upload_instance": "899a952a5a21",
|
||||
"download_instance": "0cc3ee358e59",
|
||||
"sha256_equal": true,
|
||||
"hook_seconds": 2.72,
|
||||
"download_ok_after_seconds": 2.73,
|
||||
"restored": true
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
date: 2026-10-30T04:31:11Z commit: 81dd816
|
||||
$ make test-faults
|
||||
BASE_URL="http://127.0.0.1:18084" .venv/bin/pytest -m stack -v -s student-tests/stack
|
||||
============================= test session starts ==============================
|
||||
platform darwin -- Python 3.14.5, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv/bin/python
|
||||
cachedir: .pytest_cache
|
||||
rootdir: <repo>
|
||||
configfile: pyproject.toml
|
||||
plugins: asyncio-1.4.0, anyio-4.15.1
|
||||
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
|
||||
collecting ... collected 17 items
|
||||
|
||||
student-tests/stack/test_attachment_faults.py::test_user_errors_never_become_500 10 MiB + 1 с Content-Length, тело не отправлено: 413
|
||||
10 MiB + 1 chunked: 413
|
||||
PNG 100000×100000 (бомба): 413
|
||||
PNG 8001×5000: 413
|
||||
обрезанный PNG: 415
|
||||
обрезанный JPEG: 415
|
||||
JPEG как image/png: 415
|
||||
GIF как image/png: 415
|
||||
WebP как image/png: 415
|
||||
текст как image/png: 415
|
||||
PNG как image/jpeg: 415
|
||||
пустое тело: 415
|
||||
application/octet-stream: 415
|
||||
без Content-Type: 415
|
||||
filename='../a.png': 400
|
||||
filename='a/b.png': 400
|
||||
filename='a\\b.png': 400
|
||||
filename='a\x00.png': 400
|
||||
filename='a\x01.png': 400
|
||||
filename='a\x7f.png': 400
|
||||
filename='': 400
|
||||
filename=' ': 400
|
||||
filename='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: 400
|
||||
filename=None: 400
|
||||
посторонний: upload в чужой чат: 404
|
||||
посторонний: метаданные: 404
|
||||
посторонний: /content: 404
|
||||
посторонний: ссылка на чужое вложение: 404
|
||||
вложение другого чата: 404
|
||||
неизвестное вложение: 404
|
||||
11 вложений: 400
|
||||
повтор вложения: 400
|
||||
невалидный UUID: 400
|
||||
пустой текст без вложений: 400
|
||||
невалидный id вложения: 400
|
||||
variant=thumbnail: 400
|
||||
строк вложений в чате: 2 (= ответов 201); ответов в журнале реплик: 54, из них 5xx: 0
|
||||
PASSED
|
||||
student-tests/stack/test_attachment_faults.py::test_commit_failure_is_compensated_at_once отказ COMMIT после записи объекта: 503 unavailable
|
||||
сразу после ответа: строка нет, объект HEAD 404
|
||||
журнал: audit.attachment_discarded reason=compensation
|
||||
PASSED
|
||||
student-tests/stack/test_attachment_faults.py::test_crash_between_put_and_commit_is_swept_after_grace реплика 899a952a5a21 убита между PUT и COMMIT, клиент получил 502
|
||||
реплика 0cc3ee358e59 убита между PUT и COMMIT, клиент получил 502
|
||||
остаток после падения: строка pending, объект HEAD 200
|
||||
остаток после падения: строка pending, объект HEAD 200
|
||||
старше grace: строка убрана через 26.2 с, объект HEAD 404
|
||||
моложе grace: строка pending, объект HEAD 200
|
||||
тот же после сдвига: убран через 1.0 с, объект HEAD 404
|
||||
готовое вложение в сообщении со сдвинутым created_at скачивается, SHA-256 совпадает
|
||||
PASSED
|
||||
student-tests/stack/test_attachment_faults.py::test_aborted_upload_leaves_nothing обрыв после 256 KiB из 5 MiB: статус в журнале реплики [400], намерение None
|
||||
PASSED
|
||||
student-tests/stack/test_attachment_faults.py::test_stalled_upload_is_cut_and_leaves_nothing тело зависло после 1 KiB: 503 unavailable за 8.01 с
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_registration_race_yields_exactly_one_user гонка 50 регистраций: 201×1, 409×49
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_chat_creation_rolls_back_on_unknown_member чат с несуществующим участником: 400 invalid_request
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_wrong_password_and_unknown_user_get_same_basic_challenge неверный пароль: 401 за 0.011 с
|
||||
неизвестный пользователь: 401 за 0.011 с
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_logout_then_token_is_dead logout: 204, затем 401, повтор 401
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_valkey_serves_repeated_checks 5 проверок токена: keyspace_hits 119 → 124
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_valkey_stopped_is_bypassed_but_logout_waits valkey остановлен, действующий токен: 200 за 0.004 с
|
||||
valkey остановлен, неизвестный токен: 401 за 0.003 с
|
||||
valkey остановлен: ready 200, вход 201, выход 503
|
||||
valkey снова запущен: повторный выход 204
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_valkey_restart_keeps_cache_and_revocations рестарт valkey: ключей 45 → 45
|
||||
рестарт valkey: живой 200, отозванный 401
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_valkey_flushall_loses_nothing FLUSHALL: живой 200, отозванный 401
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_postgres_stopped_gives_bounded_503_and_recovers postgres остановлен, ready: 503 за 0.004 с
|
||||
postgres остановлен, me: 503 за 0.003 с
|
||||
postgres остановлен, stranger: 503 за 0.002 с
|
||||
postgres остановлен, login: 503 за 0.002 с
|
||||
postgres остановлен, register: 503 за 0.015 с
|
||||
live внутри реплики 200; LB исключил все реплики ещё через 1.16 с
|
||||
live через LB без реплик: 503 за 0.000 с
|
||||
postgres запущен: готовность через 1.6 с, прежний токен 200
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_api_restart_keeps_session_without_extending_it рестарт api: готовность через 2.3 с, токен 200
|
||||
expires_at при входе 2026-10-30T05:32:12.249834Z, в БД после рестарта 2026-10-30T05:32:12.249834Z
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_full_restart_keeps_session_until_logout restart.sh: готовность через 0.0 с, прежний токен 200, выход 204, затем 401
|
||||
PASSED
|
||||
student-tests/stack/test_faults.py::test_session_expires_after_restart_at_original_time срок сессии сокращён до 20 с, рестарт api: готовность через 3.1 с, до срока 200, после срока 401
|
||||
PASSED
|
||||
|
||||
======================== 17 passed in 98.43s (0:01:38) =========================
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,52 @@
|
||||
# Поздний перенос ЛР3 → ЛР4
|
||||
|
||||
Исходный source SHA: `f591fa64e525679a31c9db7f942d36c789e1a12f`.
|
||||
Финальный source SHA: `ba78cf6da439a4ec60fd59389583b38285b0b2b1`.
|
||||
Источник только immutable snapshot `lab3-ba78cf6da439a4ec60fd59389583b38285b0b2b1`
|
||||
в `.pipeline/.runs/labs/snapshots/`; изменяемый каталог ЛР3 не использован.
|
||||
База ЛР4: `d7478726a85791c21e065d58f610735a9e687433`, чистое дерево до начала.
|
||||
План зафиксирован в `f0fc084`; change `forward-lab3-final-review-fixes`.
|
||||
|
||||
Полный список всех 214 изменённых файлов, их source blob и решение для каждого:
|
||||
[manifest](forward-final-2026-11-06/source-manifest.json). Неучтённых путей нет.
|
||||
|
||||
## Применимые исправления
|
||||
|
||||
| Источник | Файлы ЛР4 | Решение |
|
||||
| --- | --- | --- |
|
||||
| `2af24d7`: отзыв сессии и потеря кэша | identity/application/handlers.py; identity/infrastructure/postgres.py, valkey.py | DELETE в транзакции до инвалидации, FOR KEY SHARE при cache miss, nonce reservation и атомарные Lua. Закрывает возврат отозванного токена при flush/evict/replacement и до COMMIT. |
|
||||
| `2af24d7`: JSON ошибок LB | infra/haproxy/haproxy.cfg | json(ascii) для поля request_id в 502/503/504; заголовок сохранён. Буферы, таймауты и политика POST/upload ЛР4 не затронуты. |
|
||||
| `e66e2d7`: NUL | identity/domain/values.py; identity/entrypoints/authentication.py; messaging/domain/values.py | Отклонение до SQL, 400 для display_name/title/text, 401 для Basic username. MessageText вручную объединён: text="" с вложением по-прежнему допустим. |
|
||||
| `7e19d4e`: non-ASCII Basic | identity/entrypoints/authentication.py | Проверка encoded.isascii до Base64, одинаковый 401 вместо 500. |
|
||||
| Регрессии источника | student-tests/api/test_cache.py, test_sessions.py, test_nul_validation.py; unit/test_authentication.py, test_haproxy_errors.py, test_nul_inputs.py, test_session_cache.py | Перенесены все 7 файлов; проверяют гонки, rollback, TTL, NUL, malformed Basic и JSON ошибок. |
|
||||
| Переносимые сценарии внутри source evidence | student-tests/tools/forward_network.py, tools/lb_errors/ | Сценарии выполняются заново; изменены порт/образ/project, сервер fixture использует stdlib socketserver. Исходное сырьё не скопировано как результат ЛР4. |
|
||||
| OpenSpec | 6 исходных capabilities; 3 source archives (19 файлов) | Дельты применяются к прежним префиксам. В history сохранены все сценарии attachment_ids. Архивы ЛР3 сохранены побайтно с lab:3, это история источника, не проверки ЛР4. |
|
||||
| Контекст | AGENTS.md, openspec/config.yaml | Переносимые правила provenance/Context7/сохранения evidence адаптированы к ЛР4 и текущему правилу major/minor. |
|
||||
|
||||
Пять файлов Identity и семь тестовых файлов совпали с базой f591fa6 до переноса,
|
||||
поэтому взяты из final snapshot целиком. Два файла с механизмами ЛР4 объединены вручную.
|
||||
SQLAlchemy/Alembic остаются обязательными; новых миграций или зависимостей в диапазоне нет.
|
||||
|
||||
## Неприменимые изменения
|
||||
|
||||
169 файлов REPORT/evidence ЛР3 не скопированы: это чужой для ЛР4 отчёт, результаты
|
||||
трёхуровневой матрицы масштабирования и аудиты конкретных образов/стендов ЛР3.
|
||||
Их цифры не доказывают ЛР4. Четыре переносимых файла сценариев выделены отдельно выше.
|
||||
AGENTS/config: статусы 135 измерений ЛР3, порты 18083/23083, трек масштабирования,
|
||||
ограничения отдельной report-фазы не заменяют контекст текущей ЛР4. Применимые
|
||||
правила перенесены с портами 18084/24000–24999 и актуальным порядком runner.
|
||||
Нормативные contracts/tests/README/COURSE, secrets/.env/volumes не переносились.
|
||||
Source REPORT содержит minor про суррогаты; он сохраняется как ограничение, а не исправление.
|
||||
|
||||
## Проверки и применимость измерений
|
||||
|
||||
Новые команды, UTC и полные SHA сохраняются в `forward-final-2026-11-06/`.
|
||||
API-сессии/валидация/LB затронуты: повторяются smoke, persistence, failover,
|
||||
stack faults и сетевые регрессии, три прогона записи и граничные точки памяти.
|
||||
Reconciler demo повторяется для интеграции с API. Его стоимость 1k–100k сохраняется:
|
||||
алгоритм, SQL-адаптер вложений, CLI, S3, зависимости и драйвер cost неизменны;
|
||||
в cost API/LB/Valkey остановлены. Прежняя матрица памяти остаётся историческим
|
||||
сравнением, новые контрольные точки не выдаются за повтор всех 36 точек.
|
||||
Фон Docker фиксируется, чужие контейнеры не останавливаются.
|
||||
|
||||
Результаты этого этапа будут добавлены после завершения команд.
|
||||
@@ -0,0 +1,13 @@
|
||||
date: 2026-10-30T04:32:56Z commit: 81dd816
|
||||
$ psql -c "SELECT substring(password_hash from '^[$]argon2id[$]v=[0-9]+[$]m=[0-9]+,t=[0-9]+,p=[0-9]+[$]') AS kdf_prefix, username = 'seed_author' AS seed_stub, count(*) AS users, min(length(password_hash)) AS min_length, max(length(password_hash)) AS max_length FROM users GROUP BY 1, 2 ORDER BY 2"
|
||||
kdf_prefix | seed_stub | users | min_length | max_length
|
||||
---------------------------------+-----------+-------+------------+------------
|
||||
$argon2id$v=19$m=19456,t=2,p=1$ | f | 66 | 97 | 97
|
||||
(1 row)
|
||||
|
||||
$ psql -c "SELECT octet_length(token_hash) AS stored_bytes, count(*) AS sessions FROM sessions GROUP BY 1"
|
||||
stored_bytes | sessions
|
||||
--------------+----------
|
||||
32 | 60
|
||||
(1 row)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"instances_one_token": {
|
||||
"899a952a5a21": 20,
|
||||
"0cc3ee358e59": 20
|
||||
},
|
||||
"same_key": {
|
||||
"rounds": 20,
|
||||
"parallel": 8,
|
||||
"statuses": {
|
||||
"201": 160
|
||||
},
|
||||
"instances": {
|
||||
"899a952a5a21": 80,
|
||||
"0cc3ee358e59": 80
|
||||
},
|
||||
"identical_bodies_rounds": 20,
|
||||
"single_copy_rounds": 20,
|
||||
"conflict_rounds": 20
|
||||
},
|
||||
"pass": true
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
date: 2026-10-30T04:29:07Z commit: 81dd816
|
||||
$ docker compose --profile bench --profile tools --profile reconcile config --format json (declared)
|
||||
service cpus/mem ports secrets volumes networks ro
|
||||
---------- ---------- ------------------------------- -------------------------------------------------------------------------- ---------- ---------------------- -----
|
||||
api 1/512MiB - cache_url,cursor_secret,database_url,s3_access_key_id,s3_secret_access_key - backend(internal) true
|
||||
k6 2/512MiB - - - edge false
|
||||
lb 1/128MiB 127.0.0.1:18084,127.0.0.1:24084 - - backend(internal),edge true
|
||||
migrate 0.5/256MiB - database_url - backend(internal) false
|
||||
postgres 2/1024MiB - postgres_password pgdata backend(internal) false
|
||||
reconciler 1/256MiB - database_url,s3_access_key_id,s3_secret_access_key - backend(internal) true
|
||||
s3 1/512MiB - s3_root_password,s3_root_user s3data backend(internal) true
|
||||
s3-cli 0.5/64MiB - s3_access_key_id,s3_root_password,s3_root_user,s3_secret_access_key - backend(internal) true
|
||||
s3-init 0.5/64MiB - s3_access_key_id,s3_root_password,s3_root_user,s3_secret_access_key - backend(internal) true
|
||||
valkey 0.5/128MiB - valkey.conf valkeydata backend(internal) false
|
||||
|
||||
$ docker inspect (running containers: hostname = X-Instance-Id, applied limits)
|
||||
service hostname cpus memory published
|
||||
-------- ------------ ---- ------- ---------------------------------------------------
|
||||
api 0cc3ee358e59 1 512MiB
|
||||
api 899a952a5a21 1 512MiB
|
||||
lb a51c65de79e9 1 128MiB 127.0.0.1:18084->8080/tcp,127.0.0.1:24084->8404/tcp
|
||||
postgres 54d604398b41 2 1024MiB
|
||||
s3 89f363c93892 1 512MiB
|
||||
valkey 99365a2af315 0.5 128MiB
|
||||
|
||||
PASS: limits, ports, secrets, volumes and networks match the policy
|
||||
@@ -0,0 +1,66 @@
|
||||
date: 2026-10-30T04:43:19Z commit: 81dd816
|
||||
# закрытый контур tests/load.py: 64 потока, 8 с, все записи прогона в один чат, 3 повтора с паузой 15 с.
|
||||
# Клиент — одноразовый контейнер в сети edge стенда (как k6 в лабе 3): 2 CPU, 512 MiB, образ python API по digest,
|
||||
# tests/, contracts/ и lab.json только для чтения, tcp_tw_reuse=1; адрес — http://lb:8080. С хоста macOS тот же
|
||||
# прогон упирается в эфемерные порты прокси Docker Desktop (новое соединение на запрос): ~16 000 сокетов TIME_WAIT,
|
||||
# клиентские ошибки соединения без единого запроса к LB, поэтому замер с хоста не годится.
|
||||
# На 4-й секунде — docker stats; после прогона — статусы request.handled реплик за окно прогона.
|
||||
$ docker ps --format '{{.Names}}' | grep -v mtusi2026lab4 # чужие контейнеры на VM во время серии
|
||||
mtusi-lab6-test-rabbitmq-44e4f19b
|
||||
$ client() { docker run --rm --network mtusi2026lab4_edge --cpus 2 --memory 512m --sysctl net.ipv4.tcp_tw_reuse=1 -v tests,contracts,lab.json:ro -v evidence/load:/out python:3.14-slim-trixie@sha256:51dafde8… python /w/tests/load.py "$@"; }
|
||||
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run1.json
|
||||
exit 0
|
||||
{'elapsed_seconds': 8.191, 'successful_requests': 17199, 'failed_requests': 0, 'successful_rps': 2099.764, 'successful_latency_ms': {'p50': 25.927, 'p95': 68.522, 'p99': 96.55}}
|
||||
$ docker stats --no-stream (середина прогона): контейнер CPU% память
|
||||
api-1 89.46% 215MiB / 512MiB
|
||||
api-2 91.69% 214.8MiB / 512MiB
|
||||
lab4-load-client 106.19% 83.36MiB / 512MiB
|
||||
lb-1 80.99% 25.83MiB / 128MiB
|
||||
postgres-1 215.44% 164.6MiB / 1GiB
|
||||
s3-1 0.81% 327.6MiB / 512MiB
|
||||
valkey-1 6.12% 14.06MiB / 128MiB
|
||||
$ docker compose logs --since 2026-10-30T04:43:19Z api | request.handled: статус метод маршрут число
|
||||
200 GET /health/live 1
|
||||
200 GET /health/ready 23
|
||||
201 POST /api/v1/auth/sessions 3
|
||||
201 POST /api/v1/chats 1
|
||||
201 POST /api/v1/chats/{chat_id}/messages 17199
|
||||
201 POST /api/v1/users 3
|
||||
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run2.json
|
||||
exit 0
|
||||
{'elapsed_seconds': 8.207, 'successful_requests': 17386, 'failed_requests': 0, 'successful_rps': 2118.439, 'successful_latency_ms': {'p50': 26.371, 'p95': 66.641, 'p99': 86.248}}
|
||||
$ docker stats --no-stream (середина прогона): контейнер CPU% память
|
||||
api-1 92.83% 216.9MiB / 512MiB
|
||||
api-2 93.26% 216.8MiB / 512MiB
|
||||
lab4-load-client 106.22% 82.68MiB / 512MiB
|
||||
lb-1 79.14% 26.29MiB / 128MiB
|
||||
postgres-1 213.30% 174.1MiB / 1GiB
|
||||
s3-1 0.01% 337.3MiB / 512MiB
|
||||
valkey-1 6.36% 13.95MiB / 128MiB
|
||||
$ docker compose logs --since 2026-10-30T04:43:43Z api | request.handled: статус метод маршрут число
|
||||
200 GET /health/live 1
|
||||
200 GET /health/ready 23
|
||||
201 POST /api/v1/auth/sessions 3
|
||||
201 POST /api/v1/chats 1
|
||||
201 POST /api/v1/chats/{chat_id}/messages 17386
|
||||
201 POST /api/v1/users 3
|
||||
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run3.json
|
||||
exit 0
|
||||
{'elapsed_seconds': 8.229, 'successful_requests': 17332, 'failed_requests': 0, 'successful_rps': 2106.215, 'successful_latency_ms': {'p50': 26.607, 'p95': 67.007, 'p99': 88.37}}
|
||||
$ docker stats --no-stream (середина прогона): контейнер CPU% память
|
||||
api-1 96.95% 217.1MiB / 512MiB
|
||||
api-2 97.50% 218.4MiB / 512MiB
|
||||
lab4-load-client 101.96% 82.94MiB / 512MiB
|
||||
lb-1 79.73% 26.28MiB / 128MiB
|
||||
postgres-1 212.83% 186.4MiB / 1GiB
|
||||
s3-1 3.74% 343MiB / 512MiB
|
||||
valkey-1 6.35% 13.94MiB / 128MiB
|
||||
$ docker compose logs --since 2026-10-30T04:44:07Z api | request.handled: статус метод маршрут число
|
||||
200 GET /health/live 1
|
||||
200 GET /health/ready 23
|
||||
201 POST /api/v1/auth/sessions 3
|
||||
201 POST /api/v1/chats 1
|
||||
201 POST /api/v1/chats/{chat_id}/messages 17332
|
||||
201 POST /api/v1/users 3
|
||||
$ docker compose exec -T postgres psql: сообщений в базе после серии
|
||||
70839
|
||||
@@ -0,0 +1,24 @@
|
||||
date: 2026-10-30T04:32:57Z commit: 81dd816 BASE_URL=http://127.0.0.1:18084
|
||||
# Отброшенная первая попытка: тот же tests/load.py (64 потока, 8 с, пауза 40 с), но клиент на хосте macOS.
|
||||
# Исходный load.txt этой попытки перезаписан итоговой серией; строки ниже перенесены дословно из вывода консоли
|
||||
# сессии. Третий повтор и его вывод не сохранились.
|
||||
$ python3 tests/load.py --base-url http://127.0.0.1:18084 --duration 8 --concurrency 64 --output evidence/load/run1.json
|
||||
{'elapsed_seconds': 8.117, 'successful_requests': 8119, 'failed_requests': 10045, 'successful_rps': 1000.281, 'successful_latency_ms': {'p50': 47.448, 'p95': 58.768, 'p99': 91.04}}
|
||||
$ docker compose logs --since 2026-10-30T04:32:57Z api | request.handled: статус × маршрут
|
||||
201 POST /api/v1/chats/{chat_id}/messages 8119
|
||||
$ netstat -an -p tcp | grep -c TIME_WAIT # через несколько секунд после повтора 1
|
||||
16350
|
||||
$ sysctl net.inet.ip.portrange.first net.inet.ip.portrange.last net.inet.tcp.msl
|
||||
net.inet.ip.portrange.first: 49152
|
||||
net.inet.ip.portrange.last: 65535
|
||||
net.inet.tcp.msl: 15000
|
||||
$ python3 tests/load.py --base-url http://127.0.0.1:18084 --duration 8 --concurrency 64 --output evidence/load/run2.json # после паузы 40 с
|
||||
{'elapsed_seconds': 8.144, 'successful_requests': 2396, 'failed_requests': 6398, 'successful_rps': 294.186, 'successful_latency_ms': {'p50': 46.791, 'p95': 53.737, 'p99': 58.858}}
|
||||
$ docker compose logs --since 2026-10-30T04:33:45Z api | request.handled: статус × маршрут
|
||||
201 POST /api/v1/chats/{chat_id}/messages 2396
|
||||
$ netstat -an -p tcp | grep -c TIME_WAIT
|
||||
16959
|
||||
# Вывод: реплики ответили 201 на каждый дошедший запрос и ни одного 5xx; все неудачи — клиентские ошибки соединения
|
||||
# при ~16 000 сокетов TIME_WAIT на хосте (диапазон эфемерных портов — 16 384, TIME_WAIT 2 × MSL = 30 с, прокси
|
||||
# Docker Desktop держит свои сокеты на каждое соединение). tests/load.py открывает соединение на каждый запрос,
|
||||
# поэтому замер с хоста ограничен портами хоста, а не стендом; итоговая серия — клиентом в сети edge (load.txt).
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 4,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 8.0,
|
||||
"elapsed_seconds": 8.191,
|
||||
"concurrency": 64,
|
||||
"successful_requests": 17199,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 2099.764,
|
||||
"successful_latency_ms": {
|
||||
"p50": 25.927,
|
||||
"p95": 68.522,
|
||||
"p99": 96.55
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 4,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 8.0,
|
||||
"elapsed_seconds": 8.207,
|
||||
"concurrency": 64,
|
||||
"successful_requests": 17386,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 2118.439,
|
||||
"successful_latency_ms": {
|
||||
"p50": 26.371,
|
||||
"p95": 66.641,
|
||||
"p99": 86.248
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 4,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 8.0,
|
||||
"elapsed_seconds": 8.229,
|
||||
"concurrency": 64,
|
||||
"successful_requests": 17332,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 2106.215,
|
||||
"successful_latency_ms": {
|
||||
"p50": 26.607,
|
||||
"p95": 67.007,
|
||||
"p99": 88.37
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
date: 2026-10-30T04:32:54Z commit: 81dd816
|
||||
$ psql -c "SELECT (SELECT count(*) FROM users) users, (SELECT count(*) FROM sessions) sessions, (SELECT count(*) FROM chats) chats, (SELECT count(*) FROM chat_members) members, (SELECT count(*) FROM messages) messages, (SELECT count(*) FROM idempotency_keys) keys, (SELECT count(*) FROM attachments) attachments, (SELECT count(*) FROM message_attachments) links, (SELECT count(*) FROM schema_migrations) versions"
|
||||
users | sessions | chats | members | messages | keys | attachments | links | versions
|
||||
-------+----------+-------+---------+----------+------+-------------+-------+----------
|
||||
66 | 60 | 38 | 56 | 288 | 288 | 17 | 3 | 4
|
||||
(1 row)
|
||||
|
||||
$ make migrate
|
||||
{"reason":"up to date","event":"migration.completed","level":"info","ts":"2026-10-30T04:32:56.159252Z"}
|
||||
$ psql -c "SELECT (SELECT count(*) FROM users) users, (SELECT count(*) FROM sessions) sessions, (SELECT count(*) FROM chats) chats, (SELECT count(*) FROM chat_members) members, (SELECT count(*) FROM messages) messages, (SELECT count(*) FROM idempotency_keys) keys, (SELECT count(*) FROM attachments) attachments, (SELECT count(*) FROM message_attachments) links, (SELECT count(*) FROM schema_migrations) versions"
|
||||
users | sessions | chats | members | messages | keys | attachments | links | versions
|
||||
-------+----------+-------+---------+----------+------+-------------+-------+----------
|
||||
66 | 60 | 38 | 56 | 288 | 288 | 17 | 3 | 4
|
||||
(1 row)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
date: 2026-10-30T04:43:02Z commit: 81dd816
|
||||
# после трёх прогонов upload-memory и mmap-32m на том же стенде: 68 загрузок получили 503 (7 + 27 + 34, все при 40 одновременных по 10 MiB)
|
||||
$ make reconcile # dry-run, 04:42:40Z, сразу после серии
|
||||
{"mode": "dry-run", "grace_seconds": 3600, "scanned": {"objects": 1794, "rows": 1837}, "found": {"orphan_stale": 0, "orphan_fresh": 0, "missing": 0, "size_mismatch": 0, "sha_mismatch": 0, "pending_stale": 0, "pending_fresh": 68, "quarantined": 0, "healed": 0}, "fixed": {"orphan_stale": 0, "missing": 0, "size_mismatch": 0, "sha_mismatch": 0, "pending_stale": 0, "healed": 0}, "errors": 0}
|
||||
$ psql -c "SELECT status, count(*), min(created_at), max(created_at) FROM attachments GROUP BY status"
|
||||
status | count | min | max
|
||||
---------+-------+-------------------------------+-------------------------------
|
||||
pending | 68 | 2026-10-30 04:30:05.876922+00 | 2026-10-30 04:38:09.467838+00
|
||||
ready | 1769 | 2026-10-30 02:30:27.495355+00 | 2026-10-30 04:42:33.025293+00
|
||||
(2 rows)
|
||||
|
||||
$ psql -c "SELECT created_at < '2026-10-30 04:34:42+00' AS before_upload_memory, count(*), sum(size_bytes) FILTER (WHERE size_bytes > 10000000) / 1048576 AS mib_10m FROM attachments WHERE status = 'pending' GROUP BY 1 ORDER BY 1"
|
||||
before_upload_memory | count | mib_10m
|
||||
----------------------+-------+----------------------
|
||||
f | 67 | 669.9677963256835938
|
||||
t | 1 |
|
||||
(2 rows)
|
||||
|
||||
# ожидание: until [ $(psql -tA -c "SELECT count(*) FROM attachments WHERE status='pending'") = 0 ]; do sleep 10; done
|
||||
pending = 0 в 2026-10-30T04:53:47Z (последнее намерение создано в 04:38:09, grace 900 с, уборка раз в 30 с)
|
||||
$ docker compose logs api | audit.attachment_discarded по причине и времени (сортировка по ts); сумма attachments.swept
|
||||
{'abandoned': 68} swept 68; по времени: первое 2026-10-30T04:45:08Z (намерение от s3-outage), затем 67 с 04:51:08Z по 04:53:38Z
|
||||
$ psql -c "SELECT status, count(*) FROM attachments GROUP BY status"
|
||||
status | count
|
||||
--------+-------
|
||||
ready | 1769
|
||||
(1 row)
|
||||
|
||||
$ make reconcile # dry-run после уборки
|
||||
{"mode": "dry-run", "grace_seconds": 3600, "scanned": {"objects": 1769, "rows": 1769}, "found": {"orphan_stale": 0, "orphan_fresh": 0, "missing": 0, "size_mismatch": 0, "sha_mismatch": 0, "pending_stale": 0, "pending_fresh": 0, "quarantined": 0, "healed": 0}, "fixed": {"orphan_stale": 0, "missing": 0, "size_mismatch": 0, "sha_mismatch": 0, "pending_stale": 0, "healed": 0}, "errors": 0}
|
||||
@@ -0,0 +1,22 @@
|
||||
date: 2026-10-30T04:29:52Z commit: 81dd816
|
||||
== before: service hostname StartedAt status
|
||||
api 0cc3ee358e59 2026-10-30T04:29:49.45750296Z running
|
||||
api 899a952a5a21 2026-10-30T04:29:31.104320507Z running
|
||||
lb a51c65de79e9 2026-10-30T04:28:53.588116504Z running
|
||||
migrate 9181dd1eb5a8 2026-10-30T04:28:54.673721004Z exited
|
||||
postgres 54d604398b41 2026-10-30T04:28:53.58363217Z running
|
||||
s3 89f363c93892 2026-10-30T04:28:53.59152942Z running
|
||||
s3-init a8f9ad1766ab 2026-10-30T04:28:59.185601048Z exited
|
||||
valkey 99365a2af315 2026-10-30T04:28:53.590483087Z running
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:18084"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
== after: service hostname StartedAt status
|
||||
api 0cc3ee358e59 2026-10-30T04:30:01.738275341Z running
|
||||
api 899a952a5a21 2026-10-30T04:30:01.662962216Z running
|
||||
lb a51c65de79e9 2026-10-30T04:29:56.045382713Z running
|
||||
migrate 9181dd1eb5a8 2026-10-30T04:29:56.567340338Z exited
|
||||
postgres 54d604398b41 2026-10-30T04:29:55.776017088Z running
|
||||
s3 89f363c93892 2026-10-30T04:29:55.723034421Z running
|
||||
s3-init a8f9ad1766ab 2026-10-30T04:30:01.069323507Z exited
|
||||
valkey 99365a2af315 2026-10-30T04:29:55.801923296Z running
|
||||
@@ -0,0 +1,37 @@
|
||||
# Трек 2 «Согласованность двух хранилищ»: сырые данные
|
||||
|
||||
Этот каталог — историческая серия asyncpg. Текущие измерения SQLAlchemy, включая 100k ×3,
|
||||
хранятся отдельно: [протокол](../sqlalchemy-2026-11-06/track5/NOTES.md).
|
||||
Новые команды принимают `ARGS="--out <новый-каталог>"`; существующие серии не удаляются.
|
||||
|
||||
Отчёты сверки — stdout `python -m messenger.attachments.entrypoints.reconcile` (поля описаны в
|
||||
`openspec/specs/lab4-storage-reconciler/spec.md`) плюс `exit_code` и `wall_seconds` (время `docker compose run`
|
||||
вместе со стартом контейнера). Независимая проверка — `scripts/reconcile_check.py`: листинг bucket через `rc`
|
||||
под root-ключом, строки через `psql`, SHA-256 каждого объекта через `rc object show | sha256sum`, без кода API.
|
||||
Время в JSON — UTC.
|
||||
|
||||
| Файл | Что внутри | Чем получен |
|
||||
| --- | --- | --- |
|
||||
| `demo.json` | итог сценария: коммит, внедрённые id по классам (у объекта без строки — uuid его ключа), 13 проверок с деталями, `ok` | `make reconcile-demo` |
|
||||
| `ready-before.json`, `ready-untouched.json` | id → SHA-256 готовых вложений до внедрения; то же без повреждаемых — ожидаемый набор после `apply` | `reconcile_check.py --save-ready` |
|
||||
| `check-before.json`, `check-after.json` | независимая проверка (`--deep`) после внедрения и после двух `apply` | `reconcile_check.py` |
|
||||
| `dry-run.json`, `apply-1.json`, `apply-2.json` | `--dry-run --deep`, затем `--apply --deep` дважды, `--grace 60 --skew 0`; `audit` — события `audit.*` журнала прохода | сервис `reconciler` |
|
||||
| `healed.json` | `--apply` без `--deep` после того, как под ключ одного вложения в карантине `missing` вернули исходные байты, а под ключ другого — случайные той же длины | сервис `reconciler` |
|
||||
| `sigterm.json` | `docker stop` прохода, висящего на листинге остановленного (`pause`) S3: состояние до остановки, `init`, секунды, код выхода, не пропущен ли следующий проход | `reconcile_track.py` |
|
||||
| `lock-busy.json` | проход, пока `pg_advisory_lock(20260004)` держит другой сеанс: `skipped` | сервис `reconciler` |
|
||||
| `s3-down.json` | проход при остановленном `s3`: код, время, stdout, строки журнала `reconcile.*` | сервис `reconciler` |
|
||||
| `ready-load.json` | id → SHA-256 всех вложений, которые должны пережить нагрузку: готовые до неё и каждое `201` под ней | `reconcile_track.py` |
|
||||
| `under-load.json`, `check-under-load.json` | 75 с загрузок через LB (3 потока, каждое 10-е вложение — в сообщение) и `--apply` подряд: ответы, время проходов, исправленное, увиденное свежим, отказы после повторной проверки (`rechecked_total`); проверка `--deep --expect-ready` после | `reconcile_track.py` |
|
||||
| `cost/n<N>-<режим>-<повтор>.json` | отчёт прохода `--dry-run` на N = 1k, 10k, 30k, 100k объектах и строках; режимы `shallow` (страница 1000), `deep` (`--deep`), `page100` (страница 100, на 10k); `screen` — чужая нагрузка CPU за окно прогона. В историческом драйвере прошлые файлы удалялись; текущий драйвер требует новый каталог и сохраняет старые данные | `make reconcile-cost` |
|
||||
| `cost/disturbed/*.json` | отбракованные прогоны (чужого CPU больше 2 ядер во всей VM или 0,25 на закреплённых ядрах сверх запуска контейнера); каждый повторён после 15 с тишины | `make reconcile-cost` |
|
||||
| `cost/summary.json`, `cost/summary.txt` | медианы трёх прогонов на точку, запросы, RSS, CPU, наибольшая чужая нагрузка, число отбракованных; закрепление CPU и лимиты `s3`/`postgres`; время наполнения | `make reconcile-cost` |
|
||||
| `cost/host-docker-stats.txt` | `docker stats --all` и `docker ps` всего хоста до и после серии, loadavg macOS | `make reconcile-cost` |
|
||||
| `cost-b191623/` | прошлая серия 1k/10k/30k (`b191623`, 30.10) с отбраковкой: до исправления keyset (SQL-страниц на одну больше) и до снятия карантина по SHA-256; для сравнения | `make reconcile-cost` на `b191623` |
|
||||
| `cost-2026-10-29/` | первая полная серия 1k/10k/30k (`5ca2cdc`, 29.10): без отбраковки и без `cpu_seconds`, рядом шёл k6 другой лабы; для сравнения между днями, `NOTE.txt` | `make reconcile-cost` на `5ca2cdc` |
|
||||
| `cost-aborted/` | две прерванные попытки наполнить RustFS до 100k в прежних конфигурациях: RustFS 1 GiB (упор в лимит памяти) и 16 параллельных `PutObject` (запись мешала сама себе); их точки 1k/10k; диагноз — `NOTE.txt`. Итоговая конфигурация (3 GiB, 4 записи) 100k наполняет | `make reconcile-cost` до `5ca2cdc` |
|
||||
|
||||
Поля `screen`: `window_seconds` — окно между двумя чтениями счётчиков VM (`/proc/uptime`), `ours_cores` — CPU
|
||||
`s3`, `postgres` и процесса сверки за окно, `other_cores` и `other_on_pinned_cores` — чужой CPU во всей VM и на
|
||||
ядрах `s3`/`postgres`/`reconciler` сверх запуска контейнера (1,5 и 0,5 ядро·с), в ядрах, `disturbed` — прогон
|
||||
отбракован. Пороги, запас на запуск контейнера и число повторов записаны в `cost/summary.json` (`screen`). Объём данных в матрице — синтетические вложения
|
||||
`student-tests/tools/seed_storage.py` (PNG 8 × 8, 264 B, строки `ready` двухчасовой давности).
|
||||
@@ -0,0 +1,140 @@
|
||||
{
|
||||
"mode": "apply",
|
||||
"skipped": false,
|
||||
"grace_seconds": 60,
|
||||
"skew_seconds": 0,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 24,
|
||||
"rows": 27
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 3,
|
||||
"orphan_fresh": 2,
|
||||
"missing": 3,
|
||||
"size_mismatch": 3,
|
||||
"sha_mismatch": 3,
|
||||
"pending_stale": 6,
|
||||
"pending_fresh": 2,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 3,
|
||||
"missing": 3,
|
||||
"size_mismatch": 3,
|
||||
"sha_mismatch": 3,
|
||||
"pending_stale": 6,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {
|
||||
"missing": [
|
||||
"01a18b6d-7f51-7100-9ff4-889e89caccd9",
|
||||
"01a18b6d-7f6a-7296-81fd-fb883beb9b39",
|
||||
"01a18b6d-7fc2-73ac-839f-0107ae03f9a6"
|
||||
],
|
||||
"size_mismatch": [
|
||||
"01a18b6d-7f95-7491-92e4-8ecd4a5edd55",
|
||||
"01a18b6d-7fcb-759d-913d-211ccaa962ad",
|
||||
"01a18b6d-7fd4-77f4-98c3-ebe387a28aea"
|
||||
],
|
||||
"sha_mismatch": [
|
||||
"01a18b6d-7fa5-75f1-accf-49b1e660d865",
|
||||
"01a18b6d-7fdc-74b5-85bf-4a96931cd5d5",
|
||||
"01a18b6d-7fe5-7056-a2f5-7cdf0aa614f1"
|
||||
],
|
||||
"pending_stale": [
|
||||
"2a195d07-ad0a-415c-9d36-f1a6d367c616",
|
||||
"32651f33-918e-4dff-a137-f0b4196286a1",
|
||||
"42fba42a-d020-4f89-aad3-e9e21840d25b",
|
||||
"4fe15617-cab8-469d-a25e-34a981e7c4c5",
|
||||
"6678cf2a-8292-4943-8955-75d7df8f9307",
|
||||
"8ec129d3-3721-4449-af97-4355cc19dd80"
|
||||
],
|
||||
"orphan_fresh": [
|
||||
"attachments/4b21266b-8dfc-4c67-9ffc-11575d794795",
|
||||
"attachments/fa6c3d18-8e06-4b14-8a7d-acd5e1671890"
|
||||
],
|
||||
"orphan_stale": [
|
||||
"attachments/57198272-dd0d-46d6-97f0-e68295a5e65e",
|
||||
"attachments/aeebb4d7-95f8-4ebd-ac86-1031bc42e469",
|
||||
"attachments/fc854d9e-6be4-4b3a-a676-d2dcf9be5993"
|
||||
],
|
||||
"pending_fresh": [
|
||||
"80259edc-7cb8-4181-9878-f642a2b34d71",
|
||||
"a3e9efb4-3de5-43a8-8d18-296bf48cc4f8"
|
||||
]
|
||||
},
|
||||
"cost": {
|
||||
"seconds": 0.107,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 6,
|
||||
"s3_get": 13,
|
||||
"s3_delete": 9,
|
||||
"sql": 19
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.015,
|
||||
"sql": 0.003
|
||||
},
|
||||
"hashed_bytes": 1453621,
|
||||
"cpu_seconds": 0.479,
|
||||
"max_rss_mib": 84.9
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 0.922,
|
||||
"audit": [
|
||||
{
|
||||
"attachment_id": "2a195d07-ad0a-415c-9d36-f1a6d367c616",
|
||||
"chat_id": "01a18b6d-798f-75e5-ac4e-9af3b84aaa94",
|
||||
"reason": "reconcile",
|
||||
"event": "audit.attachment_discarded",
|
||||
"level": "info",
|
||||
"ts": "2026-10-30T06:10:43.376524Z"
|
||||
},
|
||||
{
|
||||
"attachment_id": "32651f33-918e-4dff-a137-f0b4196286a1",
|
||||
"chat_id": "01a18b6d-798f-75e5-ac4e-9af3b84aaa94",
|
||||
"reason": "reconcile",
|
||||
"event": "audit.attachment_discarded",
|
||||
"level": "info",
|
||||
"ts": "2026-10-30T06:10:43.386996Z"
|
||||
},
|
||||
{
|
||||
"attachment_id": "42fba42a-d020-4f89-aad3-e9e21840d25b",
|
||||
"chat_id": "01a18b6d-798f-75e5-ac4e-9af3b84aaa94",
|
||||
"reason": "reconcile",
|
||||
"event": "audit.attachment_discarded",
|
||||
"level": "info",
|
||||
"ts": "2026-10-30T06:10:43.396935Z"
|
||||
},
|
||||
{
|
||||
"attachment_id": "4fe15617-cab8-469d-a25e-34a981e7c4c5",
|
||||
"chat_id": "01a18b6d-798f-75e5-ac4e-9af3b84aaa94",
|
||||
"reason": "reconcile",
|
||||
"event": "audit.attachment_discarded",
|
||||
"level": "info",
|
||||
"ts": "2026-10-30T06:10:43.398761Z"
|
||||
},
|
||||
{
|
||||
"attachment_id": "6678cf2a-8292-4943-8955-75d7df8f9307",
|
||||
"chat_id": "01a18b6d-798f-75e5-ac4e-9af3b84aaa94",
|
||||
"reason": "reconcile",
|
||||
"event": "audit.attachment_discarded",
|
||||
"level": "info",
|
||||
"ts": "2026-10-30T06:10:43.409239Z"
|
||||
},
|
||||
{
|
||||
"attachment_id": "8ec129d3-3721-4449-af97-4355cc19dd80",
|
||||
"chat_id": "01a18b6d-798f-75e5-ac4e-9af3b84aaa94",
|
||||
"reason": "reconcile",
|
||||
"event": "audit.attachment_discarded",
|
||||
"level": "info",
|
||||
"ts": "2026-10-30T06:10:43.418544Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"mode": "apply",
|
||||
"skipped": false,
|
||||
"grace_seconds": 60,
|
||||
"skew_seconds": 0,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 18,
|
||||
"rows": 21
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 2,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 2,
|
||||
"quarantined": 9,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {
|
||||
"quarantined": [
|
||||
"01a18b6d-7f51-7100-9ff4-889e89caccd9",
|
||||
"01a18b6d-7f6a-7296-81fd-fb883beb9b39",
|
||||
"01a18b6d-7f95-7491-92e4-8ecd4a5edd55",
|
||||
"01a18b6d-7fc2-73ac-839f-0107ae03f9a6",
|
||||
"01a18b6d-7fcb-759d-913d-211ccaa962ad",
|
||||
"01a18b6d-7fd4-77f4-98c3-ebe387a28aea",
|
||||
"01a18b6d-7fa5-75f1-accf-49b1e660d865",
|
||||
"01a18b6d-7fdc-74b5-85bf-4a96931cd5d5",
|
||||
"01a18b6d-7fe5-7056-a2f5-7cdf0aa614f1"
|
||||
],
|
||||
"orphan_fresh": [
|
||||
"attachments/4b21266b-8dfc-4c67-9ffc-11575d794795",
|
||||
"attachments/fa6c3d18-8e06-4b14-8a7d-acd5e1671890"
|
||||
],
|
||||
"pending_fresh": [
|
||||
"80259edc-7cb8-4181-9878-f642a2b34d71",
|
||||
"a3e9efb4-3de5-43a8-8d18-296bf48cc4f8"
|
||||
]
|
||||
},
|
||||
"cost": {
|
||||
"seconds": 0.031,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 13,
|
||||
"s3_delete": 0,
|
||||
"sql": 1
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.015,
|
||||
"sql": 0.004
|
||||
},
|
||||
"hashed_bytes": 1453621,
|
||||
"cpu_seconds": 0.478,
|
||||
"max_rss_mib": 85.3
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 0.856,
|
||||
"audit": []
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"checked_at": "2026-10-30T06:10:45Z",
|
||||
"grace_seconds": 60,
|
||||
"deep": true,
|
||||
"objects": 18,
|
||||
"rows": 21,
|
||||
"ready_healthy": 10,
|
||||
"counts": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 2,
|
||||
"missing_referenced": 0,
|
||||
"missing_unreferenced": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale_with_object": 0,
|
||||
"pending_stale_without_object": 0,
|
||||
"pending_fresh": 2,
|
||||
"quarantined": 9,
|
||||
"incomplete_stale": 0,
|
||||
"incomplete_fresh": 0,
|
||||
"lost_ready": 0
|
||||
},
|
||||
"samples": {
|
||||
"orphan_fresh": [
|
||||
"attachments/4b21266b-8dfc-4c67-9ffc-11575d794795",
|
||||
"attachments/fa6c3d18-8e06-4b14-8a7d-acd5e1671890"
|
||||
],
|
||||
"pending_fresh": [
|
||||
"80259edc-7cb8-4181-9878-f642a2b34d71",
|
||||
"a3e9efb4-3de5-43a8-8d18-296bf48cc4f8"
|
||||
],
|
||||
"quarantined": [
|
||||
"01a18b6d-7f51-7100-9ff4-889e89caccd9",
|
||||
"01a18b6d-7f6a-7296-81fd-fb883beb9b39",
|
||||
"01a18b6d-7f95-7491-92e4-8ecd4a5edd55",
|
||||
"01a18b6d-7fa5-75f1-accf-49b1e660d865",
|
||||
"01a18b6d-7fc2-73ac-839f-0107ae03f9a6",
|
||||
"01a18b6d-7fcb-759d-913d-211ccaa962ad",
|
||||
"01a18b6d-7fd4-77f4-98c3-ebe387a28aea",
|
||||
"01a18b6d-7fdc-74b5-85bf-4a96931cd5d5",
|
||||
"01a18b6d-7fe5-7056-a2f5-7cdf0aa614f1"
|
||||
]
|
||||
},
|
||||
"seconds": {
|
||||
"s3_list": 0.349,
|
||||
"s3_incomplete": 0.341,
|
||||
"pg_query": 0.129,
|
||||
"deep_hash": 0.583,
|
||||
"total": 1.402
|
||||
},
|
||||
"violations": [],
|
||||
"ok": true
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"checked_at": "2026-10-30T06:10:40Z",
|
||||
"grace_seconds": 60,
|
||||
"deep": true,
|
||||
"objects": 24,
|
||||
"rows": 27,
|
||||
"ready_healthy": 10,
|
||||
"counts": {
|
||||
"orphan_stale": 3,
|
||||
"orphan_fresh": 2,
|
||||
"missing_referenced": 2,
|
||||
"missing_unreferenced": 1,
|
||||
"size_mismatch": 3,
|
||||
"sha_mismatch": 3,
|
||||
"pending_stale_with_object": 3,
|
||||
"pending_stale_without_object": 3,
|
||||
"pending_fresh": 2,
|
||||
"quarantined": 0,
|
||||
"incomplete_stale": 0,
|
||||
"incomplete_fresh": 0,
|
||||
"lost_ready": 0
|
||||
},
|
||||
"samples": {
|
||||
"orphan_stale": [
|
||||
"attachments/57198272-dd0d-46d6-97f0-e68295a5e65e",
|
||||
"attachments/aeebb4d7-95f8-4ebd-ac86-1031bc42e469",
|
||||
"attachments/fc854d9e-6be4-4b3a-a676-d2dcf9be5993"
|
||||
],
|
||||
"orphan_fresh": [
|
||||
"attachments/4b21266b-8dfc-4c67-9ffc-11575d794795",
|
||||
"attachments/fa6c3d18-8e06-4b14-8a7d-acd5e1671890"
|
||||
],
|
||||
"missing_referenced": [
|
||||
"01a18b6d-7f51-7100-9ff4-889e89caccd9",
|
||||
"01a18b6d-7f6a-7296-81fd-fb883beb9b39"
|
||||
],
|
||||
"missing_unreferenced": [
|
||||
"01a18b6d-7fc2-73ac-839f-0107ae03f9a6"
|
||||
],
|
||||
"size_mismatch": [
|
||||
"01a18b6d-7f95-7491-92e4-8ecd4a5edd55",
|
||||
"01a18b6d-7fcb-759d-913d-211ccaa962ad",
|
||||
"01a18b6d-7fd4-77f4-98c3-ebe387a28aea"
|
||||
],
|
||||
"sha_mismatch": [
|
||||
"01a18b6d-7fa5-75f1-accf-49b1e660d865",
|
||||
"01a18b6d-7fdc-74b5-85bf-4a96931cd5d5",
|
||||
"01a18b6d-7fe5-7056-a2f5-7cdf0aa614f1"
|
||||
],
|
||||
"pending_stale_with_object": [
|
||||
"32651f33-918e-4dff-a137-f0b4196286a1",
|
||||
"42fba42a-d020-4f89-aad3-e9e21840d25b",
|
||||
"8ec129d3-3721-4449-af97-4355cc19dd80"
|
||||
],
|
||||
"pending_stale_without_object": [
|
||||
"2a195d07-ad0a-415c-9d36-f1a6d367c616",
|
||||
"4fe15617-cab8-469d-a25e-34a981e7c4c5",
|
||||
"6678cf2a-8292-4943-8955-75d7df8f9307"
|
||||
],
|
||||
"pending_fresh": [
|
||||
"80259edc-7cb8-4181-9878-f642a2b34d71",
|
||||
"a3e9efb4-3de5-43a8-8d18-296bf48cc4f8"
|
||||
]
|
||||
},
|
||||
"seconds": {
|
||||
"s3_list": 0.333,
|
||||
"s3_incomplete": 0.335,
|
||||
"pg_query": 0.13,
|
||||
"deep_hash": 0.605,
|
||||
"total": 1.404
|
||||
},
|
||||
"violations": [
|
||||
"orphan_stale",
|
||||
"missing_referenced",
|
||||
"missing_unreferenced",
|
||||
"size_mismatch",
|
||||
"sha_mismatch",
|
||||
"pending_stale_with_object",
|
||||
"pending_stale_without_object"
|
||||
],
|
||||
"ok": false
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"checked_at": "2026-10-30T06:13:49Z",
|
||||
"grace_seconds": 60,
|
||||
"deep": true,
|
||||
"objects": 3472,
|
||||
"rows": 3473,
|
||||
"ready_healthy": 3465,
|
||||
"counts": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing_referenced": 0,
|
||||
"missing_unreferenced": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale_with_object": 0,
|
||||
"pending_stale_without_object": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 8,
|
||||
"incomplete_stale": 0,
|
||||
"incomplete_fresh": 0,
|
||||
"lost_ready": 0
|
||||
},
|
||||
"samples": {
|
||||
"quarantined": [
|
||||
"01a18b6d-7f6a-7296-81fd-fb883beb9b39",
|
||||
"01a18b6d-7f95-7491-92e4-8ecd4a5edd55",
|
||||
"01a18b6d-7fa5-75f1-accf-49b1e660d865",
|
||||
"01a18b6d-7fc2-73ac-839f-0107ae03f9a6",
|
||||
"01a18b6d-7fcb-759d-913d-211ccaa962ad",
|
||||
"01a18b6d-7fd4-77f4-98c3-ebe387a28aea",
|
||||
"01a18b6d-7fdc-74b5-85bf-4a96931cd5d5",
|
||||
"01a18b6d-7fe5-7056-a2f5-7cdf0aa614f1"
|
||||
]
|
||||
},
|
||||
"seconds": {
|
||||
"s3_list": 0.614,
|
||||
"s3_incomplete": 0.344,
|
||||
"pg_query": 0.138,
|
||||
"deep_hash": 69.163,
|
||||
"total": 70.267
|
||||
},
|
||||
"violations": [],
|
||||
"ok": true
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
Первая полная серия make reconcile-cost: 2026-10-29T01:40Z, коммит 5ca2cdc (до переноса исправлений лабы 3 и до
|
||||
отбраковки возмущённых прогонов). Конфигурация та же, что у итоговой серии evidence/reconcile/cost: RustFS 2 CPU /
|
||||
3 GiB на cpuset 11-12, PostgreSQL 13-14, reconciler 15, наполнение 4 параллельными PutObject, по 3 прогона.
|
||||
Чужая нагрузка за окно прогона не измерялась; в снимке host-docker-stats.txt перед серией работал стенд другой
|
||||
лабы под k6 (review-lab3-*: api 23 %, k6, lb). Отчёты прогонов без полей cpu_seconds и screen.
|
||||
Хранится для сравнения двух серий между днями; выводы трека опираются на итоговую серию.
|
||||
@@ -0,0 +1,33 @@
|
||||
date: 2026-10-29T01:40:48Z
|
||||
$ docker stats --no-stream --all
|
||||
NAME CPU % MEM USAGE / LIMIT MEM % PIDS
|
||||
mtusi2026lab4-api-2 0.35% 123.1MiB / 512MiB 24.05% 12
|
||||
mtusi2026lab4-api-1 0.31% 163.4MiB / 512MiB 31.91% 13
|
||||
mtusi2026lab4-migrate-1 0.00% 0B / 0B 0.00% 0
|
||||
mtusi2026lab4-s3-init-1 0.00% 0B / 0B 0.00% 0
|
||||
mtusi2026lab4-postgres-1 1.15% 50.29MiB / 1GiB 4.91% 10
|
||||
mtusi2026lab4-lb-1 0.71% 19.39MiB / 128MiB 15.15% 17
|
||||
mtusi2026lab4-s3-1 0.71% 65.62MiB / 512MiB 12.82% 21
|
||||
mtusi2026lab4-valkey-1 0.11% 12.55MiB / 128MiB 9.81% 6
|
||||
review-lab3-k6-run-36a4cbb10907 4.66% 19.99MiB / 512MiB 3.90% 8
|
||||
review-lab3-api-2 0.00% 0B / 0B 0.00% 0
|
||||
review-lab3-api-1 23.17% 160.7MiB / 512MiB 31.38% 13
|
||||
review-lab3-postgres-1 5.00% 61.35MiB / 1GiB 5.99% 10
|
||||
review-lab3-valkey-1 0.65% 13.25MiB / 128MiB 10.35% 6
|
||||
review-lab3-lb-1 3.92% 27.48MiB / 128MiB 21.47% 17
|
||||
review-lab3-migrate-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-tsvision-backend-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-tsvision-consumer-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-minio-init-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-postgres-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-rabbitmq-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-minio-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-mediamtx-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-dragonfly-1 0.00% 0B / 0B 0.00% 0
|
||||
boring_merkle 0.00% 0B / 0B 0.00% 0
|
||||
infallible_solomon 0.00% 0B / 0B 0.00% 0
|
||||
friendly_goldwasser 0.00% 0B / 0B 0.00% 0
|
||||
magical_noether 0.00% 0B / 0B 0.00% 0
|
||||
postgres 0.00% 0B / 0B 0.00% 0
|
||||
main_postgres 0.00% 0B / 0B 0.00% 0
|
||||
fulfilment-backend 0.00% 0B / 0B 0.00% 0
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.524,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 1000,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.084,
|
||||
"sql": 0.01
|
||||
},
|
||||
"hashed_bytes": 375553,
|
||||
"max_rss_mib": 83.5
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 1.331
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.49,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 1000,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.083,
|
||||
"sql": 0.01
|
||||
},
|
||||
"hashed_bytes": 375553,
|
||||
"max_rss_mib": 83.1
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 1.31
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.505,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 1000,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.083,
|
||||
"sql": 0.011
|
||||
},
|
||||
"hashed_bytes": 375553,
|
||||
"max_rss_mib": 83.4
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 1.307
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.105,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.09,
|
||||
"sql": 0.008
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 82.7
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 0.908
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.096,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.081,
|
||||
"sql": 0.008
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 82.7
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 0.911
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.096,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.081,
|
||||
"sql": 0.008
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 82.6
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 0.888
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 5.261,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 10000,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 1.023,
|
||||
"sql": 0.047
|
||||
},
|
||||
"hashed_bytes": 2751553,
|
||||
"max_rss_mib": 84.3
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 6.104
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 5.252,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 10000,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 1.03,
|
||||
"sql": 0.048
|
||||
},
|
||||
"hashed_bytes": 2751553,
|
||||
"max_rss_mib": 84.6
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 6.104
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 5.179,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 10000,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 1.028,
|
||||
"sql": 0.048
|
||||
},
|
||||
"hashed_bytes": 2751553,
|
||||
"max_rss_mib": 84.3
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 6.008
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 100,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 2.157,
|
||||
"requests": {
|
||||
"s3_list": 100,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 101
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 2.055,
|
||||
"sql": 0.089
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 81.1
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 3.004
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 100,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 2.241,
|
||||
"requests": {
|
||||
"s3_list": 100,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 101
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 2.126,
|
||||
"sql": 0.101
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 81.1
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 3.084
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 100,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 2.434,
|
||||
"requests": {
|
||||
"s3_list": 100,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 101
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 2.313,
|
||||
"sql": 0.108
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 81.2
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 3.324
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 1.058,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 1.0,
|
||||
"sql": 0.046
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 84.1
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 1.92
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 1.09,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 1.033,
|
||||
"sql": 0.046
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 83.8
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 1.932
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 1.086,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 1.029,
|
||||
"sql": 0.046
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 83.8
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 1.929
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 30000,
|
||||
"rows": 30000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 15.9,
|
||||
"requests": {
|
||||
"s3_list": 30,
|
||||
"s3_head": 0,
|
||||
"s3_get": 30000,
|
||||
"s3_delete": 0,
|
||||
"sql": 31
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 3.239,
|
||||
"sql": 0.157
|
||||
},
|
||||
"hashed_bytes": 8031553,
|
||||
"max_rss_mib": 84.4
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 16.714
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 30000,
|
||||
"rows": 30000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 16.148,
|
||||
"requests": {
|
||||
"s3_list": 30,
|
||||
"s3_head": 0,
|
||||
"s3_get": 30000,
|
||||
"s3_delete": 0,
|
||||
"sql": 31
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 3.373,
|
||||
"sql": 0.138
|
||||
},
|
||||
"hashed_bytes": 8031553,
|
||||
"max_rss_mib": 84.4
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 16.989
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 30000,
|
||||
"rows": 30000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 15.709,
|
||||
"requests": {
|
||||
"s3_list": 30,
|
||||
"s3_head": 0,
|
||||
"s3_get": 30000,
|
||||
"s3_delete": 0,
|
||||
"sql": 31
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 3.159,
|
||||
"sql": 0.149
|
||||
},
|
||||
"hashed_bytes": 8031553,
|
||||
"max_rss_mib": 84.3
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 16.534
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 30000,
|
||||
"rows": 30000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 3.317,
|
||||
"requests": {
|
||||
"s3_list": 30,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 31
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 3.146,
|
||||
"sql": 0.147
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 83.9
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 4.189
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 30000,
|
||||
"rows": 30000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 3.378,
|
||||
"requests": {
|
||||
"s3_list": 30,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 31
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 3.209,
|
||||
"sql": 0.146
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 83.9
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 4.234
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 30000,
|
||||
"rows": 30000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 3.315,
|
||||
"requests": {
|
||||
"s3_list": 30,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 31
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 3.148,
|
||||
"sql": 0.144
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 83.9
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 4.168
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
{
|
||||
"date": "2026-10-29T01:40:48Z",
|
||||
"commit": "5ca2cdc",
|
||||
"pins": {
|
||||
"S3_CPUS": "2",
|
||||
"S3_MEMORY": "3g",
|
||||
"S3_CPUSET": "11-12",
|
||||
"PG_CPUSET": "13-14",
|
||||
"RECONCILE_CPUSET": "15"
|
||||
},
|
||||
"limits": [
|
||||
"/mtusi2026lab4-postgres-1 cpus=2000000000 memory=1073741824 cpuset=13-14",
|
||||
"/mtusi2026lab4-s3-1 cpus=2000000000 memory=3221225472 cpuset=11-12"
|
||||
],
|
||||
"seeds": [
|
||||
{
|
||||
"added": 999,
|
||||
"rows_total": 1000,
|
||||
"object_bytes": 264,
|
||||
"seconds": {
|
||||
"s3_put": 1.078,
|
||||
"pg_copy": 0.017
|
||||
},
|
||||
"target": 1000
|
||||
},
|
||||
{
|
||||
"added": 9000,
|
||||
"rows_total": 10000,
|
||||
"object_bytes": 264,
|
||||
"seconds": {
|
||||
"s3_put": 22.064,
|
||||
"pg_copy": 0.118
|
||||
},
|
||||
"target": 10000
|
||||
},
|
||||
{
|
||||
"added": 20000,
|
||||
"rows_total": 30000,
|
||||
"object_bytes": 264,
|
||||
"seconds": {
|
||||
"s3_put": 152.798,
|
||||
"pg_copy": 0.268
|
||||
},
|
||||
"target": 30000
|
||||
}
|
||||
],
|
||||
"results": [
|
||||
{
|
||||
"objects": 1000,
|
||||
"mode": "deep",
|
||||
"runs": 3,
|
||||
"seconds_median": 0.505,
|
||||
"seconds_all": [
|
||||
0.524,
|
||||
0.49,
|
||||
0.505
|
||||
],
|
||||
"wall_seconds_median": 1.31,
|
||||
"us_per_object": 505.0,
|
||||
"s3_list_wait_median": 0.083,
|
||||
"sql_wait_median": 0.01,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 1000,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"max_rss_mib_median": 83.4,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found_nonzero": {}
|
||||
},
|
||||
{
|
||||
"objects": 1000,
|
||||
"mode": "shallow",
|
||||
"runs": 3,
|
||||
"seconds_median": 0.096,
|
||||
"seconds_all": [
|
||||
0.105,
|
||||
0.096,
|
||||
0.096
|
||||
],
|
||||
"wall_seconds_median": 0.908,
|
||||
"us_per_object": 96.0,
|
||||
"s3_list_wait_median": 0.081,
|
||||
"sql_wait_median": 0.008,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"max_rss_mib_median": 82.7,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found_nonzero": {}
|
||||
},
|
||||
{
|
||||
"objects": 10000,
|
||||
"mode": "deep",
|
||||
"runs": 3,
|
||||
"seconds_median": 5.252,
|
||||
"seconds_all": [
|
||||
5.261,
|
||||
5.252,
|
||||
5.179
|
||||
],
|
||||
"wall_seconds_median": 6.104,
|
||||
"us_per_object": 525.2,
|
||||
"s3_list_wait_median": 1.028,
|
||||
"sql_wait_median": 0.048,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 10000,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"max_rss_mib_median": 84.3,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found_nonzero": {}
|
||||
},
|
||||
{
|
||||
"objects": 10000,
|
||||
"mode": "page100",
|
||||
"runs": 3,
|
||||
"seconds_median": 2.241,
|
||||
"seconds_all": [
|
||||
2.157,
|
||||
2.241,
|
||||
2.434
|
||||
],
|
||||
"wall_seconds_median": 3.084,
|
||||
"us_per_object": 224.1,
|
||||
"s3_list_wait_median": 2.126,
|
||||
"sql_wait_median": 0.101,
|
||||
"requests": {
|
||||
"s3_list": 100,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 101
|
||||
},
|
||||
"max_rss_mib_median": 81.1,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found_nonzero": {}
|
||||
},
|
||||
{
|
||||
"objects": 10000,
|
||||
"mode": "shallow",
|
||||
"runs": 3,
|
||||
"seconds_median": 1.086,
|
||||
"seconds_all": [
|
||||
1.058,
|
||||
1.09,
|
||||
1.086
|
||||
],
|
||||
"wall_seconds_median": 1.929,
|
||||
"us_per_object": 108.6,
|
||||
"s3_list_wait_median": 1.029,
|
||||
"sql_wait_median": 0.046,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"max_rss_mib_median": 83.8,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found_nonzero": {}
|
||||
},
|
||||
{
|
||||
"objects": 30000,
|
||||
"mode": "deep",
|
||||
"runs": 3,
|
||||
"seconds_median": 15.9,
|
||||
"seconds_all": [
|
||||
15.9,
|
||||
16.148,
|
||||
15.709
|
||||
],
|
||||
"wall_seconds_median": 16.714,
|
||||
"us_per_object": 530.0,
|
||||
"s3_list_wait_median": 3.239,
|
||||
"sql_wait_median": 0.149,
|
||||
"requests": {
|
||||
"s3_list": 30,
|
||||
"s3_head": 0,
|
||||
"s3_get": 30000,
|
||||
"s3_delete": 0,
|
||||
"sql": 31
|
||||
},
|
||||
"max_rss_mib_median": 84.4,
|
||||
"scanned": {
|
||||
"objects": 30000,
|
||||
"rows": 30000
|
||||
},
|
||||
"found_nonzero": {}
|
||||
},
|
||||
{
|
||||
"objects": 30000,
|
||||
"mode": "shallow",
|
||||
"runs": 3,
|
||||
"seconds_median": 3.317,
|
||||
"seconds_all": [
|
||||
3.317,
|
||||
3.378,
|
||||
3.315
|
||||
],
|
||||
"wall_seconds_median": 4.189,
|
||||
"us_per_object": 110.6,
|
||||
"s3_list_wait_median": 3.148,
|
||||
"sql_wait_median": 0.146,
|
||||
"requests": {
|
||||
"s3_list": 30,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 31
|
||||
},
|
||||
"max_rss_mib_median": 83.9,
|
||||
"scanned": {
|
||||
"objects": 30000,
|
||||
"rows": 30000
|
||||
},
|
||||
"found_nonzero": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
date: 2026-10-29T01:40:48Z pins: {'S3_CPUS': '2', 'S3_MEMORY': '3g', 'S3_CPUSET': '11-12', 'PG_CPUSET': '13-14', 'RECONCILE_CPUSET': '15'}
|
||||
objects mode runs t_med,s wall,s us/obj list,s sql,s lists sqls gets rss,MiB
|
||||
1000 deep 3 0.505 1.31 505.0 0.083 0.010 1 2 1000 83.4
|
||||
1000 shallow 3 0.096 0.91 96.0 0.081 0.008 1 2 0 82.7
|
||||
10000 deep 3 5.252 6.10 525.2 1.028 0.048 10 11 10000 84.3
|
||||
10000 page100 3 2.241 3.08 224.1 2.126 0.101 100 101 0 81.1
|
||||
10000 shallow 3 1.086 1.93 108.6 1.029 0.046 10 11 0 83.8
|
||||
30000 deep 3 15.900 16.71 530.0 3.239 0.149 30 31 30000 84.4
|
||||
30000 shallow 3 3.317 4.19 110.6 3.148 0.146 30 31 0 83.9
|
||||
@@ -0,0 +1,29 @@
|
||||
date: 2026-10-29T00:50Z commit: a335f65
|
||||
Первый прогон make reconcile-cost: RustFS с лимитом 1 CPU / 1 GiB (S3_MEMORY=1g, cpuset 12), PostgreSQL cpuset 13-14,
|
||||
reconciler cpuset 15. Точки 1k и 10k сняты полностью (n1000-*.json, n10000-*.json, по 3 прогона).
|
||||
Наполнение до 100k прервано вручную: скорость PutObject упала с ~240 объектов/с (первые 2283) до ~11 объектов/с.
|
||||
$ ls /data/messenger-attachments/attachments | wc -l 45381, через 20 с 45602
|
||||
журнал RustFS: "PutObject store write remains in flight" > 5 с при 31-32 запросах в полёте
|
||||
cgroup RustFS: memory.events max=297 (упор в лимит 1 GiB), memory.stat anon 515 MiB, file 289 MiB,
|
||||
kernel 157 MiB (slab), CPU 100-113 % при лимите 1 CPU
|
||||
Вывод: RustFS держит в памяти метаданные пропорционально числу объектов; на 1 GiB при ~45k объектов cgroup
|
||||
постоянно вытесняет страничный кэш, запись идёт через reclaim. Повторный прогон — с RustFS 2 CPU / 3 GiB.
|
||||
Стенд после прерывания сброшен (make reset-data): 45k объектов без строк в замер не попали.
|
||||
|
||||
date: 2026-10-29T01:40Z commit: 7dca40c
|
||||
Второй прогон: RustFS 2 CPU / 3 GiB (cpuset 11-12), наполнение 16 параллельными PutObject. Точки 1k и 10k сняты,
|
||||
наполнение к 100k снова прервано: ≥65 объектов/с в районе 13-20k, ~13 объектов/с на 27 752 объектах.
|
||||
памяти хватает: memory.events max=0, anon 507 MiB, file 129 MiB, kernel 76 MiB
|
||||
после остановки записи CPU RustFS падает со 190 % до 1 % — фоновый сканер ни при чём
|
||||
40 последовательных PutObject по 264 B через rc: 1,99 с в префиксе attachments/ (27 752 объекта)
|
||||
против 1,03 с в пустом префиксе (оба времени со стартом контейнера ~0,7 с), т. е. ~32 и ~8 мс на запись
|
||||
Вывод: стоимость записи в RustFS 1.0.4 растёт с числом объектов под одним префиксом, а параллельные записи
|
||||
в один префикс только мешают друг другу. 100k объектов в один префикс на этом стенде не наполнить за разумное
|
||||
время; матрица снята до N = 30 000 при 4 параллельных записях. Сырые отчёты 1k/10k второго прогона заменены
|
||||
повторным прогоном с той же конфигурацией.
|
||||
|
||||
date: 2026-10-30T06:51Z commit: 61dcb6b
|
||||
Дополнение. В итоговой конфигурации (RustFS 2 CPU / 3 GiB, 4 параллельных PutObject) наполнение 30k → 100k заняло
|
||||
1580 с, ≈ 44 объекта/с против ≈ 148 на отрезке 10k → 30k: запись по-прежнему дорожает с ростом префикса, но идёт.
|
||||
Точка 100k снята (cost/summary.json, cost/n100000-*.json). Вывод «100k не наполнить за разумное время» выше
|
||||
относится к двум прерванным попыткам в прежних конфигурациях.
|
||||
@@ -0,0 +1,44 @@
|
||||
date: 2026-10-29T00:24:32Z
|
||||
$ docker stats --no-stream --all
|
||||
NAME CPU % MEM USAGE / LIMIT MEM % PIDS
|
||||
mtusi2026lab5-worker-1 2.22% 244.4MiB / 1GiB 23.87% 11
|
||||
mtusi2026lab4-api-2 0.25% 121.8MiB / 512MiB 23.80% 12
|
||||
mtusi2026lab4-api-1 12.63% 144MiB / 512MiB 28.13% 13
|
||||
mtusi2026lab4-migrate-1 0.00% 0B / 0B 0.00% 0
|
||||
mtusi2026lab4-s3-init-1 0.00% 0B / 0B 0.00% 0
|
||||
mtusi2026lab4-postgres-1 0.93% 47.48MiB / 1GiB 4.64% 10
|
||||
mtusi2026lab4-lb-1 0.04% 17.23MiB / 128MiB 13.46% 17
|
||||
mtusi2026lab4-valkey-1 0.06% 12.81MiB / 128MiB 10.01% 6
|
||||
mtusi2026lab4-s3-1 0.90% 59.34MiB / 512MiB 11.59% 14
|
||||
review-lab3-k6-run-5d2c16202cba 3.32% 20.96MiB / 512MiB 4.09% 8
|
||||
mtusi2026lab5-relay-1 0.42% 78.39MiB / 192MiB 40.83% 4
|
||||
mtusi2026lab5-api-1 1.60% 176.7MiB / 512MiB 34.50% 13
|
||||
mtusi2026lab5-api-2 4.56% 177MiB / 512MiB 34.56% 13
|
||||
mtusi2026lab5-migrate-1 0.00% 0B / 0B 0.00% 0
|
||||
review-lab3-api-2 5.00% 106.5MiB / 512MiB 20.81% 11
|
||||
review-lab3-api-1 5.12% 141.7MiB / 512MiB 27.67% 12
|
||||
review-lab3-migrate-1 0.00% 0B / 0B 0.00% 0
|
||||
review-lab3-postgres-1 2.81% 93.32MiB / 1GiB 9.11% 22
|
||||
review-lab3-lb-1 2.05% 21MiB / 128MiB 16.40% 17
|
||||
review-lab3-valkey-1 0.40% 4.25MiB / 128MiB 3.32% 7
|
||||
mtusi2026lab5-s3-init-1 0.00% 0B / 0B 0.00% 0
|
||||
mtusi2026lab5-broker-1 45.76% 179.4MiB / 512MiB 35.03% 105
|
||||
mtusi2026lab5-postgres-1 0.84% 60.28MiB / 1GiB 5.89% 13
|
||||
mtusi2026lab5-lb-1 0.62% 18.96MiB / 128MiB 14.81% 17
|
||||
mtusi2026lab5-s3-1 2.89% 99.68MiB / 512MiB 19.47% 16
|
||||
mtusi2026lab5-valkey-1 0.13% 13.07MiB / 128MiB 10.21% 7
|
||||
infra-tsvision-backend-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-tsvision-consumer-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-minio-init-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-postgres-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-rabbitmq-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-minio-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-mediamtx-1 0.00% 0B / 0B 0.00% 0
|
||||
infra-dragonfly-1 0.00% 0B / 0B 0.00% 0
|
||||
boring_merkle 0.00% 0B / 0B 0.00% 0
|
||||
infallible_solomon 0.00% 0B / 0B 0.00% 0
|
||||
friendly_goldwasser 0.00% 0B / 0B 0.00% 0
|
||||
magical_noether 0.00% 0B / 0B 0.00% 0
|
||||
postgres 0.00% 0B / 0B 0.00% 0
|
||||
main_postgres 0.00% 0B / 0B 0.00% 0
|
||||
fulfilment-backend 0.00% 0B / 0B 0.00% 0
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 1.118,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 1000,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.138,
|
||||
"sql": 0.026
|
||||
},
|
||||
"hashed_bytes": 375553,
|
||||
"max_rss_mib": 83.1
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 3.176
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.862,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 1000,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.149,
|
||||
"sql": 0.018
|
||||
},
|
||||
"hashed_bytes": 375553,
|
||||
"max_rss_mib": 83.2
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 2.509
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.764,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 1000,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.103,
|
||||
"sql": 0.014
|
||||
},
|
||||
"hashed_bytes": 375553,
|
||||
"max_rss_mib": 83.4
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 1.946
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.124,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.099,
|
||||
"sql": 0.015
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 82.9
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 1.215
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.616,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.158,
|
||||
"sql": 0.019
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 82.6
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 2.967
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": false,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 1000,
|
||||
"rows": 1000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 0.196,
|
||||
"requests": {
|
||||
"s3_list": 1,
|
||||
"s3_head": 0,
|
||||
"s3_get": 0,
|
||||
"s3_delete": 0,
|
||||
"sql": 2
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 0.139,
|
||||
"sql": 0.02
|
||||
},
|
||||
"hashed_bytes": 0,
|
||||
"max_rss_mib": 82.7
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 2.166
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 12.954,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 10000,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 1.821,
|
||||
"sql": 0.127
|
||||
},
|
||||
"hashed_bytes": 2751553,
|
||||
"max_rss_mib": 84.3
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 14.836
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"skipped": false,
|
||||
"grace_seconds": 3600,
|
||||
"skew_seconds": 60,
|
||||
"deep": true,
|
||||
"page_size": 1000,
|
||||
"scanned": {
|
||||
"objects": 10000,
|
||||
"rows": 10000
|
||||
},
|
||||
"found": {
|
||||
"orphan_stale": 0,
|
||||
"orphan_fresh": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"pending_fresh": 0,
|
||||
"quarantined": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"fixed": {
|
||||
"orphan_stale": 0,
|
||||
"missing": 0,
|
||||
"size_mismatch": 0,
|
||||
"sha_mismatch": 0,
|
||||
"pending_stale": 0,
|
||||
"healed": 0
|
||||
},
|
||||
"rechecked": {},
|
||||
"errors": 0,
|
||||
"samples": {},
|
||||
"cost": {
|
||||
"seconds": 12.829,
|
||||
"requests": {
|
||||
"s3_list": 10,
|
||||
"s3_head": 0,
|
||||
"s3_get": 10000,
|
||||
"s3_delete": 0,
|
||||
"sql": 11
|
||||
},
|
||||
"waited_seconds": {
|
||||
"s3_list": 1.547,
|
||||
"sql": 0.156
|
||||
},
|
||||
"hashed_bytes": 2751553,
|
||||
"max_rss_mib": 84.7
|
||||
},
|
||||
"exit_code": 0,
|
||||
"wall_seconds": 15.588
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user