PEP-221: долгая история вне основной базы — history.db и архив логов #211

Merged
peppa-bot merged 6 commits from task/pep-221 into main 2026-11-23 17:20:06 +00:00
19 changed files with 908 additions and 23 deletions

View File

@ -54,6 +54,7 @@
- act_runner (PEP-233): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
## Решения
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
- Застрявшая задача (PEP-209): лечит `stuckTaskTick` — платформа сама на ревью/в «Готово», агенту — новый процесс (`restartAgent`: старый не вернёт MCP), не `sendToSession`. Новая причина задержки с повторами — `platformDelay` с `retryMin`/`retryAt`, суперадмину кнопки — `buttons: true`.

View File

@ -17,6 +17,7 @@ import {
resolveRunnerSettings,
getProjectBudget,
listJournal,
archivedLog,
taskBudgetView,
getEpic,
isSuperadmin,
@ -127,7 +128,11 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
const refining = task.status === "backlog" && intakePending(await getIntakeSettings(db, ref.project.id), task, intake) ? (intake?.stage ?? "analyst") : null;
const runs: CheckRunRow[] =
tab === "tests" && ci.sha
? (await db.select().from(checkRuns).where(eq(checkRuns.taskId, task.id)).orderBy(desc(checkRuns.updatedAt))).filter((r) => r.sha === ci.sha).sort((a, b) => a.check.localeCompare(b.check))
? (await db.select().from(checkRuns).where(eq(checkRuns.taskId, task.id)).orderBy(desc(checkRuns.updatedAt)))
.filter((r) => r.sha === ci.sha)
.sort((a, b) => a.check.localeCompare(b.check))
// PEP-221: a tail older than a day was moved to the log archive.
.map((r) => (r.logTail || r.state === "success" || r.state === "pending" ? r : { ...r, logTail: archivedLog("checks", r.id, r.updatedAt) }))
: [];
const pendingAccept = await getPendingAccept(db, task.id);
// PEP-150: a delay on the platform's side — one line instead of a message to the owner.

View File

@ -1,4 +1,4 @@
import { pausedProjectIds, listSessions, needsPerson, questionType, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core";
import { historyJournal, pausedProjectIds, listSessions, needsPerson, questionType, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core";
import { events, projects, questions, sessions, tasks } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { m } from "@peppa/shared/i18n";
@ -75,6 +75,27 @@ export async function taskActivity(taskId: number) {
const ss = await listSessions(db, { taskId });
// Steps of agents (PEP-33) have their own live feed.
const evs = await db.select().from(events).where(and(eq(events.taskId, taskId), ne(events.type, STEP_EVENT))).orderBy(desc(events.id)).limit(100);
// PEP-221: events of a closed story leave the main base after a week — the rest comes from the archive.
if (evs.length < 100) {
const seen = new Set(evs.map((e) => e.id));
for (const e of historyJournal({ taskId, excludeTypes: [STEP_EVENT], limit: 100 })) {
if (seen.has(e.id)) continue;
evs.push({
id: e.id,
projectId: e.projectId,
taskId: e.taskId,
sessionId: e.sessionId,
type: e.type,
payload: e.payload,
actorKind: e.actorKind as (typeof evs)[number]["actorKind"],
actorUserId: e.actorUserId,
actorChannel: e.actorChannel as (typeof evs)[number]["actorChannel"],
actorClientId: e.actorClient,
createdAt: e.createdAt,
});
}
evs.sort((a, b) => b.id - a.id).splice(100);
}
return { questions: qs, sessions: ss, events: evs };
}

View File

@ -0,0 +1,33 @@
## Хранилище по видам истории
| Вид | Где | Срок | Почему |
|---|---|---|---|
| Журнал «кто что сделал» (все события, кроме шума PEP-220) | `history.db`, таблица `journal` | `journalDays` = 90 | Читают постранично с фильтрами (проект, задача, автор, канал) — нужны индексы, значит SQLite. Отдельный файл, как `observe.db` (PEP-202): своя запись, свои индексы, основная база не блокируется. Ключ проекта, задачи, логин и имя клиента пишутся в строку — чтение не ходит в основную базу. |
| Факты метрик: смены статусов задач, лимиты | `history.db`, таблица `metric_events` | `metricsDays` = 365 | Медиану времени цикла и долю «с первого раза» нельзя собрать из суточных сумм — нужны факты по задаче. Строка ~100 байт, год такого — мегабайты. Это и есть «суточные агрегаты» в форме, из которой метрики считаются точно. |
| Хвосты логов проверок и выкладок | `$PEPPA_HOME/archive/<checks\|releases>/<день>.jsonl.gz` | `logDays` = 7 | Читают редко и по одной записи; файлы по дням сжимаются в разы и удаляются целиком. Дописывание — отдельным gzip-членом в конец файла (zlib читает склейку членов). |
| Ошибки продукта и сбои | Bugsink, мониторинг (PEP-58/202) | как там | Не дублируем. |
## Перенос
- Курсор `events.cursor` хранится в самой `history.db` и двигается в той же транзакции, что и вставка, — повтор после сбоя не теряет и не дублирует (`INSERT OR IGNORE` по id события).
- Берутся события с `id > cursor` по порядку, пачками по 5 000, не больше 20 пачек за проход; первая слишком свежая (моложе 10 минут) строка останавливает проход, чтобы курсор не перепрыгнул незаписанное.
- Шум PEP-220 (`NOISE_EVENTS`) не переносится, курсор его проходит.
- Хвост лога пишется в файл перед стиранием в основной базе; стирание делает перенос идемпотентным (строка без хвоста больше не выбирается), а повтор после сбоя между записью и стиранием даёт дубль строки в файле — читатель берёт последнюю запись с этим id.
## Что удаляется из основной базы
Событие уже в архиве (`id <= cursor`), старше `mainDays` (7 дней), не обсуждение задачи (`pm_comment`, `intake_note`, `proposal_approved` — их показывает страница принятой задачи и «Сводка готовых»), задача закрыта (`done` или в архиве) или события проекта без задачи, сессия события закончена или её нет. События открытых задач остаются: по ним работают ревьюер, эскалация модели, уточнение постановки, «Активность».
Почему 7 дней, а не 1: читатели с окнами до недели (лента переключений подписок, сводки входов eGov, признаки инъекций, ротация) остаются на основной базе без переписывания. Через неделю основная база выходит на плато: её размер больше не зависит от возраста системы.
## Читатели
- `listJournal`: основная база, затем архив с теми же фильтрами; слияние по id без повторов, новые сверху.
- `taskActivity` (вкладка «Активность»): добирает из архива до 100 строк.
- `projectMetrics`: `task_updated` и лимиты из основной базы ∪ `metric_events` (без повторов по id).
- «Подробнее» у упавшей проверки: хвост из основной базы, иначе из архива по id прогона и дню; журнал упавшей выкладки в задаче «Продукт должен открываться по ссылке» — так же.
- Дашборд суперадмина: «последняя активность» проекта и пользователя — максимум основной базы и архива.
## Копии
`backupDb` после копии основной базы делает `VACUUM INTO` для `history.db` (`history-<день>.db`, те же 7 штук). Сбой копии архива не портит копию основной базы — только сообщение администраторам. Файлы логов не копируются: срок 7 дней, они для разбора, не для восстановления.
## Решения
- `history.db` открывается через `node:sqlite` напрямую, без drizzle, как `observe.db`; схема — `PRAGMA user_version`.
- Сроки — поля `platform.retention` рядом с `workDays`/`stateDays` PEP-220.
- В тестах файл живёт в `PEPPA_HOME` теста.

View File

@ -0,0 +1,15 @@
## Why
После PEP-220 основная база держит журнал работы сутки, но деловая история (кто что сделал, смены статусов задач, лимиты) по-прежнему копится в `events` без срока, а хвосты логов проверок и выкладок через сутки просто стираются. Страницы работают по той же таблице и тормозят от её роста; разбор упавшей проверки через сутки невозможен.
## What Changes
- Отдельная SQLite-база `$PEPPA_HOME/history.db` (`PEPPA_HISTORY_DB`): журнал «кто что сделал» (90 дней) и факты для метрик — смены статусов задач и упоминания лимитов (год).
- Хвосты логов проверок и выкладок перед стиранием — в сжатые файлы по дням `$PEPPA_HOME/archive/<checks|releases>/<YYYY-MM-DD>.jsonl.gz` (7 дней).
- Уборка (`runRetention`, PEP-220) сначала переносит события в архив по курсору, пачками и идемпотентно, потом удаляет из основной базы деловые события закрытых задач и проекта старше `mainDays` (7 дней). Обсуждение задачи (`pm_comment`, `intake_note`, `proposal_approved`) остаётся в основной базе.
- Читатели: `/journal`, вкладка «Журнал» проекта, автор в «Активности» задачи и сама «Активность» — дочитывают из архива; метрики проекта считают смены статусов и лимиты из основной базы и архива; «Подробнее» у упавшей проверки и журнал упавшей выкладки — из архива; «последняя активность» дашборда суперадмина — с архивом.
- Сроки — в `platform.retention`: `mainDays`, `journalDays` (90), `metricsDays` (365), `logDays` (7).
- Ежедневная копия базы копирует и `history.db`.
- Bugsink и мониторинг не дублируются: в архив идут только события Пеппы и логи.
## Impact
- Новый модуль `packages/core/src/history.ts`, правки `retention.ts`, `audit.ts`, `analytics.ts`, `backup.ts`, `platform-dashboard.ts`, страница задачи и `queries.ts` веба, `runner/product-link.ts`.
- Миграций основной базы нет; `history.db` создаётся и обновляется сама (`PRAGMA user_version`).

View File

@ -0,0 +1,60 @@
## ADDED Requirements
### Requirement: Деловая история переносится в архив до удаления
Система SHALL при уборке переносить события (кроме журнала работы) в отдельную базу `history.db` по курсору, пачками и идемпотентно, и только после переноса удалять из основной базы события закрытых задач и проекта старше `platform.retention.mainDays` (7 дней); обсуждение задачи в основной базе остаётся.
#### Scenario: Событие закрытой задачи уходит в архив и удаляется из основной базы
- **GIVEN** у принятой задачи есть событие «смена статуса» десятидневной давности
- **WHEN** вачдог выполняет уборку
- **THEN** события нет в основной базе
- **AND** оно есть в архиве с ключом задачи и автором
#### Scenario: Повторный перенос ничего не дублирует
- **GIVEN** уборка уже перенесла события в архив
- **WHEN** уборка запускается ещё раз
- **THEN** в архиве столько же строк журнала, сколько было
#### Scenario: Событие открытой задачи и комментарий остаются в основной базе
- **GIVEN** событие открытой задачи и комментарий владельца к принятой задаче десятидневной давности
- **WHEN** вачдог выполняет уборку
- **THEN** оба события остались в основной базе
- **AND** оба есть в архиве
### Requirement: Журнал и метрики читают архив
Система SHALL показывать в журнале (`/journal`, вкладка проекта, «Активность» задачи) и метриках проекта историю из архива за `journalDays` (90 дней) и `metricsDays` (365 дней) соответственно, без повторов строк.
#### Scenario: Журнал показывает событие, удалённое из основной базы
- **GIVEN** событие принятой задачи перенесено в архив и удалено из основной базы
- **WHEN** суперадмин открывает журнал проекта
- **THEN** событие видно с ключом задачи и автором
#### Scenario: Метрики считают задачу, история которой в архиве
- **GIVEN** задача прошла «в работе» → «готово» на этой неделе, и её смены статусов есть только в архиве
- **WHEN** открываются метрики проекта
- **THEN** за неделю видна одна принятая задача и время цикла
#### Scenario: Журнал старше срока удаляется из архива
- **GIVEN** в архиве есть событие старше 90 дней
- **WHEN** вачдог выполняет уборку
- **THEN** события нет в архиве журнала
### Requirement: Хвосты логов проверок и выкладок хранятся в архиве 7 дней
Система SHALL перед стиранием хвоста лога проверки или выкладки в основной базе записывать его в сжатый файл дня и отдавать его в «Подробнее» упавшей проверки; файлы старше `logDays` (7 дней) удаляются.
#### Scenario: Хвост упавшей проверки читается из архива
- **GIVEN** хвост лога упавшей проверки старше суток стёрт уборкой в основной базе
- **WHEN** открывается «Подробнее» этой проверки
- **THEN** виден тот же хвост лога
#### Scenario: Старые файлы логов удаляются
- **GIVEN** файл логов проверок десятидневной давности
- **WHEN** вачдог выполняет уборку
- **THEN** файла нет
### Requirement: Архив попадает в ежедневную копию
Система SHALL вместе с ежедневной копией основной базы делать копию `history.db`.
#### Scenario: Копия архива рядом с копией базы
- **GIVEN** архив существует
- **WHEN** вачдог делает ежедневную копию
- **THEN** рядом с копией базы лежит проверенная копия архива за тот же день

View File

@ -0,0 +1,14 @@
## 1. Архив
- [x] 1.1 `core/history.ts`: `history.db` (схема, открытие), перенос событий по курсору, `metric_events`, уборка архива по срокам
- [x] 1.2 Логи проверок и выкладок в `archive/<вид>/<день>.jsonl.gz`: запись, чтение по id, удаление старых файлов
- [x] 1.3 `runRetention`: перенос → хвосты в файлы → стирание; удаление деловых событий из основной базы после `mainDays`; сроки в `platform.retention`
## 2. Читатели
- [x] 2.1 `listJournal` и `taskActivity` дочитывают архив
- [x] 2.2 `projectMetrics` со сменами статусов и лимитами из архива
- [x] 2.3 «Подробнее» упавшей проверки и журнал упавшей выкладки — из архива; последняя активность на дашборде
## 3. Копии и проверка
- [x] 3.1 `backupDb` копирует `history.db`
- [x] 3.2 Тесты: перенос, повторный запуск, чтение журнала и метрик после удаления из основной базы, логи
- [x] 3.3 Проверки, память, архив change, PR

View File

@ -31,3 +31,62 @@ TBD - created by archiving change pep-220-retention. Update Purpose after archiv
- **GIVEN** `PEPPA_RETENTION=off`
- **WHEN** вачдог делает часовой тик
- **THEN** ничего не удаляется
### Requirement: Деловая история переносится в архив до удаления
Система SHALL при уборке переносить события (кроме журнала работы) в отдельную базу `history.db` по курсору, пачками и идемпотентно, и только после переноса удалять из основной базы события закрытых задач и проекта старше `platform.retention.mainDays` (7 дней); обсуждение задачи в основной базе остаётся.
#### Scenario: Событие закрытой задачи уходит в архив и удаляется из основной базы
- **GIVEN** у принятой задачи есть событие «смена статуса» десятидневной давности
- **WHEN** вачдог выполняет уборку
- **THEN** события нет в основной базе
- **AND** оно есть в архиве с ключом задачи и автором
#### Scenario: Повторный перенос ничего не дублирует
- **GIVEN** уборка уже перенесла события в архив
- **WHEN** уборка запускается ещё раз
- **THEN** в архиве столько же строк журнала, сколько было
#### Scenario: Событие открытой задачи и комментарий остаются в основной базе
- **GIVEN** событие открытой задачи и комментарий владельца к принятой задаче десятидневной давности
- **WHEN** вачдог выполняет уборку
- **THEN** оба события остались в основной базе
- **AND** оба есть в архиве
### Requirement: Журнал и метрики читают архив
Система SHALL показывать в журнале (`/journal`, вкладка проекта, «Активность» задачи) и метриках проекта историю из архива за `journalDays` (90 дней) и `metricsDays` (365 дней) соответственно, без повторов строк.
#### Scenario: Журнал показывает событие, удалённое из основной базы
- **GIVEN** событие принятой задачи перенесено в архив и удалено из основной базы
- **WHEN** суперадмин открывает журнал проекта
- **THEN** событие видно с ключом задачи и автором
#### Scenario: Метрики считают задачу, история которой в архиве
- **GIVEN** задача прошла «в работе» → «готово» на этой неделе, и её смены статусов есть только в архиве
- **WHEN** открываются метрики проекта
- **THEN** за неделю видна одна принятая задача и время цикла
#### Scenario: Журнал старше срока удаляется из архива
- **GIVEN** в архиве есть событие старше 90 дней
- **WHEN** вачдог выполняет уборку
- **THEN** события нет в архиве журнала
### Requirement: Хвосты логов проверок и выкладок хранятся в архиве 7 дней
Система SHALL перед стиранием хвоста лога проверки или выкладки в основной базе записывать его в сжатый файл дня и отдавать его в «Подробнее» упавшей проверки; файлы старше `logDays` (7 дней) удаляются.
#### Scenario: Хвост упавшей проверки читается из архива
- **GIVEN** хвост лога упавшей проверки старше суток стёрт уборкой в основной базе
- **WHEN** открывается «Подробнее» этой проверки
- **THEN** виден тот же хвост лога
#### Scenario: Старые файлы логов удаляются
- **GIVEN** файл логов проверок десятидневной давности
- **WHEN** вачдог выполняет уборку
- **THEN** файла нет
### Requirement: Архив попадает в ежедневную копию
Система SHALL вместе с ежедневной копией основной базы делать копию `history.db`.
#### Scenario: Копия архива рядом с копией базы
- **GIVEN** архив существует
- **WHEN** вачдог делает ежедневную копию
- **THEN** рядом с копией базы лежит проверенная копия архива за тот же день

View File

@ -6,6 +6,7 @@ import { m as tr } from "@peppa/shared/i18n";
import { codeReviews, events, questions, sessions, tasks, type Db } from "@peppa/db";
import { and, eq, gte, inArray } from "drizzle-orm";
import { epicSpend, spendOf, type EpicSpend, type Spend } from "./budgets.ts";
import { historyMetricEvents } from "./history.ts";
export interface MetricsBucket {
/** Monday 00:00 of the week (local time); the period start for the summary. */
@ -84,13 +85,22 @@ export async function projectMetrics(db: Db, projectId: number, o: { weeks?: num
// Status history of every story (whole history: a story finished now may have started long ago).
const evs = taskIds.length
? await db
.select({ taskId: events.taskId, payload: events.payload, createdAt: events.createdAt })
.select({ id: events.id, taskId: events.taskId, payload: events.payload, createdAt: events.createdAt })
.from(events)
.where(and(eq(events.projectId, projectId), eq(events.type, "task_updated")))
.orderBy(events.id)
: [];
// PEP-221: status changes moved to history.db (closed stories after a week) — merged by event id.
const archived = historyMetricEvents(projectId, { since: new Date(from) });
const known = new Set(evs.map((e) => e.id));
const statusChanges = [
...evs,
...archived
.filter((a) => a.type === "task_updated" && !known.has(a.eventId))
.map((a) => ({ id: a.eventId, taskId: a.taskId, payload: { from: { status: a.fromStatus ?? undefined }, to: { status: a.toStatus ?? undefined } } as unknown, createdAt: a.at })),
].sort((a, b) => a.id - b.id);
const facts = new Map<number, StoryFacts>();
for (const e of evs) {
for (const e of statusChanges) {
if (e.taskId == null) continue;
const p = e.payload as { from?: { status?: string }; to?: { status?: string } } | null;
const to = p?.to?.status;
@ -115,9 +125,14 @@ export async function projectMetrics(db: Db, projectId: number, o: { weeks?: num
.from(questions)
.where(and(eq(questions.projectId, projectId), gte(questions.createdAt, new Date(from))));
const limits = await db
.select({ type: events.type, payload: events.payload, createdAt: events.createdAt })
.select({ id: events.id, type: events.type, payload: events.payload, createdAt: events.createdAt })
.from(events)
.where(and(eq(events.projectId, projectId), inArray(events.type, ["usage_limit", "stop_failure"]), gte(events.createdAt, new Date(from))));
const limitIds = new Set(limits.map((l) => l.id));
for (const a of archived) {
if (a.type === "task_updated" || limitIds.has(a.eventId)) continue;
limits.push({ id: a.eventId, type: a.type, payload: { error: a.error ?? undefined }, createdAt: a.at });
}
const bucket = (a: number, b: number): MetricsBucket => {
const inRange = (t: number | null | undefined) => t != null && t >= a && t < b;

View File

@ -4,6 +4,7 @@ import { events, oauthClients, projects, tasks, users, type Db } from "@peppa/db
import { formatTaskKey } from "@peppa/shared";
import { and, desc, eq, inArray, lt, type SQL } from "drizzle-orm";
import { actorColumns, type ActorChannel, type ActorKind } from "./actor.ts";
import { historyJournal } from "./history.ts";
/** An event done by the current actor (settings changes and other actions without a session). */
export async function logEvent(db: Db, e: { projectId: number; taskId?: number | null; sessionId?: number | null; type: string; payload?: unknown }) {
@ -80,9 +81,10 @@ export async function listJournal(db: Db, f: JournalFilter = {}): Promise<Journa
.orderBy(desc(events.id))
.limit(Math.min(f.limit ?? 100, 500) * (f.excludeTypes?.length ? 3 : 1));
const skip = new Set(f.excludeTypes ?? []);
return rows
const limit = Math.min(f.limit ?? 100, 500);
const fresh: JournalEntry[] = rows
.filter((r) => !skip.has(r.e.type))
.slice(0, Math.min(f.limit ?? 100, 500))
.slice(0, limit)
.map((r) => ({
id: r.e.id,
type: r.e.type,
@ -98,6 +100,29 @@ export async function listJournal(db: Db, f: JournalFilter = {}): Promise<Journa
actorLogin: r.login,
actorClient: r.client ?? r.e.actorClientId,
}));
// PEP-221: older history lives in history.db; rows still in both places are taken from the main base.
if (fresh.length >= limit) return fresh;
const seen = new Set(fresh.map((e) => e.id));
const old = historyJournal({ ...f, limit })
.filter((e) => !seen.has(e.id))
.map(
(e): JournalEntry => ({
id: e.id,
type: e.type,
payload: e.payload,
createdAt: e.createdAt,
projectId: e.projectId,
projectKey: e.projectKey,
taskId: e.taskId,
taskKey: e.taskKey,
sessionId: e.sessionId,
actorKind: e.actorKind as ActorKind | null,
actorChannel: e.actorChannel as ActorChannel | null,
actorLogin: e.actorLogin,
actorClient: e.actorClient,
}),
);
return [...fresh, ...old].sort((a, b) => b.id - a.id).slice(0, limit);
}
/** «anna · веб», «pm · MCP (ChatGPT)», «агент · раннер #12», «FORGE · вачдог». Null for pre-PEP-48 events. */

View File

@ -6,6 +6,8 @@ import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { alertAdmins } from "./monitor.ts";
import { getSetting, setSetting } from "./settings.ts";
import { historyDb, historyDbPath } from "./history.ts";
import { existsSync } from "node:fs";
const DAY_MS = 24 * 3600_000;
const KEY = "backup:last";
@ -39,7 +41,7 @@ export function verifyBackup(file: string): void {
* checked (`verifyBackup`); a failed copy is removed and the platform admins are told; the
* services keep running either way.
*/
export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?: string; error?: string; skipped?: boolean }> {
export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?: string; history?: string; error?: string; skipped?: boolean }> {
const now = o.now ?? new Date();
const log = o.log ?? (() => {});
const last = await getSetting<{ at: number }>(db, KEY);
@ -66,8 +68,31 @@ export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?:
return { file };
}
const keep = o.keep ?? 7;
const copies = readdirSync(dir).filter((f) => /^peppa-\d{4}-\d{2}-\d{2}\.db$/.test(f)).sort();
for (const old of copies.slice(0, Math.max(0, copies.length - keep))) rmSync(join(dir, old), { force: true });
// PEP-221: the archive (journal 90 days, metrics a year) is copied next to it; its failure does not
// spoil the copy of the main base. Log files of the archive are not copied (7 days, for analysis only).
let history: string | undefined;
if (existsSync(historyDbPath())) {
const hfile = join(dir, `history-${day}.db`);
try {
rmSync(hfile, { force: true });
historyDb().prepare("VACUUM INTO ?").run(hfile);
const copy = new DatabaseSync(hfile, { readOnly: true });
try {
const r = copy.prepare("PRAGMA quick_check").get() as { quick_check?: string } | undefined;
if (r?.quick_check !== "ok") throw new Error(tr("копия повреждена: {v}", { v: r?.quick_check ?? tr("нет ответа") }));
} finally {
copy.close();
}
history = hfile;
} catch (e) {
rmSync(hfile, { force: true });
await alertAdmins(db, `backup:history:fail:${day}`, tr("⚠️ Резервная копия архива FORGE не сделана: {reason}", { reason: (e as Error).message }), log);
}
}
for (const re of [/^peppa-\d{4}-\d{2}-\d{2}\.db$/, /^history-\d{4}-\d{2}-\d{2}\.db$/]) {
const copies = readdirSync(dir).filter((f) => re.test(f)).sort();
for (const old of copies.slice(0, Math.max(0, copies.length - keep))) rmSync(join(dir, old), { force: true });
}
await setSetting(db, KEY, { at: now.getTime(), file });
// PEP-214: statistics for the query planner next to the daily copy (0x10002 = also analyse
// tables that never had statistics). A failure here must not spoil the backup.
@ -76,6 +101,6 @@ export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?:
} catch (e) {
log(`optimize failed: ${(e as Error).message}`);
}
log(`backup: ${file}`);
return { file };
log(`backup: ${file}${history ? ` + ${history}` : ""}`);
return { file, history };
}

View File

@ -0,0 +1,386 @@
// PEP-221: long history outside the main database (see the change's design.md).
// · `history.db` (PEPPA_HISTORY_DB, default $PEPPA_HOME/history.db, like observe.db of PEP-202):
// `journal` — «who did what», `journalDays` (90); `metric_events` — status changes of stories and
// limit hits for the project metrics, `metricsDays` (365);
// · `$PEPPA_HOME/archive/<checks|releases>/<YYYY-MM-DD>.jsonl.gz` — log tails of checks and releases,
// `logDays` (7), one gzip member appended per batch.
// The main database's events are copied by a cursor kept in history.db itself (moved in the same
// transaction as the rows), so a rerun neither loses nor duplicates anything.
import { DatabaseSync } from "node:sqlite";
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { gunzipSync, gzipSync } from "node:zlib";
import { dirname, join } from "node:path";
import { peppaHome } from "@peppa/shared";
import type { Db } from "@peppa/db";
const DAY = 86_400_000;
/** Events younger than this are not copied yet: the cursor must never pass a row still being written. */
const SETTLE_MS = 10 * 60_000;
export const HISTORY_BATCH = 5000;
const MAX_BATCHES = 20;
const SCHEMA = [
`CREATE TABLE journal (
id INTEGER PRIMARY KEY,
project_id INTEGER NOT NULL,
project_key TEXT NOT NULL,
task_id INTEGER,
task_key TEXT,
session_id INTEGER,
type TEXT NOT NULL,
payload TEXT,
actor_kind TEXT,
actor_channel TEXT,
actor_user_id INTEGER,
actor_login TEXT,
actor_client TEXT,
created_at INTEGER NOT NULL
)`,
`CREATE INDEX journal_project ON journal (project_id, id)`,
`CREATE INDEX journal_task ON journal (task_id, id)`,
`CREATE INDEX journal_created ON journal (created_at)`,
`CREATE INDEX journal_user ON journal (actor_user_id, created_at)`,
`CREATE TABLE metric_events (
event_id INTEGER PRIMARY KEY,
project_id INTEGER NOT NULL,
task_id INTEGER,
type TEXT NOT NULL,
from_status TEXT,
to_status TEXT,
error TEXT,
at INTEGER NOT NULL
)`,
`CREATE INDEX metric_events_project ON metric_events (project_id, type, at)`,
`CREATE INDEX metric_events_at ON metric_events (at)`,
`CREATE TABLE history_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
];
const MIGRATIONS: string[][] = [SCHEMA];
const opened = new Map<string, DatabaseSync>();
export const historyDbPath = () => process.env.PEPPA_HISTORY_DB ?? join(peppaHome(), "history.db");
export const archiveDir = () => join(dirname(historyDbPath()), "archive");
/** The history database of this process (opened and migrated on first use). */
export function historyDb(): DatabaseSync {
const path = historyDbPath();
const known = opened.get(path);
if (known) return known;
mkdirSync(dirname(path), { recursive: true });
const db = new DatabaseSync(path);
db.exec("PRAGMA busy_timeout = 5000");
db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA synchronous = NORMAL");
const version = Number((db.prepare("PRAGMA user_version").get() as { user_version: number }).user_version);
for (let v = version; v < MIGRATIONS.length; v++) {
db.exec("BEGIN IMMEDIATE");
try {
for (const sql of MIGRATIONS[v]!) db.exec(sql);
db.exec(`PRAGMA user_version = ${v + 1}`);
db.exec("COMMIT");
} catch (e) {
db.exec("ROLLBACK");
throw e;
}
}
opened.set(path, db);
return db;
}
/** Tests: forget opened files. */
export function closeHistoryDb(): void {
for (const db of opened.values()) db.close();
opened.clear();
}
/** Opened only if the file exists: readers must not create an empty archive on a fresh system. */
function historyIfAny(): DatabaseSync | null {
if (!opened.has(historyDbPath()) && !existsSync(historyDbPath())) return null;
return historyDb();
}
const meta = (h: DatabaseSync, key: string): string | null => (h.prepare("SELECT value FROM history_meta WHERE key = ?").get(key) as { value: string } | undefined)?.value ?? null;
const setMeta = (h: DatabaseSync, key: string, value: string) => h.prepare("INSERT INTO history_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
/** The id of the last main-database event already in the archive (0 — nothing yet). */
export const historyCursor = (): number => Number(meta(historyDb(), "events.cursor") ?? 0);
type MainEvent = {
id: number;
project_id: number;
project_key: string;
task_id: number | null;
task_number: number | null;
session_id: number | null;
type: string;
payload: string | null;
actor_kind: string | null;
actor_channel: string | null;
actor_user_id: number | null;
login: string | null;
client: string | null;
actor_client_id: string | null;
created_at: number;
};
const LIMIT_TYPES = new Set(["usage_limit", "stop_failure"]);
/**
* Copies events of the main database (except `skipTypes` — the work journal) into `journal` and
* `metric_events`, in id order, in batches. Returns how many rows were copied.
*/
export function archiveEvents(db: Db, o: { now?: Date; skipTypes?: readonly string[] } = {}): number {
const h = historyDb();
const main = db.$client.db;
const settled = (o.now ?? new Date()).getTime() - SETTLE_MS;
const skip = new Set(o.skipTypes ?? []);
const select = main.prepare(
`SELECT e.id, e.project_id, p.key AS project_key, e.task_id, t.number AS task_number, e.session_id, e.type, e.payload,
e.actor_kind, e.actor_channel, e.actor_user_id, u.login, c.name AS client, e.actor_client_id, e.created_at
FROM events e JOIN projects p ON p.id = e.project_id
LEFT JOIN tasks t ON t.id = e.task_id
LEFT JOIN users u ON u.id = e.actor_user_id
LEFT JOIN oauth_clients c ON c.id = e.actor_client_id
WHERE e.id > ? ORDER BY e.id LIMIT ${HISTORY_BATCH}`,
);
const insJournal = h.prepare(
`INSERT OR IGNORE INTO journal (id, project_id, project_key, task_id, task_key, session_id, type, payload, actor_kind, actor_channel, actor_user_id, actor_login, actor_client, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
);
const insMetric = h.prepare(`INSERT OR IGNORE INTO metric_events (event_id, project_id, task_id, type, from_status, to_status, error, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
let copied = 0;
for (let b = 0; b < MAX_BATCHES; b++) {
const cursor = historyCursor();
const rows = select.all(cursor) as unknown as MainEvent[];
if (!rows.length) break;
let last = cursor;
let stopped = false;
h.exec("BEGIN IMMEDIATE");
try {
for (const r of rows) {
if (Number(r.created_at) > settled) {
stopped = true;
break;
}
last = Number(r.id);
if (skip.has(r.type)) continue;
const taskKey = r.task_number != null ? `${r.project_key}-${r.task_number}` : null;
insJournal.run(r.id, r.project_id, r.project_key, r.task_id, taskKey, r.session_id, r.type, r.payload, r.actor_kind, r.actor_channel, r.actor_user_id, r.login, r.client ?? r.actor_client_id, r.created_at);
copied++;
let p: { from?: { status?: string }; to?: { status?: string }; error?: string } | null = null;
try {
p = r.payload ? JSON.parse(r.payload) : null;
} catch {}
if (r.type === "task_updated" && p?.to?.status) insMetric.run(r.id, r.project_id, r.task_id, r.type, p.from?.status ?? null, p.to.status, null, r.created_at);
else if (LIMIT_TYPES.has(r.type)) insMetric.run(r.id, r.project_id, r.task_id, r.type, null, null, typeof p?.error === "string" ? p.error : null, r.created_at);
}
if (last > cursor) setMeta(h, "events.cursor", String(last));
h.exec("COMMIT");
} catch (e) {
h.exec("ROLLBACK");
throw e;
}
if (stopped || rows.length < HISTORY_BATCH) break;
}
return copied;
}
/** Drops archive rows past their terms. */
export function expireHistory(o: { now?: Date; journalDays: number; metricsDays: number }): { journal: number; metrics: number } {
const h = historyIfAny();
if (!h) return { journal: 0, metrics: 0 };
const now = (o.now ?? new Date()).getTime();
const journal = Number(h.prepare("DELETE FROM journal WHERE created_at < ?").run(now - o.journalDays * DAY).changes);
const metrics = Number(h.prepare("DELETE FROM metric_events WHERE at < ?").run(now - o.metricsDays * DAY).changes);
return { journal, metrics };
}
// ── readers ──────────────────────────────────────────────────────────────────
export interface HistoryJournalRow {
id: number;
projectId: number;
projectKey: string;
taskId: number | null;
taskKey: string | null;
sessionId: number | null;
type: string;
payload: unknown;
actorKind: string | null;
actorChannel: string | null;
actorUserId: number | null;
actorLogin: string | null;
actorClient: string | null;
createdAt: Date;
}
export interface HistoryJournalFilter {
projectIds?: number[];
projectId?: number;
taskId?: number;
actorKind?: string;
channel?: string;
excludeTypes?: string[];
before?: number;
limit?: number;
}
const parse = (s: string | null): unknown => {
if (s == null) return null;
try {
return JSON.parse(s);
} catch {
return s;
}
};
/** Archived journal rows, newest first, with the same filters as `listJournal`. */
export function historyJournal(f: HistoryJournalFilter = {}): HistoryJournalRow[] {
if (f.projectIds && !f.projectIds.length) return [];
const h = historyIfAny();
if (!h) return [];
const where: string[] = [];
const args: (number | string)[] = [];
if (f.projectIds) {
where.push(`project_id IN (${f.projectIds.map(() => "?").join(",")})`);
args.push(...f.projectIds);
}
if (f.projectId != null) where.push("project_id = ?"), args.push(f.projectId);
if (f.taskId != null) where.push("task_id = ?"), args.push(f.taskId);
if (f.actorKind) where.push("actor_kind = ?"), args.push(f.actorKind);
if (f.channel) where.push("actor_channel = ?"), args.push(f.channel);
if (f.before) where.push("id < ?"), args.push(f.before);
if (f.excludeTypes?.length) {
where.push(`type NOT IN (${f.excludeTypes.map(() => "?").join(",")})`);
args.push(...f.excludeTypes);
}
const rows = h
.prepare(`SELECT * FROM journal ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY id DESC LIMIT ?`)
.all(...args, Math.min(f.limit ?? 100, 500)) as Record<string, unknown>[];
return rows.map((r) => ({
id: Number(r.id),
projectId: Number(r.project_id),
projectKey: String(r.project_key),
taskId: r.task_id == null ? null : Number(r.task_id),
taskKey: (r.task_key as string | null) ?? null,
sessionId: r.session_id == null ? null : Number(r.session_id),
type: String(r.type),
payload: parse(r.payload as string | null),
actorKind: (r.actor_kind as string | null) ?? null,
actorChannel: (r.actor_channel as string | null) ?? null,
actorUserId: r.actor_user_id == null ? null : Number(r.actor_user_id),
actorLogin: (r.actor_login as string | null) ?? null,
actorClient: (r.actor_client as string | null) ?? null,
createdAt: new Date(Number(r.created_at)),
}));
}
export interface MetricEvent {
eventId: number;
taskId: number | null;
type: string;
fromStatus: string | null;
toStatus: string | null;
error: string | null;
at: Date;
}
/** Archived facts for the project metrics: status changes (whole term) and limit hits since `since`. */
export function historyMetricEvents(projectId: number, o: { since?: Date } = {}): MetricEvent[] {
const h = historyIfAny();
if (!h) return [];
const rows = h
.prepare(`SELECT * FROM metric_events WHERE project_id = ? AND (type = 'task_updated' OR at >= ?) ORDER BY event_id`)
.all(projectId, o.since?.getTime() ?? 0) as Record<string, unknown>[];
return rows.map((r) => ({
eventId: Number(r.event_id),
taskId: r.task_id == null ? null : Number(r.task_id),
type: String(r.type),
fromStatus: (r.from_status as string | null) ?? null,
toStatus: (r.to_status as string | null) ?? null,
error: (r.error as string | null) ?? null,
at: new Date(Number(r.at)),
}));
}
/** Last archived activity of every project and every person (the superadmin's dashboard). */
export function historyLastActivity(): { projects: Map<number, Date>; users: Map<number, Date> } {
const h = historyIfAny();
if (!h) return { projects: new Map(), users: new Map() };
const ps = h.prepare("SELECT project_id AS k, max(created_at) AS at FROM journal GROUP BY project_id").all() as { k: number; at: number }[];
const us = h.prepare("SELECT actor_user_id AS k, max(created_at) AS at FROM journal WHERE actor_user_id IS NOT NULL GROUP BY actor_user_id").all() as { k: number; at: number }[];
const map = (xs: { k: number; at: number }[]) => new Map(xs.map((x) => [Number(x.k), new Date(Number(x.at))]));
return { projects: map(ps), users: map(us) };
}
// ── log tails ────────────────────────────────────────────────────────────────
export type LogKind = "checks" | "releases";
export interface ArchivedLog {
id: number;
projectId: number;
taskId?: number | null;
sha?: string | null;
check?: string | null;
env?: string | null;
state?: string | null;
at: number;
log: string;
}
const dayOf = (ms: number) => new Date(ms).toISOString().slice(0, 10);
const logFile = (kind: LogKind, day: string) => join(archiveDir(), kind, `${day}.jsonl.gz`);
/** Appends log tails to the day files (one gzip member per day per call). */
export function archiveLogs(kind: LogKind, rows: ArchivedLog[]): void {
const byDay = new Map<string, string[]>();
for (const r of rows) {
const day = dayOf(r.at);
byDay.set(day, [...(byDay.get(day) ?? []), JSON.stringify(r)]);
}
for (const [day, lines] of byDay) {
const file = logFile(kind, day);
mkdirSync(dirname(file), { recursive: true });
appendFileSync(file, gzipSync(lines.join("\n") + "\n"));
}
}
function readDay(kind: LogKind, day: string): ArchivedLog[] {
const file = logFile(kind, day);
if (!existsSync(file)) return [];
try {
return gunzipSync(readFileSync(file))
.toString("utf8")
.split("\n")
.filter(Boolean)
.map((l) => JSON.parse(l) as ArchivedLog);
} catch {
return [];
}
}
/** The archived tail of check run / release `id` written around `at` (that day or the next). */
export function archivedLog(kind: LogKind, id: number, at: Date | number): string | null {
const ms = typeof at === "number" ? at : at.getTime();
let found: string | null = null;
for (const day of [dayOf(ms), dayOf(ms + DAY)]) for (const r of readDay(kind, day)) if (r.id === id) found = r.log; // the last copy wins
return found;
}
/** Removes day files older than `days`. */
export function expireLogs(o: { now?: Date; days: number }): number {
const cut = dayOf((o.now ?? new Date()).getTime() - o.days * DAY);
let n = 0;
for (const kind of ["checks", "releases"] as const) {
const dir = join(archiveDir(), kind);
if (!existsSync(dir)) continue;
for (const f of readdirSync(dir)) {
const m = /^(\d{4}-\d{2}-\d{2})\.jsonl\.gz$/.exec(f);
if (m && m[1]! < cut) {
rmSync(join(dir, f), { force: true });
n++;
}
}
}
return n;
}

View File

@ -109,3 +109,4 @@ export * from "./accept-digest.ts";
export * from "./connections.ts";
export * from "./edge-dns.ts";
export * from "./retention.ts";
export * from "./history.ts";

View File

@ -5,6 +5,7 @@ import { m as tr } from "@peppa/shared/i18n";
import { and, isNull, max, sql } from "drizzle-orm";
import { projectAgentWarning } from "./onboarding.ts";
import { productUrls } from "./product.ts";
import { historyLastActivity } from "./history.ts";
const HOUR = 3600_000;
/** Agent sessions that are doing a task right now (not waiting, not finished). */
@ -104,6 +105,10 @@ export async function platformDashboard(db: Db, now = new Date()): Promise<Platf
const openBy = new Map(open.map((r) => [r.projectId, { n: Number(r.n), oldest: r.oldest == null ? null : Number(r.oldest) }]));
const activeBy = new Map(activity.map((r) => [r.projectId, r.at ? new Date(r.at) : null]));
const userActiveBy = new Map(userActivity.map((r) => [r.userId!, r.at ? new Date(r.at) : null]));
// PEP-221: a quiet project's events may be only in the archive by now.
const archived = historyLastActivity();
for (const [by, from] of [[activeBy, archived.projects], [userActiveBy, archived.users]] as const)
for (const [k, at] of from) if (!by.get(k) || by.get(k)! < at) by.set(k, at);
const loginOf = new Map(allUsers.map((u) => [u.id, u.login]));
const projectRows: DashboardProject[] = [];

View File

@ -7,6 +7,7 @@
// writes of every other process.
import type { Db } from "@peppa/db";
import { getSetting, setSetting } from "./settings.ts";
import { archiveEvents, archiveLogs, expireHistory, expireLogs, historyCursor, type ArchivedLog, type LogKind } from "./history.ts";
export const RETENTION_KEY = "platform.retention";
export const RETENTION_LAST_KEY = "retention.last";
@ -34,18 +35,26 @@ export const NOISE_EVENTS = [
/** `settings` keys that live minutes (login flows, link codes, brute-force counters). */
export const TEMP_SETTING_PREFIXES = ["egov.flow:", "google.flow:", "chat.link:", "auth.fail:"] as const;
export type RetentionConfig = { workDays: number; stateDays: number };
export const DEFAULT_RETENTION: RetentionConfig = { workDays: 1, stateDays: 7 };
/**
* PEP-221: `mainDays` — business events of closed stories and of the project stay this long in the
* main database once archived; `journalDays`, `metricsDays`, `logDays` — terms of the archive.
*/
export type RetentionConfig = { workDays: number; stateDays: number; mainDays: number; journalDays: number; metricsDays: number; logDays: number };
export const DEFAULT_RETENTION: RetentionConfig = { workDays: 1, stateDays: 7, mainDays: 7, journalDays: 90, metricsDays: 365, logDays: 7 };
/** The discussion of a story: shown on the page of an accepted story and in the ready digest. */
export const MAIN_KEEP_EVENTS = ["pm_comment", "intake_note", "proposal_approved"] as const;
export async function getRetention(db: Db): Promise<RetentionConfig> {
const saved = (await getSetting<Partial<RetentionConfig>>(db, RETENTION_KEY)) ?? {};
const days = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : d);
return { workDays: days(saved.workDays, DEFAULT_RETENTION.workDays), stateDays: days(saved.stateDays, DEFAULT_RETENTION.stateDays) };
const k = (key: keyof RetentionConfig) => days(saved[key], DEFAULT_RETENTION[key]);
return { workDays: k("workDays"), stateDays: k("stateDays"), mainDays: k("mainDays"), journalDays: k("journalDays"), metricsDays: k("metricsDays"), logDays: k("logDays") };
}
export const setRetention = (db: Db, c: Partial<RetentionConfig>) => setSetting(db, RETENTION_KEY, c);
export type RetentionResult = { at: number; deleted: Record<string, number>; total: number; freedBytes: number; dbBytes: number; vacuumed: boolean };
export type RetentionResult = { at: number; deleted: Record<string, number>; archived?: Record<string, number>; total: number; freedBytes: number; dbBytes: number; vacuumed: boolean };
type Raw = { prepare(sql: string): { run(...a: unknown[]): { changes: number | bigint }; get(...a: unknown[]): unknown } };
const raw = (db: Db) => (db as unknown as { $client: Raw }).$client;
@ -62,12 +71,32 @@ function purge(db: Db, table: string, where: string, params: unknown[]): number
return total;
}
/** Clears a text column of `where` rows in batches. */
function blank(db: Db, table: string, column: string, where: string, params: unknown[]): number {
/** PEP-221: what goes into the log archive of a row about to lose its tail. */
const LOG_ROW: Record<LogKind, { table: string; cols: string; map: (r: Record<string, unknown>) => ArchivedLog }> = {
checks: {
table: "check_runs",
cols: `id, project_id, task_id, sha, "check", state, updated_at, log_tail`,
map: (r) => ({ id: Number(r.id), projectId: Number(r.project_id), taskId: r.task_id == null ? null : Number(r.task_id), sha: r.sha as string, check: r.check as string, state: r.state as string, at: Number(r.updated_at), log: String(r.log_tail) }),
},
releases: {
table: "releases",
cols: "id, project_id, sha, env, status, updated_at, log_tail",
map: (r) => ({ id: Number(r.id), projectId: Number(r.project_id), sha: r.sha as string, env: r.env as string, state: r.status as string, at: Number(r.updated_at), log: String(r.log_tail) }),
},
};
/** Clears a text column of `where` rows in batches; log tails are archived first (PEP-221). */
function blank(db: Db, table: string, column: string, where: string, params: unknown[], archive?: LogKind): number {
const c = raw(db);
let total = 0;
for (let i = 0; i < MAX_BATCHES; i++) {
const n = Number(c.prepare(`UPDATE ${table} SET ${column} = NULL WHERE id IN (SELECT id FROM ${table} WHERE ${column} IS NOT NULL AND ${where} LIMIT ${BATCH})`).run(...params).changes);
const pick = `SELECT id FROM ${table} WHERE ${column} IS NOT NULL AND ${where} LIMIT ${BATCH}`;
if (archive) {
const spec = LOG_ROW[archive];
const rows = db.$client.db.prepare(`SELECT ${spec.cols} FROM ${spec.table} WHERE id IN (${pick})`).all(...(params as never[])) as Record<string, unknown>[];
if (rows.length) archiveLogs(archive, rows.map(spec.map));
}
const n = Number(c.prepare(`UPDATE ${table} SET ${column} = NULL WHERE id IN (${pick})`).run(...params).changes);
total += n;
if (n < BATCH) break;
}
@ -87,6 +116,8 @@ export async function runRetention(db: Db, o: { now?: Date; daily?: boolean } =
const state = now - cfg.stateDays * 86_400_000;
const deleted: Record<string, number> = {};
const marks = NOISE_EVENTS.map(() => "?").join(",");
// PEP-221: business history goes to history.db first; only archived rows may leave the main base.
const archived: Record<string, number> = { events: archiveEvents(db, { now: o.now, skipTypes: NOISE_EVENTS }) };
deleted.events = purge(db, "events", `type IN (${marks}) AND created_at < ?`, [...NOISE_EVENTS, work]);
// The last run of every check of a story still open keeps its log; the rest of the tails go.
@ -97,10 +128,26 @@ export async function runRetention(db: Db, o: { now?: Date; daily?: boolean } =
`updated_at < ? AND NOT (task_id IS NOT NULL AND task_id IN (SELECT id FROM tasks WHERE status NOT IN ('done') AND archived_at IS NULL)
AND NOT EXISTS (SELECT 1 FROM check_runs n WHERE n.task_id = check_runs.task_id AND n."check" = check_runs."check" AND n.id > check_runs.id))`,
[work],
"checks",
);
deleted.check_runs = purge(db, "check_runs", `updated_at < ? AND (task_id IS NULL OR task_id IN (SELECT id FROM tasks WHERE status = 'done' OR archived_at IS NOT NULL))`, [state]);
deleted.check_runs = purge(db, "check_runs", `updated_at < ? AND log_tail IS NULL AND (task_id IS NULL OR task_id IN (SELECT id FROM tasks WHERE status = 'done' OR archived_at IS NOT NULL))`, [state]);
// The newest release of every environment keeps its log (the first thing to read after a failure).
deleted.release_log = blank(db, "releases", "log_tail", `updated_at < ? AND EXISTS (SELECT 1 FROM releases n WHERE n.project_id = releases.project_id AND n.env = releases.env AND n.id > releases.id)`, [work]);
deleted.release_log = blank(db, "releases", "log_tail", `updated_at < ? AND EXISTS (SELECT 1 FROM releases n WHERE n.project_id = releases.project_id AND n.env = releases.env AND n.id > releases.id)`, [work], "releases");
// Archived business events of closed stories and of the project, past `mainDays`. Events of an open
// story stay (reviewer, model escalation, refinement read them), and so does a story's discussion.
const keep = MAIN_KEEP_EVENTS.map(() => "?").join(",");
deleted.history_events = purge(
db,
"events",
`id <= ? AND created_at < ? AND type NOT IN (${keep})
AND (task_id IS NULL OR task_id IN (SELECT id FROM tasks WHERE status = 'done' OR archived_at IS NOT NULL))
AND (session_id IS NULL OR session_id IN (SELECT id FROM sessions WHERE status IN ('done','failed')))`,
[historyCursor(), now - cfg.mainDays * 86_400_000, ...MAIN_KEEP_EVENTS],
);
const exp = expireHistory({ now: o.now, journalDays: cfg.journalDays, metricsDays: cfg.metricsDays });
archived.expired_journal = exp.journal;
archived.expired_metrics = exp.metrics;
archived.expired_log_files = expireLogs({ now: o.now, days: cfg.logDays });
// A sent message of an open question stays: the bot matches its repeats against it (PEP-151).
deleted.telegram_outbox = purge(
db,
@ -135,7 +182,7 @@ export async function runRetention(db: Db, o: { now?: Date; daily?: boolean } =
const pageSize = pragma(db, "page_size");
// What can be reused by new rows without growing the file.
const reusable = pragma(db, "freelist_count") * pageSize;
const result: RetentionResult = { at: now, deleted, total, freedBytes: freedBytes || reusable, dbBytes: pragma(db, "page_count") * pageSize, vacuumed };
const result: RetentionResult = { at: now, deleted, archived, total, freedBytes: freedBytes || reusable, dbBytes: pragma(db, "page_count") * pageSize, vacuumed };
await setSetting(db, RETENTION_LAST_KEY, result);
return result;
}

View File

@ -5,6 +5,7 @@
// one-time offer of that mode to projects created before it existed.
import { m } from "@peppa/shared/i18n";
import {
archivedLog,
askPmProject,
createTask,
getProductLinkState,
@ -83,7 +84,7 @@ export async function ensureProductLinkTask(db: Db, project: Project, o: Product
const healthy = recent.some((r) => r.status === "healthy") || !!(await currentReleases(db, project.id)).staging;
if (!failed && (healthy || done.length === 0)) return null;
const description = productLinkDescription({ doneStories: done.length, failed: failed ? { status: failed.status, sha: failed.sha, reason: failed.reason, logTail: failed.logTail, runUrl: failed.runUrl } : null });
const description = productLinkDescription({ doneStories: done.length, failed: failed ? { status: failed.status, sha: failed.sha, reason: failed.reason, logTail: failed.logTail ?? archivedLog("releases", failed.id, failed.updatedAt), runUrl: failed.runUrl } : null });
const ref = await createTask(db, { projectId: project.id, title: PRODUCT_LINK_TITLE, description, origin: "acceptance", severity: "breakage" });
// Already formulated: «продакт» and «аналитик» of the intake skip it.
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: PRODUCT_LINK_TITLE, description }, attempts: 0, note: "заведена FORGE: продукт не открывается по ссылке" });

View File

@ -392,6 +392,7 @@ export const bot: Dict = {
"копия повреждена: {v}": "backup is corrupted: {v}",
"нет места на диске": "no disk space",
"⚠️ Резервная копия базы FORGE не сделана: {reason}": "⚠️ FORGE database backup failed: {reason}",
"⚠️ Резервная копия архива FORGE не сделана: {reason}": "⚠️ FORGE archive backup failed: {reason}",
"Неверный адрес push-подписки": "Invalid push subscription address",
"Неверные ключи push-подписки": "Invalid push subscription keys",
"Неизвестный секрет платформы: {name}": "Unknown platform secret: {name}",

View File

@ -391,6 +391,7 @@ export const bot: Dict = {
"копия повреждена: {v}": "көшірме бүлінген: {v}",
"нет места на диске": "дискіде орын жоқ",
"⚠️ Резервная копия базы FORGE не сделана: {reason}": "⚠️ FORGE базасының резервтік көшірмесі жасалмады: {reason}",
"⚠️ Резервная копия архива FORGE не сделана: {reason}": "⚠️ FORGE мұрағатының резервтік көшірмесі жасалмады: {reason}",
"Неверный адрес push-подписки": "push-жазылымның мекенжайы қате",
"Неверные ключи push-подписки": "push-жазылымның кілттері қате",
"Неизвестный секрет платформы: {name}": "Платформаның белгісіз құпиясы: {name}",

View File

@ -0,0 +1,170 @@
// PEP-221: long history outside the main database. Tests are named after the spec scenarios.
import assert from "node:assert/strict";
import { after, describe, test } from "node:test";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { gzipSync } from "node:zlib";
// helpers must load first: it sets the isolated test env that runner modules read on load.
import { core, db, teardown } from "./helpers.ts";
import { checkRuns, events, tasks } from "@peppa/db";
import { eq, inArray } from "drizzle-orm";
after(teardown);
const DAY = 86_400_000;
const NOW = new Date();
const ago = (days: number) => new Date(NOW.getTime() - days * DAY);
let seq = 0;
async function fixture(status: "done" | "in_progress" = "done") {
const key = `H${String.fromCharCode(65 + seq++)}`;
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: null });
const t = await core.createTask(db, { projectId: p.id, title: `Задача ${key}`, description: "x" });
await db.update(tasks).set({ status }).where(eq(tasks.id, t.task.id));
return { p, taskId: t.task.id, key: `${key}-${t.task.number}` };
}
const journalRows = () => Number((core.historyDb().prepare("SELECT count(*) AS n FROM journal").get() as { n: number }).n);
const mainIds = async (ids: number[]) => (await db.select({ id: events.id }).from(events).where(inArray(events.id, ids))).map((r) => r.id);
describe("PEP-221 history archive", () => {
test("Scenario: Событие закрытой задачи уходит в архив и удаляется из основной базы", async () => {
const { p, taskId, key } = await fixture("done");
const [e] = await db
.insert(events)
.values({ projectId: p.id, taskId, type: "task_updated", payload: { from: { status: "review" }, to: { status: "done" } }, actorKind: "system", actorChannel: "watchdog", createdAt: ago(10) })
.returning();
const r = await core.runRetention(db, { now: NOW });
assert.ok(r.archived!.events! >= 1);
assert.deepEqual(await mainIds([e!.id]), []);
const [row] = core.historyJournal({ taskId });
assert.equal(row?.id, e!.id);
assert.equal(row?.taskKey, key);
assert.equal(row?.actorKind, "system");
assert.deepEqual(row?.payload, { from: { status: "review" }, to: { status: "done" } });
});
test("Scenario: Повторный перенос ничего не дублирует", async () => {
const { p, taskId } = await fixture("done");
await db.insert(events).values([1, 2, 3].map((i) => ({ projectId: p.id, taskId, type: "started", payload: { i }, createdAt: ago(2) })));
await core.runRetention(db, { now: NOW });
const n = journalRows();
const cursor = core.historyCursor();
const again = await core.runRetention(db, { now: NOW });
assert.equal(again.archived!.events, 0);
assert.equal(journalRows(), n);
assert.equal(core.historyCursor(), cursor);
// A crash between commit and delete: the same rows copied again stay single.
assert.equal(core.archiveEvents(db, { now: NOW }), 0);
});
test("Scenario: Событие открытой задачи и комментарий остаются в основной базе", async () => {
const open = await fixture("in_progress");
const done = await fixture("done");
const rows = await db
.insert(events)
.values([
{ projectId: open.p.id, taskId: open.taskId, type: "task_updated", payload: { to: { status: "in_progress" } }, createdAt: ago(10) },
{ projectId: done.p.id, taskId: done.taskId, type: "pm_comment", payload: { text: "Поправьте шапку", login: "pm" }, createdAt: ago(10) },
])
.returning();
await core.runRetention(db, { now: NOW });
const ids = rows.map((r) => r.id);
assert.deepEqual((await mainIds(ids)).sort(), [...ids].sort());
assert.equal(core.historyJournal({ taskId: open.taskId }).length, 1);
assert.equal(core.historyJournal({ taskId: done.taskId }).length, 1);
});
test("Scenario: Свежие события и журнал работы в архив не попадают", async () => {
const { p, taskId } = await fixture("done");
const before = core.historyCursor();
const rows = await db
.insert(events)
.values([
{ projectId: p.id, taskId, type: "step", payload: {}, createdAt: ago(2) },
{ projectId: p.id, taskId, type: "started", payload: {}, createdAt: new Date(NOW.getTime() - 60_000) },
])
.returning();
await core.runRetention(db, { now: NOW });
assert.equal(core.historyJournal({ taskId }).length, 0, "шаг не переносится, свежее событие ждёт");
assert.ok(core.historyCursor() >= before && core.historyCursor() < rows[1]!.id, "курсор не перепрыгнул свежее событие");
assert.deepEqual(await mainIds([rows[1]!.id]), [rows[1]!.id]);
// The next run after it settles takes it.
assert.ok(core.archiveEvents(db, { now: new Date(NOW.getTime() + 11 * 60_000) }) >= 1);
assert.equal(core.historyJournal({ taskId }).length, 1);
});
test("Scenario: Журнал показывает событие, удалённое из основной базы", async () => {
const { p, taskId, key } = await fixture("done");
const [e] = await db.insert(events).values({ projectId: p.id, taskId, type: "repo_transferred", payload: { to: "org" }, actorKind: "user", actorChannel: "cli", createdAt: ago(20) }).returning();
const [fresh] = await db.insert(events).values({ projectId: p.id, type: "project_paused", payload: {}, createdAt: ago(1) }).returning();
await core.runRetention(db, { now: NOW });
assert.deepEqual(await mainIds([e!.id]), []);
const j = await core.listJournal(db, { projectId: p.id });
assert.deepEqual(
j.map((x) => x.id),
[fresh!.id, e!.id],
"без повторов, новые сверху",
);
assert.equal(j[1]!.taskKey, key);
assert.equal(core.actorLabel(j[1]!), "человек · CLI");
// Paging through `before` reaches the archive too.
assert.deepEqual((await core.listJournal(db, { projectId: p.id, before: fresh!.id })).map((x) => x.id), [e!.id]);
});
test("Scenario: Метрики считают задачу, история которой в архиве", async () => {
const { p, taskId } = await fixture("done");
const at = (h: number) => new Date(NOW.getTime() - h * 3_600_000);
// The cycle ended this week, but the main base keeps nothing of it.
const rows = await db
.insert(events)
.values([
{ projectId: p.id, taskId, type: "task_updated", payload: { from: { status: "backlog" }, to: { status: "in_progress" } }, createdAt: at(30) },
{ projectId: p.id, taskId, type: "task_updated", payload: { from: { status: "in_progress" }, to: { status: "done" } }, createdAt: at(20) },
{ projectId: p.id, taskId, type: "usage_limit", payload: {}, createdAt: at(25) },
])
.returning();
await core.runRetention(db, { now: NOW });
await db.delete(events).where(inArray(events.id, rows.map((r) => r.id)));
const m = await core.projectMetrics(db, p.id, { weeks: 2, now: NOW });
assert.equal(m.summary.done, 1);
assert.equal(Math.round(m.summary.cycleHoursMedian!), 10);
assert.equal(m.summary.limitHits, 1);
});
test("Scenario: Журнал старше срока удаляется из архива", async () => {
const { p } = await fixture("done");
const [e] = await db.insert(events).values({ projectId: p.id, type: "users_merged", payload: {}, createdAt: ago(100) }).returning();
await core.runRetention(db, { now: NOW });
assert.deepEqual(core.historyJournal({ projectId: p.id }).filter((x) => x.id === e!.id), []);
});
test("Scenario: Хвост упавшей проверки читается из архива", async () => {
const { p, taskId } = await fixture("done");
const updatedAt = ago(2);
const [run] = await db.insert(checkRuns).values({ projectId: p.id, taskId, sha: "f1", check: "test", state: "failure", logTail: "boom\nline 2", updatedAt, createdAt: updatedAt }).returning();
await core.runRetention(db, { now: NOW });
const [left] = await db.select().from(checkRuns).where(eq(checkRuns.id, run!.id));
assert.equal(left?.logTail ?? null, null, "в основной базе хвост стёрт");
assert.equal(core.archivedLog("checks", run!.id, updatedAt), "boom\nline 2");
// Two gzip members in one day file read as one.
core.archiveLogs("checks", [{ id: 999_999, projectId: p.id, at: updatedAt.getTime(), log: "second" }]);
assert.equal(core.archivedLog("checks", run!.id, updatedAt), "boom\nline 2");
assert.equal(core.archivedLog("checks", 999_999, updatedAt), "second");
});
test("Scenario: Старые файлы логов удаляются", async () => {
const dir = join(core.archiveDir(), "checks");
mkdirSync(dir, { recursive: true });
const old = join(dir, `${ago(10).toISOString().slice(0, 10)}.jsonl.gz`);
writeFileSync(old, gzipSync("{}\n"));
await core.runRetention(db, { now: NOW });
assert.equal(existsSync(old), false);
});
test("Scenario: Копия архива рядом с копией базы", async () => {
const dir = join(process.env.PEPPA_HOME!, "backups-test");
const r = await core.backupDb(db, { dir, force: true, now: NOW });
assert.ok(r.file && existsSync(r.file));
assert.ok(r.history && existsSync(r.history), "копия архива сделана");
assert.match(r.history!, /history-\d{4}-\d{2}-\d{2}\.db$/);
});
});