Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a873cb04f | ||
|
|
5c88088537 | ||
|
|
b0835fd43b | ||
|
|
76cd972bde | ||
|
|
fd57a3518d | ||
|
|
667a140c4e | ||
|
|
d8ac96e39d | ||
|
|
d725841ebc | ||
|
|
559f1804e6 | ||
|
|
ff1333d02c | ||
|
|
d3a93c64bd | ||
|
|
f7c1e7f790 |
No files matched your search
@@ -0,0 +1,152 @@
|
||||
name: DataStack CI Verification
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.gitea/workflows/datastack-ci.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
p01_only:
|
||||
description: Run P01 tests, typecheck, build and Windows clean-install only
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
quality_only:
|
||||
description: Run only TypeScript and ESLint after a focused P01 test type fix
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
node-regression:
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.quality_only != 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Install dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
- name: Build Node SDK
|
||||
run: |
|
||||
npm --prefix sdk/node/datastack install --no-audit --no-fund
|
||||
npm --prefix sdk/node/datastack run build
|
||||
- name: Run all TypeScript regression suites with bounded isolation
|
||||
run: |
|
||||
set +e
|
||||
failed=0
|
||||
total=0
|
||||
for file in tests/*.test.ts; do
|
||||
total=$((total + 1))
|
||||
echo "CI_SUITE_BEGIN $file"
|
||||
timeout --signal=TERM --kill-after=5s 70s npx --yes tsx@4.20.6 --test "$file"
|
||||
code=$?
|
||||
echo "CI_SUITE_EXIT $file $code"
|
||||
if [ "$code" -ne 0 ]; then failed=$((failed + 1)); fi
|
||||
done
|
||||
echo "CI_SUITE_SUMMARY total=$total failed=$failed"
|
||||
test "$total" -eq 24 || exit 1
|
||||
test "$failed" -eq 0
|
||||
|
||||
python-regression:
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.p01_only != 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Install Python toolchain
|
||||
run: |
|
||||
set -eu
|
||||
apt-get update -qq
|
||||
apt-get install -y python3 python3-venv python3-pip
|
||||
python3 -m venv /tmp/datastack-ci-venv
|
||||
/tmp/datastack-ci-venv/bin/python -m pip install -e ./sdk/python/datastack -e ./sdk-python
|
||||
- name: Run all Python SDK tests
|
||||
run: |
|
||||
set -eu
|
||||
/tmp/datastack-ci-venv/bin/python -m compileall -q ./sdk/python/datastack ./sdk-python
|
||||
/tmp/datastack-ci-venv/bin/python -m unittest discover -s tests -p '*_test.py' -v
|
||||
|
||||
quality:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Install dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
- name: TypeScript type check
|
||||
run: npx tsc --noEmit
|
||||
- name: ESLint
|
||||
run: npm run lint
|
||||
|
||||
production-build:
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.quality_only != 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Install dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
- name: Next.js production build
|
||||
run: |
|
||||
set -eu
|
||||
npm run build
|
||||
test -f .next/standalone/server.js
|
||||
|
||||
docker-image-build:
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.p01_only != 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 35
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Docker and Compose availability
|
||||
run: |
|
||||
set -eu
|
||||
docker --version
|
||||
docker compose version
|
||||
docker info
|
||||
- name: Validate Compose structure
|
||||
run: docker compose -f docker/docker-compose.yml config --no-interpolate --quiet
|
||||
- name: Build Docker images without running services
|
||||
run: |
|
||||
set -eu
|
||||
docker build -f docker/Dockerfile.server -t datastack-ci-ingestion .
|
||||
docker build -f docker/Dockerfile.web -t datastack-ci-web .
|
||||
docker build -f docker/Dockerfile.proxy -t datastack-ci-proxy .
|
||||
|
||||
windows-compatibility:
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.quality_only != 'true' }}
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 25
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Verify native Windows toolchain
|
||||
shell: powershell
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
node --version
|
||||
npm --version
|
||||
python --version
|
||||
git rev-parse HEAD
|
||||
- name: Install dependencies and compile Node SDK
|
||||
shell: powershell
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
# Verify the committed cross-platform lock without disposable regeneration.
|
||||
npm ci --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Committed-lock npm ci failed' }
|
||||
npm --prefix sdk/node/datastack install --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SDK install failed' }
|
||||
npm --prefix sdk/node/datastack run build
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SDK compilation failed' }
|
||||
@@ -0,0 +1,39 @@
|
||||
name: DataStack Docker Build CI
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.gitea/workflows/datastack-docker-ci.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
docker-build:
|
||||
runs-on: ubuntu-latest
|
||||
container: node:22-alpine
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- name: Provision isolated Docker CLI and Git tools
|
||||
run: |
|
||||
set -eu
|
||||
apk add --no-cache git docker-cli docker-cli-compose
|
||||
docker --version
|
||||
docker compose version
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Validate actual Compose configuration
|
||||
run: |
|
||||
set -eu
|
||||
docker compose -f docker/docker-compose.yml config --no-interpolate --quiet
|
||||
echo DATASTACK_COMPOSE_CONFIG_PASS
|
||||
- name: Check CI-only Docker daemon
|
||||
run: |
|
||||
set -eu
|
||||
docker info >/dev/null || { echo DOCKER_DAEMON_UNAVAILABLE; exit 3; }
|
||||
- name: Build all DataStack container images without deployment
|
||||
run: |
|
||||
set -eu
|
||||
docker build -f docker/Dockerfile.server -t datastack-ci-ingestion .
|
||||
docker build -f docker/Dockerfile.web -t datastack-ci-web .
|
||||
docker build -f docker/Dockerfile.proxy -t datastack-ci-proxy .
|
||||
echo DATASTACK_DOCKER_IMAGES_PASS
|
||||
@@ -0,0 +1,33 @@
|
||||
name: DataStack ESLint CI
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.gitea/workflows/datastack-eslint-ci.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
eslint-windows:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Install dependencies in isolated checkout
|
||||
shell: powershell
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
node --version
|
||||
npm --version
|
||||
npm install --package-lock-only --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Temporary lock regeneration failed' }
|
||||
npm ci --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { throw 'npm ci failed' }
|
||||
- name: Run full ESLint
|
||||
shell: powershell
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
npm run lint
|
||||
if ($LASTEXITCODE -ne 0) { throw 'ESLint check failed' }
|
||||
Write-Output 'DATASTACK_ESLINT_PASS'
|
||||
@@ -0,0 +1,38 @@
|
||||
name: DataStack Python SDK CI
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.gitea/workflows/datastack-python-ci.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
python-sdk-windows:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://dev.ivib.cc
|
||||
- name: Isolated Python 3.12 environment
|
||||
shell: powershell
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
python --version
|
||||
$venv = Join-Path $env:RUNNER_TEMP 'datastack-python-ci'
|
||||
python -m venv $venv
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Python virtual environment failed' }
|
||||
$py = Join-Path $venv 'Scripts\python.exe'
|
||||
& $py -m pip install -e ./sdk/python/datastack -e ./sdk-python
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Python SDK dependency install failed' }
|
||||
Write-Output 'PYTHON_CI_DEPS_READY'
|
||||
- name: Python SDK full regression
|
||||
shell: powershell
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$py = Join-Path $env:RUNNER_TEMP 'datastack-python-ci\Scripts\python.exe'
|
||||
& $py -m compileall -q ./sdk/python/datastack ./sdk-python
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Python SDK compile failed' }
|
||||
& $py -m unittest discover -s tests -p '*_test.py' -v
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Python SDK regression failed' }
|
||||
Write-Output 'DATASTACK_PYTHON_REGRESSION_PASS'
|
||||
+72
-6
@@ -650,6 +650,66 @@ export class DataBufferEngine {
|
||||
}
|
||||
|
||||
const executeFlush = async (): Promise<FlushResult> => {
|
||||
|
||||
// P02 R-02: examine CSV partitions before replay of an untrimmed Redis
|
||||
// batch. Streaming parsing limits memory and handles escaped/newline CSV.
|
||||
const excludeAlreadyPersisted = async (events: DataEvent[]): Promise<DataEvent[]> => {
|
||||
if (!events.length) return events;
|
||||
const fs = await import('node:fs');
|
||||
const path = await import('node:path');
|
||||
const zlib = await import('node:zlib');
|
||||
const { pipeline } = await import('node:stream/promises');
|
||||
const { Writable } = await import('node:stream');
|
||||
const { parse } = await import('csv-parse');
|
||||
const groups = new Map<string, {
|
||||
clientId: string; date: string; ids: Set<string>;
|
||||
}>();
|
||||
for (const event of events) {
|
||||
const clientId = String(event.clientId || 'unknown');
|
||||
const date = CSVStorageManager.extractSafePartitionDate(event.timestamp);
|
||||
const key = JSON.stringify([clientId, date]);
|
||||
if (!groups.has(key)) groups.set(key, { clientId, date, ids: new Set() });
|
||||
groups.get(key)!.ids.add(String(event.eventId));
|
||||
}
|
||||
const persisted = new Set<string>();
|
||||
for (const [groupKey, group] of groups) {
|
||||
const dir = CSVStorageManager.ensureClientDir(group.clientId);
|
||||
const entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() ||
|
||||
!/\.csv(?:\.gz)?$/.test(entry.name) ||
|
||||
CSVStorageManager.extractSafePartitionDate(
|
||||
entry.name.replace(/\.csv(?:\.gz)?$/, '').replace(/(?:-(?:part|gz)\d+)+$/, ''),
|
||||
) !== group.date) continue;
|
||||
const reader = fs.createReadStream(path.join(dir, entry.name));
|
||||
const parser = parse({ columns: true, bom: true, skip_empty_lines: true });
|
||||
const sink = new Writable({
|
||||
objectMode: true,
|
||||
write(row: { clientId?: string; eventId?: string }, _enc, done) {
|
||||
if (row.clientId === group.clientId && group.ids.has(String(row.eventId))) {
|
||||
persisted.add(JSON.stringify([groupKey, String(row.eventId)]));
|
||||
}
|
||||
done();
|
||||
},
|
||||
});
|
||||
if (entry.name.endsWith('.gz')) {
|
||||
await pipeline(reader, zlib.createGunzip(), parser, sink);
|
||||
} else {
|
||||
await pipeline(reader, parser, sink);
|
||||
}
|
||||
}
|
||||
}
|
||||
const batchSeen = new Set<string>();
|
||||
return events.filter((event) => {
|
||||
const key = JSON.stringify([String(event.clientId || 'unknown'),
|
||||
CSVStorageManager.extractSafePartitionDate(event.timestamp)]);
|
||||
const rowKey = JSON.stringify([key, String(event.eventId)]);
|
||||
if (persisted.has(rowKey) || batchSeen.has(rowKey)) return false;
|
||||
batchSeen.add(rowKey);
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
state.isFlushing = true;
|
||||
let totalWritten = 0;
|
||||
let lockTimedOut = false;
|
||||
@@ -793,9 +853,12 @@ export class DataBufferEngine {
|
||||
if (lockLost) break;
|
||||
|
||||
if (parsedBatch.length > 0) {
|
||||
const res = await CSVStorageManager.appendBatch(parsedBatch);
|
||||
totalWritten += res.written;
|
||||
for (const f of res.filesUpdated) filesSet.add(f);
|
||||
const unwritten = await excludeAlreadyPersisted(parsedBatch);
|
||||
if (unwritten.length > 0) {
|
||||
const res = await CSVStorageManager.appendBatch(unwritten);
|
||||
totalWritten += res.written;
|
||||
for (const f of res.filesUpdated) filesSet.add(f);
|
||||
}
|
||||
}
|
||||
|
||||
if (Date.now() - lastRenewAt >= renewIntervalMs) {
|
||||
@@ -845,9 +908,12 @@ export class DataBufferEngine {
|
||||
|
||||
if (validRamBatch.length > 0) {
|
||||
try {
|
||||
const res = await CSVStorageManager.appendBatch(validRamBatch);
|
||||
totalWritten += res.written;
|
||||
for (const f of res.filesUpdated) filesSet.add(f);
|
||||
const unwritten = await excludeAlreadyPersisted(validRamBatch);
|
||||
if (unwritten.length > 0) {
|
||||
const res = await CSVStorageManager.appendBatch(unwritten);
|
||||
totalWritten += res.written;
|
||||
for (const f of res.filesUpdated) filesSet.add(f);
|
||||
}
|
||||
} catch (err) {
|
||||
state.buffer.unshift(...validRamBatch);
|
||||
throw err;
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# DataStack — Production-Readiness Forensic Audit (Documentation Baseline)
|
||||
|
||||
Status: **BASELINE FORENSIC SNAPSHOT; P01 VERIFIED AND CLOSED (see closure appendix)**. Date: 2026-11-22 (Asia/Dhaka).
|
||||
Frozen source HEAD: `d725841ebc828d58cbe90f517da9e600f23c4630`. Local, Gitea `vibtools/DataStack`, GitLab `ivibtools/datastack`, and GitHub `JILLU-Games/DataStack` confirmed at this exact HEAD before writing these notes.
|
||||
Scope of this document: **evidence-backed CI and source review**, not proof that every production feature works. No Coolify live write, rollback, restart or deployment was conducted. Public GET `https://data.ivib.cc/api/health` returned `status: online`; full DB/Redis/MCP/S3 transaction health is not established.
|
||||
|
||||
## Findings classification
|
||||
|
||||
- **8 finding groups** from actual CI: **5 code/test/lockfile groups** (CI-01…05) and **3 CI infrastructure/security-review groups** (CI-06…08). **Not 43 separate bugs**: the 43 compiler errors belong to CI-05.
|
||||
- **2 failing assertions, 4 timeout suites** (24 TypeScript suites in run #45: 18 clean, 6 fail/timeout).
|
||||
- **3 extra source-observed reliability risks** (R-01…03) have NOT been reproduced as production failures; they require targeted fault injection before any fix or behavior change.
|
||||
- **Do not equate successful test/source feature with verified production runtime.**
|
||||
|
||||
## Eight confirmed findings / blockers
|
||||
|
||||
| ID | Severity* | Evidence (run/job) | Exact affected area | Verified observation | Planned phase |
|
||||
|---|---|---|---|---|---|
|
||||
| CI-01 | High | Run #42 job 63; #45 job 71 | `package-lock.json`, `package.json`; `.gitea/workflows/datastack-ci.yml` Windows job | Original Windows `npm ci` reports missing platform dependency entries; regenerate lock **only in runner** -> SDK builds. Lock not fixed in repo. | P01 |
|
||||
| CI-02 | Medium | Run #45 job 66 | `bun.lock` and `tests/phase07-deployment.test.ts:648-649` | Tracked `bun.lock` conflicts with assertion requiring its absence. Validate references before removing. | P01 |
|
||||
| CI-03 | Medium | Run #45 job 66 | `tests/r3-phase04-ui-metrics-rbac.test.ts`, `tests/r4-phase03-sdk-deploy-auth.test.ts`, `tests/r5-phase01-mcp-foundation-logs.test.ts`, `tests/r5-phase03-mcp-ui.test.ts` | Each suite timed out with exit **124** despite reaching passing assertions; investigate open handles/teardown without changing application timers by default. | P01 |
|
||||
| CI-04 | Medium | Run #45 job 66 | `tests/v2-phase01-storage-quotas.test.ts:788-804` vs `app/vcon/clients/page.tsx:15-20,70-95` and `lib/vconUiHelpers.ts:717-780` | Old regex expects `function isClientExpired(` in page; production page uses shared `classifyUiClientStatus` and `summarizeUiClientCounts`. Test contract is stale; not proof expiry feature fails. | P01 |
|
||||
| CI-05 | Medium | Run #45 job 68 | Nine `tests/*.test.ts` files (listed below), `tsconfig.json:27` | `npx tsc --noEmit` produced **43 compiler errors**, despite Next.js production build PASS. Type errors in test sources require focused correction; do not disable strict TypeScript. | P01 |
|
||||
| CI-06 | Low/CI | Run #45 job 67, run #48 job 74 | `.gitea/workflows/datastack-ci.yml` Python job | Linux Bullseye `apt-get` returned Debian-security 404; separate Windows Python job passed **14/14**. Runner provisioning defect, not SDK regression. | P03 |
|
||||
| CI-07 | High/CI | Run #50 job 76 | `.gitea/workflows/datastack-docker-ci.yml`, Docker daemon; `docker/Dockerfile.web:13` | Compose validation and ingestion image PASS, then web image layer copy fails with containerd `lstat .../app/node_modules/@uiw: no such file or directory`. Root cause **unconfirmed** (runner snapshot/storage or reproducible build interaction); proxy never built. | P03 |
|
||||
| CI-08 | Review | Run #50 job 76 | `package.json` / `package-lock.json` / resolved npm graph | npm reports **24 (23 moderate, 1 high)** with `--omit=dev`, **26 (25 moderate, 1 high)** with `--include=dev`. Counts overlap; no CVE list, reachable-exploit assessment or remediation done. | P03 |
|
||||
|
||||
*Severity is release-priority triage, NOT a CVSS rating and NOT proof of real-world exploitation.
|
||||
|
||||
### CI-05 exact file map (43 total, all inside tests)
|
||||
|
||||
| File | Error count | Families / main anchors |
|
||||
|---|---:|---|
|
||||
| `tests/phase01-auth.test.ts` | 4 | TS2540; 88,560,773,794 |
|
||||
| `tests/phase03-storage-buffer.test.ts` | 2 | TS2349; 1158,1202 |
|
||||
| `tests/r3-phase01-security-vault-webhooks.test.ts` | 6 | TS2353, TS2345; 185,191,202,210,295,430 |
|
||||
| `tests/r3-phase02-storage-scheduler-gzn.test.ts` | 1 | TS2345; 49 |
|
||||
| `tests/r4-phase01-security-boot.test.ts` | 3 | TS2345; 102,537,571 |
|
||||
| `tests/r4-phase02-ingestion-audit-streaming.test.ts` | 9 | TS2345/TS2833; 87,332,335,338,407 |
|
||||
| `tests/r5-phase02-mcp-server.test.ts` | 12 | TS18046; 510,524,538,549,560,570,581,604,613,635,644,657 |
|
||||
| `tests/v2-phase01-storage-quotas.test.ts` | 2 | TS2554; 762,783 |
|
||||
| `tests/v2-phase02-alerts-ip-prometheus.test.ts` | 4 | TS2339; 479,480,490,491 |
|
||||
|
||||
No source fix is authorized here. Use typed narrowing and correct test fixtures, not `skipLibCheck`, `any` everywhere, `@ts-ignore`, or changing real API responses merely to make tests compile.
|
||||
|
||||
## Three source-observed production reliability risks — CONDITIONAL GATES, not confirmed bugs
|
||||
|
||||
| Gate | Source proof | Why verification is required | Phase |
|
||||
|---|---|---|---|
|
||||
| R-01 Redis outage ACK durability | `server/index.js:165-193`, `server/socket/handlers.js:583-602` | `redis.rpush` failure falls back to RAM, and `onBufferPush()` can resolve, then Socket.IO ACK success; process crash before flush may lose acknowledged events. Fail-injection test and explicit durability contract required. | P02 |
|
||||
| R-02 Batch replay duplication | `server/index.js:943-994`, `server/workers/csvWriter.js:265-323` | CSV write precedes Redis list trim. Crash/partial write between these operations can replay already written rows. Validate at-least-once vs exactly-once guarantee before mitigation. | P02 |
|
||||
| R-03 Liveness ≠ readiness | `server/index.js:1939-1956`; `app/api/health/route.ts:95-111` | Health returns online without full PostgreSQL + Redis + disk transaction proof. Preserve existing `/health` API semantics; consider separate, internal readiness rather than breaking public health. | P02 |
|
||||
|
||||
Optional configuration review (not counted among eight): `server/index.js:1086-1089` Socket.IO uses CORS delegate; verify WebSocket origin/access and JWT guard in target deployments before recommending policy changes. `sdk/python/datastack/pyproject.toml:47-51` still references legacy `anik-d-art/datastack` URLs; metadata only, not current release blocker. Do not silently modify either under approved scope.
|
||||
|
||||
## CI evidence / original logs
|
||||
|
||||
- `https://dev.ivib.cc/vibtools/DataStack/actions/runs/42` — initial Windows lockfile failure (job 63), cancelled after partial node evidence.
|
||||
- `https://dev.ivib.cc/vibtools/DataStack/actions/runs/45` — 24 suites = 18 clean / 6 fail-or-timeout, 43 TS diagnostics, Next.js production build PASS, Windows diagnostic SDK build PASS; Linux Python apt and Docker-CLI job blocked.
|
||||
- `https://dev.ivib.cc/vibtools/DataStack/actions/runs/48` — Python SDK 14/14 PASS.
|
||||
- `https://dev.ivib.cc/vibtools/DataStack/actions/runs/49` — full ESLint PASS.
|
||||
- `https://dev.ivib.cc/vibtools/DataStack/actions/runs/50` — Compose PASS, Docker ingestion image PASS, web image containerd failure.
|
||||
- See `notes/006-BASELINE-AND-PATCH-EVIDENCE.md` for precise code/log excerpts and proposed patch anchors.
|
||||
|
||||
## Release acceptance rule
|
||||
|
||||
NOT production-update-ready until P01, conditional P02 gates, and P03 finish, 24/24 TypeScript suites exit 0, 14/14 Python tests pass, full strict `tsc --noEmit` and ESLint pass, Linux/Windows clean install is reproducible, standalone Next build passes, all 3 Docker images build, security advisories are triaged, and approved **non-mutating** live readiness checks pass. Production deploy is a separate operator-approved action; never automatic from this documentation phase.
|
||||
|
||||
## P01 Closure Appendix — 2026-11-22
|
||||
|
||||
**Implementation outcome: CI-01…CI-05 resolved within P01 source allowlist; no production app/runtime/UI/SDK changes.** Evidence: Gitea [#59](https://dev.ivib.cc/vibtools/DataStack/actions/runs/59) and focused quality retry [#60](https://dev.ivib.cc/vibtools/DataStack/actions/runs/60). Run #59 overall FAILED because a single test-only `stopTimers` type declaration remained; it was corrected in `tests/r5-phase01-mcp-foundation-logs.test.ts` and strict `tsc --noEmit` plus ESLint then PASSED in #60. The two run results are complementary; neither should be misreported as a single all-green run.
|
||||
|
||||
| Finding | Resolution and proof |
|
||||
|---|---|
|
||||
| CI-01 | `package-lock.json` gained 68 registry-integrity-verified **optional** entries including nested `@napi-rs/wasm-runtime/node_modules/@tybys/wasm-util@0.10.5`; 1293 original package entries unchanged, no removals or version bumps. Committed-lock `npm ci` PASS on Linux (job 90) and Windows (job 95). |
|
||||
| CI-02 | Removed obsolete `bun.lock`; `tests/phase07-deployment.test.ts` exit 0. |
|
||||
| CI-03 | Added suite-specific teardown hooks in four previously hanging suites, without changing core timer/runtime implementation; each exits 0. |
|
||||
| CI-04 | Replaced stale client-expiry inline-function regex with shared classifier/count behavioral assertions; `tests/v2-phase01-storage-quotas.test.ts` exit 0. |
|
||||
| CI-05 | 43 historical test-only TypeScript diagnostics corrected; one additional teardown declaration fixed after #59 typecheck failure. Final #60 strict TypeScript PASS (zero errors) and ESLint PASS. |
|
||||
|
||||
**Acceptance evidence:** #59 Node SDK build PASS, 24/24 isolated TypeScript suites exit 0 (no timeouts), Windows SDK build PASS, Next.js 15.5.29 standalone production build PASS with 22/22 pages. #60 targeted `tsc --noEmit` and `npm run lint` both PASS. Prior canonical Windows Python SDK 14/14 PASS from [#48](https://dev.ivib.cc/vibtools/DataStack/actions/runs/48); Python source unchanged and not rerun in P01. Docker images and live production behavior NOT verified in P01; P02 runtime reliability risks and P03 infrastructure/security gates remain open.
|
||||
|
||||
|
||||
## P02 Forensic Fault-Injection Update — 2026-11-22
|
||||
|
||||
Source freeze for P02: Gitea/GitHub main `667a140c4e9e75382bfdcdbe1d3e9eb96f6e808a`, matching GitLab tracked tree `d53b9e6dd7ff6d291b8bab7b841d8684ef89c703`. R-01/R-02/R-03 originally **risks**, not established production incidents. The diagnostic-only P02 patch adds disposable fixture tests in `tests/phase02-sync.test.ts` (R-01/R-03) and `tests/phase03-storage-buffer.test.ts` (R-02); CI: https://dev.ivib.cc/vibtools/DataStack/actions/runs/63. **Do not interpret diagnostic assertion success as a durability fix.** No runtime code, API, UI, data store, SDK, security policy, deployment or production host has been modified.
|
||||
|
||||
- **R-01 durable ACK:** `server/index.js:165-193,1895-1923` catches a failed Redis RPUSH and pushes accepted events into volatile RAM. `server/socket/handlers.js:583-602` then sends `{success:true,eventId}` if `onBufferPush` resolves. In the injected-RPUSH-failure fixture, simulated process-memory reset models loss of the acknowledged event; no actual server is killed. **Potential release blocker: acknowledged data is not necessarily durable.**
|
||||
- **R-02 CSV/replay:** `server/index.js:981-993` and `core/data/buffer.ts:795-809` write CSV before Redis LTRIM. The fixture injects an LTRIM failure after successful CSV append and retries the same queue; a duplicate eventId write would demonstrate at-least-once rather than exactly-once delivery. This fixture is an analogous web-buffer implementation, **not direct Port-4000 writer fault injection**. **A release decision and exact remediation require independent targeted evidence; do not extrapolate no-duplicates.**
|
||||
- **R-03 health:** `server/index.js:1926-1957` returns HTTP 200 `status:online` when Redis LLEN fails, while surfacing `redisConnected:false`; the historical route is **liveness**, not dependency readiness. `app/api/health/route.ts:95-111` likewise reports web liveness/buffer and does not prove database/Redis write readiness. A new readiness endpoint or altered public response requires separate approval.
|
||||
|
||||
Do not auto-fix source based solely on tests. Runtime code is READ-ONLY under the current approval. Any proven R-01/R-02 risk requiring behavior change needs a new exact method/file approval before application changes. P03 remains independent and unstarted.
|
||||
|
||||
|
||||
## P02 Runtime Remediation Candidate — 2026-11-22 (NOT YET VERIFIED)
|
||||
|
||||
Authorized follow-up baseline: Gitea/GitHub `fd57a3518d14bcb8367ce9ab9c3ec306bcfc9898` (GitLab same tree). Local isolated branch `p02-runtime-remediation-20261122`, implementation commit `44eee8877e40d1683f44502c2a0ba3d437a03b88`. Scope: **server/index.js** (`pushEventsToRedisOrFallback`, `flushBuffer`), **server/socket/handlers.js** (sync_data/batch_sync ACK and claim rollback), **core/data/buffer.ts** (`flush`), **tests/phase02-sync.test.ts** and **tests/phase03-storage-buffer.test.ts** only, plus notes/001–006. All other source is unchanged.
|
||||
|
||||
**Candidate R-01 behavior:** when a configured Redis client returns an RPUSH error, `pushEventsToRedisOrFallback` retains RAM fallback but throws a sanitized `BUFFER_PERSIST_FAILED` instead of returning a durable-looking buffer count. Socket single/batch ACK returns `success:false`; best-effort Redis idempotency-key removal and bounded in-process negative-ACK marker handle ordinary retries. This is a **candidate** pending tests. When Redis is intentionally absent, historical RAM fallback is deliberately unchanged; it is not a universal durable-ACK guarantee. If Redis claim deletion fails and the server restarts, stale Redis idempotency claims could still misclassify a retry; a full crash-atomic claim/queue protocol is **not established** by this patch.
|
||||
|
||||
**Candidate R-02 behavior:** Port 4000 `flushBuffer` and Port 3000 `DataBufferEngine.flush` stream-parse existing CSV/CSV.gz partitions for same-client/date/event IDs before replaying any buffered Redis or RAM batch, dropping already-persisted IDs while retaining Redis queue until the write/check completes. Scan/read/parse exceptions fail closed before LTRIM. In-scope test adds a direct Port 4000 writer + Redis LTRIM-failure/recovery test and updates the existing web-buffer replay fixture. **Not proven globally exactly-once:** cross-process CSV writers outside the Redis flush lock and unknown archival/partial-corruption cases remain; scanning partitions on each flush also has real disk-I/O cost, requiring throughput evaluation before production promotion.
|
||||
|
||||
**Candidate acceptance:** one disposable Gitea CI with 24/24 suites, strict TS, lint, Linux/Windows clean npm CI and production build; direct Port4000 replay tests; exact allowlist/diff audit and three-remote tree parity. The Gitea MCP/host was unavailable on the implementation attempt, so this is **NOT PASSED** and the P02 phase remains **BLOCKED / NOT CLOSED**. No live deployment or runtime production mutation.
|
||||
|
||||
## P02-RUNTIME-REMEDIATION-02 — Scope-locked post-patch forensic audit (2026-11-22)
|
||||
|
||||
**Source baseline:** P02 diagnostic `fd57a3518d14bcb8367ce9ab9c3ec306bcfc9898`. **Tested patch branch:** `p02-runtime-remediation-20261122`, final remediation source snapshot `5c880885378ae0f4fa8dd3a145f9c7055dada635`. This appendix supersedes the earlier "Gitea unavailable" candidate note. **Do not claim P02 CLOSED**: a separate HTTP fallback code path remains in scope-lock-excluded files.
|
||||
|
||||
**R-01 Port 4000 improvements implemented (not live-deployed):**
|
||||
- `server/index.js:pushEventsToRedisOrFallback` fails closed with sanitized `BUFFER_PERSIST_FAILED` on Redis RPUSH rejection while retaining RAM for recovery; also deduplicates same-client/eventId retries inside a single push.
|
||||
- The `onBufferPush` integration synchronously flushes to CSV before a successful ACK when Redis is intentionally absent; failed CSV append returns a negative ACK. No-Redis mode is therefore not an automatic RAM-only success ACK.
|
||||
- `server/socket/handlers.js` single/batch ACK logic clears failed local idempotency claims, never calls an uncertain Redis claim "durable duplicate", verifies a claimed duplicate against a bounded Redis buffer read or read-only CSV/.csv.gz scan, and denies uncertain mixed-batch ACKs. The proof uses a 512-item Redis window and a bounded CSV scan (256 MiB, 1.8 seconds); lack of proof yields a negative ACK, **not proof of data loss**.
|
||||
|
||||
**R-02 Port 4000 + web-buffer improvements implemented:** Both allowed flush methods check same-client/partition/eventId in physically persisted CSV/CSV.gz (including rotation) before retrying after Redis trim failure, and only trim when the disk append/check succeeds. Direct disposable Port 4000 LTRIM failure and gzip-partition replay tests exist. **Not a formal globally atomic/exactly-once guarantee:** concurrent independent writers, data corruption and repeated full-partition scans may introduce performance or recovery limitations.
|
||||
|
||||
**Critical residual R-01 HTTP path (outside this approval):** `core/data/buffer.ts:412-442` silently falls back to RAM on Redis RPUSH error; `app/api/events/route.ts:744-754` returns HTTP success after `pushAsync`. `sdk/node/datastack/index.ts:643-666,916-942` routes non-auth WebSocket rejections into HTTP fallback. Thus a negative Socket.IO ACK does **not establish end-to-end SDK/HTTP durability**. A disposable HTTP fault diagnostic was added to the P02 test allowlist; it is not a runtime fix. Fixing HTTP `POST` and the buffer push/idempotency contract needs separate explicit approval, including `core/Security/security.ts:230-375` only if reproduced claim rollback demands it.
|
||||
|
||||
**R-03:** public `/health` remains HTTP 200 liveness; no readiness endpoint, UI or auth change.
|
||||
|
||||
**CI facts:** Gitea [#66](https://dev.ivib.cc/vibtools/DataStack/actions/runs/66) terminal SUCCESS for initial patch; [#68](https://dev.ivib.cc/vibtools/DataStack/actions/runs/68) diagnosed a same-ID retry assertion regression; the exact local idempotency-claim cleanup was fixed in scope. [#70](https://dev.ivib.cc/vibtools/DataStack/actions/runs/70) is the latest disposable source acceptance (check terminal outcome in notes/003). **No code was deployed to production.**
|
||||
@@ -0,0 +1,101 @@
|
||||
# DataStack — Production Update Roadmap / Exact Scope Lock
|
||||
|
||||
Planning baseline: `d725841ebc828d58cbe90f517da9e600f23c4630` (frozen; documentation commits will advance Git HEAD but NOT this source baseline).
|
||||
Current state: **P01 CLOSED and CI-verified (1 of 3 phases complete); P02 and P03 NOT STARTED; P02 requires new explicit approval**.
|
||||
Prerequisite for any phase: compare current HEAD and changed paths with this baseline and previously committed notes. For new commits since source baseline, inspect exact diff; no implicit rebase or silent discard.
|
||||
|
||||
## Global non-negotiable Scope Lock (applies to ALL phases)
|
||||
|
||||
1. Existing UI/UX, public API response contracts, authentication, RBAC, JWT/SDK interoperability, MCP permissions, data retention, CSV content, persistent databases, keys, Redis values, S3/R2 objects, Coolify configuration and production deployment: **unchanged unless an exact targeted fix is proven and separately approved**.
|
||||
2. No live event sending, live database mutation, destructive test, production restart/deploy, automatic package vulnerability `--force`, tag or release without explicit approval.
|
||||
3. Limit changes to exact allowlisted paths per phase. Any additional path, altered schema, migration, UI behavior, API code, or security default = STOP / document scope exception / obtain new approval. No broad refactoring.
|
||||
4. One phase = targeted patch, **one focused CI verification**, exact diff/security review, log/register updates, one Git commit and 3-remote sync verification. No repetitive test loops or local production builds. If CI infra is broken, report a blocker rather than spoof PASS.
|
||||
5. Phase close requires written evidence with exit codes, commit SHA, changed paths, feature preservation checklist, remaining issues and a next-phase approval command.
|
||||
6. Reference test logs and source code, not README assertions alone. Code candidate risks require fault reproduction before production behavior changes.
|
||||
7. Secrets, personal data, local `.env` and runtime tokens never copied into reports, logs or commits. Never perform unsafe `git reset --hard` / `git clean -fd`.
|
||||
8. `AGENTS.md` cross-IDE memory requirement: update `MEMORY.md` only under explicit scope exception, otherwise provide exact handoff Markdown in `notes/003-PHASE-STATUS-LOG.md` for copy/sync.
|
||||
|
||||
## Phase P01 — Dependency, tests & type-contract reconciliation (CI-01…CI-05)
|
||||
|
||||
**Goal:** fix confirmed test/lockfile blockers without changing actual app/SDK runtime behavior.
|
||||
**Allowed paths only:**
|
||||
- `package-lock.json`; `bun.lock` (delete ONLY after verifying no build consumers; npm lock stays canonical).
|
||||
- `tests/phase07-deployment.test.ts`; `tests/v2-phase01-storage-quotas.test.ts`;
|
||||
- `tests/r3-phase04-ui-metrics-rbac.test.ts`; `tests/r4-phase03-sdk-deploy-auth.test.ts`; `tests/r5-phase01-mcp-foundation-logs.test.ts`; `tests/r5-phase03-mcp-ui.test.ts`;
|
||||
- `tests/phase01-auth.test.ts`; `tests/phase03-storage-buffer.test.ts`; `tests/r3-phase01-security-vault-webhooks.test.ts`; `tests/r3-phase02-storage-scheduler-gzn.test.ts`;
|
||||
- `tests/r4-phase01-security-boot.test.ts`; `tests/r4-phase02-ingestion-audit-streaming.test.ts`; `tests/r5-phase02-mcp-server.test.ts`; `tests/v2-phase02-alerts-ip-prometheus.test.ts`;
|
||||
- `.gitea/workflows/datastack-ci.yml` (narrow clean-install/test harness only); `notes/001…006` (status/evidence only).
|
||||
|
||||
**Not allowed:** `app/**`, `components/**`, `lib/**`, `core/**`, `server/**`, `docker/**`, `tsconfig.json`, `package.json` or SDK runtime files. If open-handle leak proves core timer bug, STOP and request explicit additional exception for `core/data/buffer.ts` instead of altering it as a side effect.
|
||||
|
||||
**Patch tasks and references:**
|
||||
- CI-01: deterministic regenerated `package-lock.json` with cross-OS optional entries, verify clean `npm ci` on Linux/Windows with same pinned npm; no dependency version bump unless separately approved. Reference `.gitea/workflows/datastack-ci.yml:91-120`.
|
||||
- CI-02: check `bun.lock` consumers, then remove stale lock or resolve test contract with proof; `tests/phase07-deployment.test.ts:649`.
|
||||
- CI-03: isolate 4 suites, enumerate open handles/intervals, add explicit test teardown / mocks; source `core/data/buffer.ts:347-391` is **read-only diagnostic reference**. Avoid `process.exit()` hacks and wholesale timeout increases.
|
||||
- CI-04: replace obsolete regex tests in `tests/v2-phase01-storage-quotas.test.ts:788-804` with precise shared-helper/integration assertions matching `app/vcon/clients/page.tsx:70-95` and `lib/vconUiHelpers.ts:717-780`.
|
||||
- CI-05: fix 43 test-code type errors across 9 listed files (see `001`). Keep strict TS compile; preserve production API signatures. `tsconfig.json:27` includes tests by glob.
|
||||
- **P01 acceptance:** 24/24 test files exit 0 (no timeout), `tsc --noEmit` zero errors, `npm run lint` PASS, Python 14/14 PASS regression, Windows/Linux original `npm ci` PASS without diagnostic lock regeneration; one focused Gitea matrix. If network/runner blocker, mark BLOCKED not PASS.
|
||||
- **Close:** update `notes/003` and `notes/005` only after verifying; commit and sync.
|
||||
|
||||
## Phase P02 — Ingestion reliability / error-handling acceptance gates (R-01…R-03)
|
||||
|
||||
**Goal:** reproduce or dismiss source-observed risk, preserve response semantics unless proven fix is necessary. **Risk ≠ bug until test fails.**
|
||||
**Diagnostic-only allowlist:** `server/index.js`, `server/socket/handlers.js`, `server/workers/csvWriter.js`, `core/data/buffer.ts`, `app/api/health/route.ts`, `tests/phase02-sync.test.ts`, `tests/phase03-storage-buffer.test.ts`, `tests/r4-phase02-ingestion-audit-streaming.test.ts`, `notes/001…006`.
|
||||
**Default write allowlist:** only the THREE listed test files plus `notes/001…006`. Runtime source files above are **READ ONLY until a reproducible failing test demonstrates the need**; then the P02 approval must name an exact method/line range and explicitly authorize the smallest required change. This is not preapproval for changing server source.
|
||||
**Test matrix (disposable, never production):**
|
||||
- R-01: fake Redis `rpush` rejection + ACK + simulated process exit/reopen; ensure API explicitly returns failed/pending unless durable, or document intended guarantee. Preserve existing duplicate/rate/size/auth error codes.
|
||||
- R-02: injected CSV partial write, simulated failure before Redis `ltrim`, restart and compare event IDs/rows; decide documented at-least-once semantics vs dedupe strategy before altering storage.
|
||||
- R-03: separate liveness/readiness checks with mocked Redis/PG errors; old public `/health` stays backwards compatible. Verify startup fail-closed when secrets or DB unavailable.
|
||||
- Review source CORS/WebSocket origin and security access policy as **read-only**, no default policy change automatically.
|
||||
- **P02 acceptance:** targeted fault-injection tests PASS, no acknowledged-event loss in the documented guarantee, no unbounded duplicate amplification, correct 503/507/429/401 semantics and recovery. If risk not reproduced, close as verified with **zero runtime source changes**; never invent a fix.
|
||||
- **Close:** record precise outcome and next P03 approval.
|
||||
|
||||
## Phase P03 — CI runner, Docker images, dependency security, release evidence (CI-06…CI-08)
|
||||
|
||||
**Goal:** reproducible Gitea verification, safe dependency advisory triage, complete all three Docker builds, confirm non-mutating production health.
|
||||
**Default write allowlist:** `.gitea/workflows/datastack-ci.yml`, `.gitea/workflows/datastack-python-ci.yml`, `.gitea/workflows/datastack-docker-ci.yml`, `.gitea/workflows/datastack-eslint-ci.yml`, `package.json`, `package-lock.json`, `notes/001…006`.
|
||||
**Conditional, separate approval only:** `docker/Dockerfile.web` / `docker/Dockerfile.server` if isolated runner/containerd evidence establishes source-level Dockerfile defect. **Not allowed** to change Compose deployment services, secrets, volumes or Dockerfiles merely to work around a runner failure.
|
||||
**Tasks:**
|
||||
- CI-06: replace stale Debian Bullseye `apt-get` dependency step with preinstalled compatible Python image/toolchain OR canonical Windows Python job; avoid duplicate CI runs.
|
||||
- CI-07: inspect runner daemon snapshotter/filesystem free space, cache/BuildKit and known `node_modules/@uiw` layer failure; use properly configured disposable BuildKit builder or another isolated runner. If reproducible Dockerfile defect is proven, obtain narrow scope amendment. Build images **without running containers**; no `docker system prune` or shared cache destruction.
|
||||
- CI-08: run read-only detailed `npm audit --json` in isolated runner, map actual direct/transitive paths and runtime impact, document advisory IDs/severity, apply minimal compatible pin bumps only where necessary. Never `npm audit fix --force`.
|
||||
- Verify canonical package metadata and Git remote SHA; GitHub login/account issue is **already resolved** and is not a current blocker.
|
||||
- **P03 acceptance:** all 3 images build, Compose config PASS, Next standalone PASS, lint + strict TS PASS, 24/24 TS suites no hang, Python 14/14, regression error codes unchanged, advisory disposition documented, read-only public health PASS. Any real deployment/production migration is a **separate approval**.
|
||||
- **Close:** exact diff, one CI acceptance run (plus only blocked job rerun where necessary), statuses/feature matrix update, one commit, synced remote HEADs, phase CLOSED.
|
||||
|
||||
## Sequence and approval gate
|
||||
|
||||
P01 **CLOSED** -> P02 **approved diagnostic completed / BLOCKED on R-01 and R-02 remediation** -> P03 **must await P02 closure**. P01 acceptance evidence: Gitea CI #59 (Windows + Linux clean install, 24/24 tests, Node SDK, Next standalone) and #60 (strict TypeScript + ESLint), with historical #59 single test-type error corrected before #60. No actual app/runtime/UI/SDK change or live deployment.
|
||||
|
||||
Approval command for next turn:
|
||||
|
||||
`APPROVED — DataStack Production Readiness P02. Follow notes/002 P02 Exact Scope Lock. Verify R-01 Redis ACK durability, R-02 CSV crash/replay duplication, and R-03 liveness/readiness with disposable fault-injection tests. App/runtime source READ-ONLY unless a reproducible bug and separate exact patch approval. Preserve all existing UI, API, auth, SDK, data, and production. One focused CI, forensic diff, notes update, commit, three-remote sync. No deploy, releases, migrations or scope expansion.`
|
||||
|
||||
## P02 Execution Scope Addendum — 2026-11-22
|
||||
|
||||
P02 approved as **diagnostic-only**. Published P01 baseline: `667a140c4e9e75382bfdcdbe1d3e9eb96f6e808a`. Isolated local worktree: `p02-readiness-test-20261122`, preserving previously staged local P01 source. The **only code edits** are `tests/phase02-sync.test.ts` and `tests/phase03-storage-buffer.test.ts`; six `notes/001–006` documents may be amended. CI #63 uses the existing `.gitea/workflows/datastack-ci.yml`; changing workflow files is **outside P02 Scope Lock**. No runtime/source/API/UI/SDK change is approved. If loss or unbounded replay is reproduced, classify as **BLOCKED pending an independently authorized narrow runtime patch**, not as fixed; do not advance P03 as if P02's production-readiness gate passed. Approval after evidence must name precise methods, event ACK contract, deduplication/CSV recovery strategy and allowed tests before editing runtime.
|
||||
|
||||
|
||||
### P02 Conditional Remediation Approval (NOT CURRENTLY APPROVED)
|
||||
|
||||
`APPROVED — DataStack P02-RUNTIME-REMEDIATION. Baseline: use the verified P02 diagnostic commit/remote tree. Fix reproduced R-01 and R-02 only, following exact notes/001–006 proof and scoped server/index.js pushEventsToRedisOrFallback/onBufferPush and flushBuffer, server/socket/handlers.js sync_data/batch_sync ACK, and their three existing P02 test files. First document safe ACK/retry semantics, exactly-once versus at-least-once CSV contract and crash recovery. Add disposable fault tests proving no positive ACK for non-durable data and no unbounded duplicate replay. Runtime sources core/data/buffer.ts and server/workers/csvWriter.js remain READ-ONLY unless a separately justified exact file/line amendment is approved. Preserve all UI/auth/SDK/public health behavior and existing error codes, production data, security, other features and Docker. One focused CI, diff/security audit, notes update, commit and 3-remote parity. No deployment, migrations, tags/releases or scope expansion. If a safe fix cannot be achieved within these exact methods, stop and report the required additional Scope Lock rather than broadening automatically.`
|
||||
|
||||
After separate approved remediation and verified P02 closure, **P03 plan** remains CI-06 Linux Python runner provisioning, CI-07 isolated Docker/BuildKit failure remediation and 3-image build, CI-08 supply-chain advisory triage, and non-mutating readiness evidence. P03 should not modify unrelated UI/runtime/API code by default.
|
||||
|
||||
|
||||
## P02 Runtime Remediation Execution Handoff — 2026-11-22
|
||||
|
||||
The user explicitly approved **only** R-01 Redis failure ACK and R-02 Redis-to-CSV replay corrections in these methods: `server/index.js` `pushEventsToRedisOrFallback` / `flushBuffer` / existing `onBufferPush` integration; `server/socket/handlers.js` `sync_data` / `batch_sync` ACK handling; `core/data/buffer.ts` `flush` if needed; the three earlier P02 test files; `notes/001–006`. No other application method/UI/API/auth/SDK/Docker/CI-workflow edit. Public R-03 `/health` semantics remain unchanged.
|
||||
|
||||
Local candidate `44eee8877e40d1683f44502c2a0ba3d437a03b88` is **not release-ready** until Gitea acceptance. Before closure, prove: negative ACK on Redis failure with no sensitive error leakage; ordinary successful Redis ACK preserved; both single and batch retries don't convert volatile failures to success; Redis queued event replays after crash without writing duplicate CSV rows in the Port 4000 worker and Port 3000 web buffer; CSV read/parse failure never causes premature Redis trim; validate bounded scan overhead and edge cases for rotated/gzipped partitions; all historical 401/403/429/507/503 tests unchanged.
|
||||
|
||||
**Stop rule:** if required fixes need touching `validateSingleEventAsync`, `csvWriter.js` or separate journal/storage scheme, do not broaden the implementation scope; record the residual and request new explicit approval. Existing unrelated files including `MEMORY.md` remain unchanged due exact Scope Lock; this note is the cross-IDE handoff. P03 must wait for P02 CLOSED, not merely implementation committed.
|
||||
|
||||
## P02 Post-implementation approval boundary — 2026-11-22
|
||||
|
||||
The separately approved R-01/R-02 **Socket.IO and CSV flush** hardening is implemented on an isolated branch, with all allowed runtime sources/tests only. Existing candidate approval text above is historic; the newest evidence is the appendix in notes/001 and notes/003. P02 must **NOT** be closed solely on P02 branch CI success: the HTTP `POST /api/events` RAM-fallback-success path is source-observed outside the current runtime method allowlist. P03 remains NOT STARTED until P02 acceptance and a new explicit approval.
|
||||
|
||||
**Proposed separate Scope Lock approval — P02-HTTP-DURABILITY-01 (NOT YET APPROVED):**
|
||||
`APPROVED — DataStack P02-HTTP-DURABILITY-01. Use latest verified P02 runtime branch and notes/001–006. Default WRITE only app/api/events/route.ts POST; core/data/buffer.ts writeEventsToRedisOrFallback, pushAsync and pushBatchAsync; tests/phase02-sync.test.ts, tests/phase03-storage-buffer.test.ts, tests/r4-phase02-ingestion-audit-streaming.test.ts; notes/001–006. Allow core/Security/security.ts validateEventAsync/idempotency rollback ONLY if a focused failing test proves stale claims cannot be handled within listed methods, and record exact lines before any edit. Fix HTTP success on volatile RAM after Redis write failure; preserve legitimate Redis-free CSV durable fallback, cross-transport duplicate correctness, current 401/403/429/507 contracts, SDK wire format, auth and user data. Use no production Redis/DB, no live requests, no UI, SDK, Docker, migrations, releases, R-03 health change or unrelated files. One focused disposable Gitea CI, exact patch/security audit, notes update, one Git commit, three-remote content parity. Then close P02 only if the entire acceptance matrix is demonstrated; provide P03 approval command.`
|
||||
|
||||
**P03 outline once P02 is truly CLOSED:** CI-06 restore reliable Python CI runner provisioning; CI-07 diagnose Docker/containerd Builder snapshot error and build all three images in disposable CI; CI-08 trace exact npm advisories and apply only proven compatible security upgrades. Preserve UI, auth, backend feature semantics and live data. No automatic deployment.
|
||||
@@ -0,0 +1,119 @@
|
||||
# DataStack — Phase Status & Change Log (Source of Progress Truth)
|
||||
|
||||
Frozen source baseline: `d725841ebc828d58cbe90f517da9e600f23c4630`. Generated: 2026-11-22 Asia/Dhaka.
|
||||
Scope: documentation-only kickoff. Any future phase must update this log **after** verification, not on intention.
|
||||
**Completed implementation phases: 1 / 3. Remaining: 2.** Documentation baseline preparation is a separate non-implementation milestone.
|
||||
|
||||
| Phase | Status | IDs / function | Changed source | Verified CI evidence | Commit / remote sync |
|
||||
|---|---|---|---|---|---|
|
||||
| P00 Notes / freeze | COMPLETED (documentation only) | `001–006` docs, source baseline and exact scope | `notes/**` only | 6 Markdown files; balanced fences; staged diff `--check` PASS | Documentation commit containing this file; remote SHA verification recorded in session handoff |
|
||||
| P01 Tests & lockfile | **CLOSED — VERIFIED** | CI-01…CI-05, no runtime feature changes | 16 exact P01 code/test/CI paths, plus `notes/001–006` records | #59 Linux/Windows clean npm/SDK, 24/24 TS suites, Next standalone PASS; #60 strict TypeScript and ESLint PASS; historical #59 quality mismatch corrected | One permanent P01 main commit containing these notes; confirm remote SHA/tree parity in phase handoff |
|
||||
| P02 Ingestion reliability | **BLOCKED — three diagnostic cases reproduced; runtime fix requires separate approval** | R-01 ACK/RAM loss; R-02 CSV duplicate replay; R-03 health liveness vs readiness | Only `tests/phase02-sync.test.ts` and `tests/phase03-storage-buffer.test.ts`, plus notes/001–006 | Gitea #63: all three P02 subtests PASS to reproduce existing behavior; full matrix status recorded in appendix | Diagnostic branch `p02-readiness-test-20261122`, no production runtime changes |
|
||||
| P03 CI/Docker/security | NOT STARTED | CI-06,07,08; release gates | None | Not run | — |
|
||||
|
||||
## Existing diagnostic CI snapshot (NOT implementation phase completions)
|
||||
|
||||
| Run | Baseline commit | Result | Meaning |
|
||||
|---|---|---|---|
|
||||
| #42 | `f7c1e7f` | Cancelled | Windows original lock fail logged; long combined regression stopped |
|
||||
| #45 | `d3a93c6` | Failure | TS 18 clean/6 fail-or-timeout; 43 type errors; build and Windows SDK pass; Python apt / Docker CLI blockers |
|
||||
| #48 | `ff1333d` | Success | Python SDK 14/14 |
|
||||
| #49 | `559f180` | Success | ESLint |
|
||||
| #50 | `d725841` | Failure | Compose + ingestion image pass; web image fails containerd snapshot copy; proxy unrun |
|
||||
|
||||
Historical baseline code stayed frozen through these CI workflow changes. Current HEAD before documentation changes = `d725841ebc828d58cbe90f517da9e600f23c4630` on local/GitHub/GitLab/Gitea.
|
||||
|
||||
## Per-phase closure record template — COPY for each P01/P02/P03
|
||||
|
||||
### P0X — [TITLE] (OPEN / BLOCKED / CLOSED)
|
||||
|
||||
- Authorized baseline / parent SHA:
|
||||
- Approval command / exact scope document reference:
|
||||
- Findings addressed + any conditional gates:
|
||||
- Exact modified paths (one path per row):
|
||||
- Applied code patch summary (function + lines):
|
||||
- Existing feature/UI/API/auth/SDK/data preservation audit:
|
||||
- Focused CI run URL / test counts / exit codes:
|
||||
- Security check / handling of secrets, data and scope exceptions:
|
||||
- Verification result: PASS / FAIL / BLOCKED, not assumed:
|
||||
- Closure commit SHA + GitHub/GitLab/Gitea main SHAs:
|
||||
- Completed implementation phases: X/3; remaining: Y.
|
||||
- Next phase: P0Y; **specific approved features** / allowed files:
|
||||
- New issues / deferred risks / notes evidence links:
|
||||
- MEMORY.md cross-IDE handoff text (copyable):
|
||||
`[DataStack P0X] Baseline=<SHA>; findings=<IDs>; scope=<exact paths>; CI=<run + exit>; commit=<SHA>; remote sync=<all 3>; phase=CLOSED; next=P0Y; production deployment=unchanged.`
|
||||
|
||||
## P01 attempted implementation & gate outcome (2026-11-22)
|
||||
|
||||
- Frozen source baseline remains `d725841ebc828d58cbe90f517da9e600f23c4630`; latest source HEAD before P01 was documentation commit `d8ac96e39dad4ea3b241c1d2f16f959c5215701e` on all three remotes.
|
||||
- Disposable CI commit `90fce0629a752dd2916d8d3a2afeaf2c52ed6cbb` contains **16 P01-allowed paths**: `bun.lock` deletion, `package-lock.json` optional/native metadata closure (+67 entries, no existing version or root-manifest change), 14 scoped test files, and `.gitea/workflows/datastack-ci.yml` clean-install/phase-filter changes. No application runtime source/UI/SDK/Docker changes.
|
||||
- Gitea run: https://dev.ivib.cc/vibtools/DataStack/actions/runs/58; overall **FAIL**, terminal. `windows-compatibility`, `node-regression`, `quality`, `production-build` all failed during clean `npm ci`: `Missing: @tybys/wasm-util@0.10.5 from lock file`. The Python and Docker jobs were intentionally skipped for P01. **No current TypeScript test, strict typecheck, ESLint or build PASS may be claimed**.
|
||||
- Root issue likely parallel incompatible transitive requirement of `@tybys/wasm-util`; inspect `node_modules/@napi-rs/wasm-runtime` vs `node_modules/@tailwindcss/oxide-wasm32-wasi` in lock and install exact requested transitive version under correct nested path without changing existing pinned entries. Then verify npm clean-install on both platforms and rerun focused P01 acceptance once after repair; do not blindly override lock integrity.
|
||||
- Local original Windows device's VARUA connection reached monthly call quota; local changes were staged via safe squash on `main` but **no P01 main commit/push** occurred. A separate connected desktop did not have this workspace. Do not claim local/3-remote post-P01 sync until verified.
|
||||
- **Historical #58 status:** 0/3, P01 BLOCKED before nested lockfile correction. **Superseded by closure evidence below**; no force push or deploy was used.
|
||||
|
||||
## Status transition rules
|
||||
|
||||
- OPEN -> IN PROGRESS only with explicit approval and baseline SHA match.
|
||||
- IN PROGRESS -> CLOSED only after one focused CI and exact diff audit, updated `003` + `005` + relevant `001/004/006`, Git commit, sync, and confirmed remote SHA.
|
||||
- Failed test -> BLOCKED with log excerpt and scope decision; never log as complete.
|
||||
- Unexpected file change -> STOP and revert only own documented changes safely; never touch pre-existing work.
|
||||
- At any time, `actual production deployment status` is a separate tracked dimension (do not infer deployed SHA from Git HEAD).
|
||||
|
||||
## P01 Final Closure — CI-01…CI-05
|
||||
|
||||
- **Status:** CLOSED after one P01 acceptance CI (#59) plus one narrow quality-only correction/retry (#60); completed implementation phases **1/3**, remaining **2** (P02 and P03).
|
||||
- **Baseline:** frozen source `d725841ebc828d58cbe90f517da9e600f23c4630`; pre-P01 documentation HEAD `d8ac96e39dad4ea3b241c1d2f16f959c5215701e`.
|
||||
- **Validated implementation code snapshot:** `7d8eebd3dc867e82113343403b63ce1d4ed20584` on disposable Gitea P01 branch. Permanent main commit is the **single squash commit containing this closure log**; remote SHAs and content-tree equality must be checked at publish, not predicted here.
|
||||
- **Exact P01 patch:** deletion `bun.lock`; append-only 68 optional/native lock entries with zero original package-version changes; 13 in-scope test files with typed mocks, teardown, and shared-helper assertions; narrow `.gitea/workflows/datastack-ci.yml` clean-install and focused verification inputs. `package.json`, `tsconfig.json`, all app/UI/backend/SDK/Docker/production files unchanged.
|
||||
- **#58 failed before tests** (`@tybys/wasm-util@0.10.5` missing); fixed by nested, registry-hash-verified optional dependency. **#59 overall FAIL** due exactly one TS2339 test teardown type declaration; the same run separately proved 24/24 TS suite exits 0, Linux/Windows original committed-lock `npm ci`, both Node SDK builds, and Next standalone production build (22/22 pages). Fixed only the test declaration; **#60 quality-only PASS** for `npx tsc --noEmit` and `npm run lint` with no error.
|
||||
- Prior independent Python SDK 14/14 PASS: #48 (SDK unmodified); not rerun during P01. P03 Docker and security/advisory findings unresolved; no Docker builds, live ingestion, network fault injection, migrations, releases or production deployment occurred.
|
||||
- **Diff audit:** only allowlisted 16 P01 code/test/CI paths and 6 `notes/*.md` files; `git diff --check` PASS; no unrelated features, API behavior, UI or persistent data changed. 1293 original lock entries remained byte-equivalent; 68 optional entries added with integrity hashes.
|
||||
- **Working tree caveat:** original local Windows VARUA device reached its monthly quota during P01; its current local branch/working tree could not be rechecked and should be reconciled against published `main` before new local work. A separate authorized temporary Windows clone was used for diff and Git push verification. Never claim original PC is already updated.
|
||||
- **Next:** P02 read-only initial source audit plus targeted disposable fault-injection tests for R-01 (Redis ACK), R-02 (CSV replay), R-03 (health readiness). Runtime-source change requires reproduced issue and a separate exact method/file approval. P03 only after P02 closure.
|
||||
- **P02 implementation approval command:** `APPROVED — DataStack P02. Implement only notes/002 P02 diagnostic/test write scope for R-01, R-02 and R-03. Keep app/UI/API/auth/SDK/runtime/data unchanged. Runtime files read-only unless a proven failure and separately approved narrow code patch. One focused disposable Gitea CI, exact diff, notes/001–006 update, commit and remote verification. No production deployment or scope expansion.`
|
||||
|
||||
|
||||
## P02 Execution Log — 2026-11-22 (supersedes P02: pending until acceptance)
|
||||
|
||||
- **Status: IN PROGRESS / diagnostic CI pending.** Not CLOSED and not a production-readiness certificate.
|
||||
- P01 published baseline `667a140c4e9e75382bfdcdbe1d3e9eb96f6e808a`. Original PC local `main` still at prior docs HEAD with **16 user-visible staged P01 paths**, preserved untouched. New isolated `p02-readiness-test-20261122` worktree based on published baseline; no reset/stash/force update.
|
||||
- P02 disposable test commit: `bbe73d91666641743cbec6cf7203f1694094caef`; **only two files**: `tests/phase02-sync.test.ts` (Redis negative-path ACK and health fallback), `tests/phase03-storage-buffer.test.ts` (failure between CSV append and Redis LTRIM, replay). Source contracts and auth flows unchanged.
|
||||
- Focused evidence: https://dev.ivib.cc/vibtools/DataStack/actions/runs/63. Record terminal suite/typecheck/build results after completion. Test assertions expose existing behavior; they do not implement durability or readiness fixes.
|
||||
- Scope audited: `server/index.js`, `server/socket/handlers.js`, `server/workers/csvWriter.js`, `core/data/buffer.ts`, `app/api/health/route.ts` all READ-ONLY; `app/**`, `components/**`, `lib/**`, `sdk/**`, Docker, settings, production data and deployments unchanged.
|
||||
- P01 remains CLOSED (1/3). If R-01 or R-02 are confirmed unsafe, P02 must remain BLOCKED for runtime remediation approval. No P03 implementation on this approval.
|
||||
|
||||
|
||||
### P02 Verified Diagnostic Gate (R-01/R-02/R-03)
|
||||
|
||||
- Gitea #63 (test-only commit `bbe73d91666641743cbec6cf7203f1694094caef`): `P02 R-01 diagnostic` PASS, `P02 R-03 diagnostic` PASS, `P02 R-02 diagnostic` PASS. Each PASS validates reproduction of existing behavior, **not a successful reliability remediation**.
|
||||
- `tests/phase02-sync.test.ts` suite exit 0; `tests/phase03-storage-buffer.test.ts` suite exit 0. Other CI jobs may have independent status; do not infer full job or complete workflow PASS from three cases.
|
||||
- **BLOCKING RELEASE FINDINGS:** R-01 success ACK issued for non-durable RAM fallback when Redis RPUSH fails; R-02 identical eventId can append twice on post-CSV Redis-trim failure (web-side representative test). R-03 health remains online on Redis loss; liveness-only behavior is backward-compatible, protected dependency-readiness verification remains missing.
|
||||
- **P02 PHASE = BLOCKED**, diagnostic implementation done, release reliability acceptance NOT satisfied. Runtime remediation requires separate exact approval. 1/3 phases still CLOSED (P01 only); P02 and P03 remain unclosed. No P03 start authorization from this diagnostic completion.
|
||||
- Next approval must explicitly authorize exact narrow server/core patch for ACK durability and CSV replay deduplication, plus concrete no-loss/no-duplicate tests. Any readiness endpoint change needs separate explicit approval. User's initial P02 approval is insufficient for runtime mutation.
|
||||
|
||||
|
||||
## P02-RUNTIME-REMEDIATION — Candidate implementation checkpoint (2026-11-22)
|
||||
|
||||
- **Current P02: BLOCKED / NOT CLOSED.** One previous diagnostic Gitea CI #63 reproduced R-01/R-02/R-03; runtime remediation was separately approved after that. Verified completed implementation phases remain **1/3** (P01 only). Do not approve P03 yet.
|
||||
- Published P02 diagnosis baseline `fd57a3518d14bcb8367ce9ab9c3ec306bcfc9898`; isolated local candidate commit `44eee8877e40d1683f44502c2a0ba3d437a03b88` on `p02-runtime-remediation-20261122`.
|
||||
- Exactly five code/test files changed in this candidate: `server/index.js`, `server/socket/handlers.js`, `core/data/buffer.ts`, `tests/phase02-sync.test.ts`, `tests/phase03-storage-buffer.test.ts`. No `server/workers/csvWriter.js`, `app/**`, `components/**`, SDK, public R-03 health, CI workflow, database, migration, production data, secrets or deployment touched.
|
||||
- JS `node --check` on two changed JS files PASS; `git diff --check` PASS and allowlist audit PASS. Targeted TS/Node regression and Gitea CI **NOT YET RUN TO TERMINAL PASS**. The Gitea connector/host was unavailable when dispatch/push was attempted. Local temporary dependency installation also not yet complete.
|
||||
- The original user PC root `D:\VibTools_Workspace\01_Products\14_DataStack` still has 16 pre-existing staged P01 paths on older `d8ac96e`; deliberately preserved without reset/stash/discard. All P02 implementation is in a separate temporary worktree. Do not assume the old local root is up to date.
|
||||
- R-01 and R-02 implementations are candidates; practical reliability limitations and I/O cost recorded in `notes/001` and `notes/004`. No false claim of globally exactly-once CSV or universally durable ACK.
|
||||
- **Next gates:** restore Gitea access; run one focused disposable acceptance; fix any in-scope test/TS defects; record exact CI terminal results; only after required acceptance and security audit, squash single phase main commit and verify GitHub/GitLab/Gitea tree parity; then, and only then, decide P02 CLOSED versus residual-risk blocker.
|
||||
|
||||
|
||||
### Verification environment blocker — local dependency install
|
||||
|
||||
The authorized Windows PC attempted a **local disposable** `npm.cmd ci --ignore-scripts --no-audit --no-fund --prefer-offline` in the isolated P02 worktree only; it failed with `npm ERR! ETARGET No matching version found for yaml@2.9.1` plus cleanup EPERM warnings in the temp worktree's `node_modules`. Exact output captured in `%TEMP%\DataStack-P02-npm-ci.log` on the authorized PC. This is **not a passed code test nor proof of a repository package defect**, and `package-lock.json` / `package.json` cannot be edited under P02 scope. Gitea MCP remained UNAVAILABLE and the Git remote/HTTP service was not responding when CI was attempted, so the mandatory P02 focused CI was **not dispatched**. Phase remains BLOCKED pending actual CI evidence; no runtime change was pushed to production/main.
|
||||
|
||||
## P02-RUNTIME-REMEDIATION-02 — Post-patch evidence/status (2026-11-22)
|
||||
|
||||
- **P02 current status: BLOCKED / NOT CLOSED** by a separate Port 3000 HTTP RAM-ACK path (and until terminal CI evidence). Completed implementation phases remain **1/3** (P01 only); P03 not authorized.
|
||||
- Baseline `fd57a3518d14bcb8367ce9ab9c3ec306bcfc9898`; isolated Gitea branch `p02-runtime-remediation-20261122`; inspected code commit `5c880885378ae0f4fa8dd3a145f9c7055dada635`. Original PC root `main` at earlier docs SHA with 16 user-staged P01 paths remains untouched. No force-reset, stash, production write or deployment.
|
||||
- **Verified earlier focused CI #66:** 24/24 TS suites, strict TypeScript, ESLint, Windows/npm SDK and Next.js standalone production build success; Python/Docker jobs skipped as separate P03 work.
|
||||
- **CI #68:** new same-ID retry test failed because an unproven duplicate had left a local claim set; this was corrected in handlers on the subsequent scoped code commit. #68 was cancelled after failure (logs preserved). **CI #70:** revised focused acceptance and added HTTP failure diagnostic; confirm actual terminal job conclusions before claiming PASS. The HTTP diagnostic is intentionally expected to expose an unresolved behavior, not fix it.
|
||||
- P02 code changes confined to `server/index.js` selected ACK/buffer/flush methods, `server/socket/handlers.js` persistence ACK/duplicate proof methods, `core/data/buffer.ts` flush, and three approved test files; notes/001–006 only. R-03 public health unchanged. All other app/UI/auth/SDK/CI workflow/lockfile/Docker/runtime source unchanged.
|
||||
- **Residual blocking source evidence:** `app/api/events/route.ts:744-754` returns success following `core/data/buffer.ts:412-442` silent Redis-error RAM fallback; Node SDK may switch to HTTP after negative WS ACK. A separate exact scope exception is required for end-to-end no-positive-ACK-on-volatile-data acceptance. Do not merge the blocked candidate into three `main` refs or assert P02 production ready.
|
||||
- Performance boundary: replay checking can stream entire CSV partitions per flush (not throughput benchmarked); duplicate proof is capped at last 512 Redis queue items and 256 MiB/1.8s CSV proof (negative ACK on uncertainty). This is safer than a false positive, but compatibility under heavy ingestion must be reviewed before release.
|
||||
@@ -0,0 +1,92 @@
|
||||
# DataStack — Error Handling Inventory & Proposed Safety Gates
|
||||
|
||||
Source baseline: `d725841ebc828d58cbe90f517da9e600f23c4630`. This is an **implementation inventory**, NOT an independently executed production fault-injection certificate. Existing codes and APIs below are source-grounded.
|
||||
|
||||
## Existing handlers: observed code paths
|
||||
|
||||
| Failure / scenario | Exact path and lines | Current response / behavior | CI coverage/status |
|
||||
|---|---|---|---|
|
||||
| Missing/bad client ID | `app/api/events/route.ts:433-442` | `400 VALIDATION_ERROR` | TS suites; no live write |
|
||||
| Deleted/missing/revoked client | `app/api/events/route.ts:445-474` | `403 CLIENT_REVOKED` | Auth regression passed in suite |
|
||||
| Rotated token | `app/api/events/route.ts:476-487` | `401 TOKEN_ROTATED` | Auth/SDK regression coverage |
|
||||
| Expired client token | `app/api/events/route.ts:489-504` | `401 CLIENT_TOKEN_EXPIRED` + webhook trigger | Python SDK tests pass |
|
||||
| Disallowed IP | `app/api/events/route.ts:506-526`; `app/api/health/route.ts:82-91` | `403 CLIENT_IP_FORBIDDEN` | Source + TS regression |
|
||||
| Disk low / client quota exhausted | `core/Storage/csvStorage.ts:1159-1193`; `app/api/events/route.ts:567-589` | `507 DISK_SPACE_LOW` or `STORAGE_QUOTA_EXCEEDED`; webhook | Python 14/14, TS related suite passed except stale UI assertion |
|
||||
| Duplicate, payload oversize, rate limit | `app/api/events/route.ts:633-681` | dedupe; `413 PAYLOAD_TOO_LARGE`, `429 RATE_LIMIT_EXCEEDED`, `400 BATCH_REJECTED` | Regression suites |
|
||||
| Socket buffer persistence exception | `server/socket/handlers.js:583-602` | `BUFFER_PERSIST_FAILED` callback **if onBufferPush throws**; success ACK after normal resolution | R-01 requires RAM-fallback failure injection |
|
||||
| Redis distributed flush lock | `app/api/storage/route.ts:102-127` and :187-197 | `503 FLUSH_LOCK_TIMEOUT` on guarded flush | Existing TS test pass |
|
||||
| Webhook disabled/blocked/redirect/timeout | `core/alerts/webhookNotifier.ts:94-176` | SSRF URL check, HMAC, timeout, manual redirect policy, per-client cooldown | Source + TS security tests |
|
||||
| Admin cookie integrity/revocation | `core/auth/adminSession.ts:70-154`; `app/api/auth/**` | HMAC verified session with tokenVersion support; 401/403 boundaries | Auth TS regression passed |
|
||||
| MCP permissions / filesystem sandbox | `server/mcp/mcpEngine.js:12-50,167-248` | 17 granular permissions; writes disabled default; path jail/symlink rejects | MCP server suite passed |
|
||||
| Python SDK typed error mapping | `sdk/python/datastack/datastack/exceptions.py:8-84` | Auth/config/quota/payload/file errors mostly non-retryable, connection/rate retryable | Windows Python CI 14/14 |
|
||||
| Public liveness health | `server/index.js:1939-1956`; `app/api/health/route.ts:95-111` | `online` reflects responder; not full transactional readiness | Public endpoint GET online only |
|
||||
|
||||
## Missing / not proven handling — proposals, NOT implemented
|
||||
|
||||
| Gate | Existing evidence | Narrow proposed addition | Risk / invariant |
|
||||
|---|---|---|---|
|
||||
| EH-01 Durable ACK under Redis loss | `server/index.js:165-193` RAM fallback; `server/socket/handlers.js:583-602` ACK | Test Redis RPUSH failure followed by crash. If confirmed, add reliable negative ACK/persist-queue contract with focused regression. | Preserve SDK fallback/spooling & existing auth/ack fields |
|
||||
| EH-02 Partial CSV replay duplication | `server/index.js:981-994` write before trim | Crash/replay fault test; clarify at-least-once vs exactly-once and idempotent recovery strategy. | Do not silently drop events or rewrite existing CSV |
|
||||
| EH-03 Degraded readiness | `/health` source | Keep existing public liveness backward compatible; optionally protected readiness with PG/Redis/disk dependency evidence. | No public status/availability semantic regression |
|
||||
| EH-04 Docker runner filesystem | CI #50 containerd lstat error | Capture runner snapshotter/storage/logs and BuildKit proof, retry only affected job once on clean isolated builder. | No production Docker prune or volume change |
|
||||
| EH-05 Linux Python provisioning | CI #45 apt 404 | Use stable Python runner or existing Windows 14/14 job in canonical CI matrix. | No change to Python SDK package semantics |
|
||||
| EH-06 Supply-chain advisory details | CI #50 24/26 summaries | Generate advisory ID/package/version/production-path inventory, apply compatible pinned patches only when justified. | No blanket major upgrades, no `audit fix --force` |
|
||||
| EH-07 WebSocket origin/defaults | `server/index.js:1086-1089` | Document access control and test raw WS handshake plus verified JWT behavior; adjust only with repro and approval. | Avoid breaking legitimate SDK cross-origin connection |
|
||||
|
||||
## Mandatory error-handling acceptance matrix (disposable only)
|
||||
|
||||
- 401 invalid/expired/rotated JWT, 403 revoked/IP forbidden, 400 bad client ID, 413 oversized event, 429 rate limit, 507 quota/disk low, 503 flush-lock timeout: contract and safe error payload tests.
|
||||
- Verify duplicate rejection across HTTP + Socket.IO, Redis outage/resume, multi-client isolation, process crash and CSV replay boundaries.
|
||||
- Verify Python/Node SDK retryability: auth and quota failures never endlessly retry/spool; temporary network errors backoff/spool safely.
|
||||
- Webhooks: URL SSRF/private/cloud metadata reject, redirects rejected, signatures match, bounded timeout/cooldown.
|
||||
- MCP: disabled by default, read vs write permissions, bearer hashing, IP allowlist, sandbox traversal and symlink reject, no secret emission.
|
||||
- Do not run these failure injections against `https://data.ivib.cc/`. Use disposable CI fixtures/data directories/Redis containers only.
|
||||
|
||||
## P01 dependency-install blocker note (2026-11-22)
|
||||
|
||||
Gitea run #58 failed before application error-handling tests because clean npm install found an unresolved transitive lock entry: `@tybys/wasm-util@0.10.5`. No runtime error-handling paths were changed or re-verified in this run. Existing source-level handler inventory remains unchanged; P02 fault-injection gates are **NOT STARTED**.
|
||||
|
||||
## Change control
|
||||
|
||||
Any new error code, status, SDK public exception or alert flow is **feature/API behavior change**: STOP and request explicit new scope approval. This register is documentation for deciding whether a new handler is warranted, not blanket authorization to add handlers.
|
||||
|
||||
## P01 Closure Verification (2026-11-22)
|
||||
|
||||
The previous #58 package-lock error was resolved by adding the exact nested optional `@tybys/wasm-util@0.10.5` lock entry without changing the 1293 original locked packages. Gitea #59 clean installs and all **24/24** TypeScript regression suites passed; #59 had a single test-only TS2339 mock-type declaration error, corrected in scope and verified by **#60 strict TypeScript + ESLint PASS**. P01 made **zero changes** to runtime error-handler implementation, response codes, auth, SDK error classification, telemetry behavior or UI. Existing handler inventory remains valid as source observations. P02 R-01…R-03 fault-injection and P03 infrastructure/security remain unverified; do not claim production fault tolerance from P01.
|
||||
|
||||
|
||||
## P02 R-01–R-03 Diagnostic Addendum — 2026-11-22
|
||||
|
||||
| Gate | Injected failure / expected observation | Scope / remediation gate |
|
||||
|---|---|---|
|
||||
| R-01 Redis durability | Mock `rpush` rejects; in-process websocket `sync_data` ACK may still return `success:true` while the event exists only in RAM. A simulated RAM reset (not killing live services) shows unrecoverable ACKed event if Redis remained empty. | `server/index.js:165-193,1897-1923`, `server/socket/handlers.js:583-602` **READ ONLY**. A correction to ACK/persist/spooling semantics requires explicit approval. |
|
||||
| R-02 CSV replay | Mock Redis LTRIM fails **after** CSV append. Retrying buffered event may write same `eventId` twice, exposing duplicate amplification under persistent failures. | Test the web-side `DataBufferEngine.flush` CSV-before-trim pattern; direct ingestion writer proof remains separate. Deduplication scheme or exactly-once guarantees require explicit approval. |
|
||||
| R-03 availability | Redis `llen` rejection leaves Express `/health` online with `redisConnected:false`. Recovery flips the flag while HTTP 200 remains unchanged. | Public 200 is liveness by existing contract; a protected dependency readiness probe/503 is **not implemented** and needs explicit approval. |
|
||||
|
||||
Security invariants: do not expose secrets in ACK/errors, keep JWT/auth and 401/403/429/503/507 contracts unchanged, and never run failure-injection against actual Redis, Postgres, production API, live events, or user CSV. Disposable fake Redis and temporary files only. CI #63: https://dev.ivib.cc/vibtools/DataStack/actions/runs/63; results tracked in notes/003.
|
||||
|
||||
|
||||
## P02 Runtime Candidate — Error-path change inventory (pending CI)
|
||||
|
||||
| Path | Candidate result | Explicit limitation |
|
||||
|---|---|---|
|
||||
| Redis `RPUSH` rejects with configured Redis client | Retains event in volatile RAM as preexisting fallback but returns `BUFFER_PERSIST_FAILED` to Socket.IO via thrown error; **no successful ACK** for that failure; error text does not expose connection details | No-Redis intentional legacy RAM mode unchanged, still not a durable guarantee |
|
||||
| `sync_data` and `batch_sync` failures | `success:false`, `code:BUFFER_PERSIST_FAILED` and best-effort rollback of previously claimed idempotency keys, negative failure marker for in-process retries | If claim rollback cannot reach Redis and process crashes, durable claim/queue atomicity remains unsolved |
|
||||
| Redis buffer `LTRIM` rejects after successful CSV append | Subsequent flush checks physically stored CSV IDs and avoids appending matching rows again; Redis is trimmed only after successful check/write | Concurrent independent CSV appenders, compressed archived CSV, corrupt partial rows, and per-flush CSV scan cost require separate proof |
|
||||
| Legacy public health | **UNCHANGED** HTTP 200 liveness contract and Redis-connected diagnostic field; R-03 readiness is not introduced in this approval | Does not prove full DB/Redis transactional readiness |
|
||||
|
||||
Security/API invariants: leave token/JWT/auth/rate limits/quotas/webhooks/MCP/sandbox/UI/SDK unchanged. No production Redis/Postgres/API/CSV mutation. No lockfile/dependency versions or CI workflow changes. CI acceptance remains pending; these are code-level observations, not release certification.
|
||||
|
||||
## P02-RUNTIME-REMEDIATION-02 — Updated safety contract evidence
|
||||
|
||||
| Scenario | In-scope behavior | Residual |
|
||||
|---|---|---|
|
||||
| Port 4000 Redis `RPUSH` failure | `BUFFER_PERSIST_FAILED`, `success:false`; no Redis transport diagnostics disclosed in client ACK | SDK can retry via HTTP; Port 3000 volatile RAM success path remains unpatched |
|
||||
| Port 4000 without Redis | Await actual CSV flush before positive ACK; disk error yields negative ACK and queue retained | Disk API does not provide fsync-level power-loss guarantees |
|
||||
| Stale idempotency after restart | Never treat a claim alone as persisted; only accept a duplicate after in-memory acknowledged proof, Redis queued ID or read-only CSV partition proof | Bounded scans may cause temporary negative ACK for otherwise durable old events, rather than unsafe success |
|
||||
| Mixed `batch_sync` with uncertain claim | Overall negative `BUFFER_PERSIST_FAILED`; newer items may already be persisted, repeat dedupe resolves them | Preserve existing response fields and rate/quota/auth validations |
|
||||
| Redis `LTRIM` fails after CSV write | On retry, scan CSV/CSV.gz by client/date/event ID and skip already written event; trim Redis only after safe check | Cross-process exact-once not proven; I/O cost needs throughput validation |
|
||||
| Port 3000 HTTP `pushAsync` / `pushBatchAsync` | **UNCHANGED** (excluded from current approval); Redis error can return HTTP success with data only in volatile RAM | **OPEN R-01 blocker**, requires separate approval; `core/Security/security.ts` precommit idempotency claims may also need scoped rollback |
|
||||
| Public `/health` | Unchanged 200 liveness, `redisConnected` diagnostic | No dependency readiness probe under P02-R01/R02 authorization |
|
||||
|
||||
Do not silently remap 401/403/429/507 errors; no SDK edits or live fault injection. Tests use mock Redis and temp CSV only. Relevant CI #66/#68/#70 in notes/003.
|
||||
@@ -0,0 +1,70 @@
|
||||
# DataStack — Actual Implementation / Working-Feature Register
|
||||
|
||||
Frozen source HEAD: `d725841ebc828d58cbe90f517da9e600f23c4630`. Date: 2026-11-22.
|
||||
**Evidence levels**: SOURCE = verified code present; CI PASS = focused automated tests/build passed; LIVE READ = public read-only endpoint observed; NOT VERIFIED = no independent safe live runtime evidence. These are deliberately different. Do NOT infer production DB/S3/MCP health from a public `online` response.
|
||||
|
||||
| Capability / feature | Exact representative path | Baseline evidence | Actual live conclusion | Changed by P01/P02/P03 |
|
||||
|---|---|---|---|---|
|
||||
| Next.js 15 public landing and app pages | `app/**`, `docker/Dockerfile.web` | Next.js CI build PASS and 22/22 static pages; public landing loads | LIVE READ for landing only | None |
|
||||
| Console admin authentication/setup | `app/api/auth/**`, `core/auth/adminUsers.ts`, `core/auth/adminSession.ts` | SOURCE + auth regression suite PASS | Admin login NOT live-tested | None |
|
||||
| Roles / owner-admin-operator-viewer | `core/auth/**`, `components/layout/VconShell.tsx` | SOURCE + RBAC TS tests PASS | NOT live-tested | None |
|
||||
| SDK registered clients, token issuance/revoke/rotate | `core/sdk/sdkManager.ts`, `app/api/clients/**` | SOURCE + client/auth TS regression PASS | NOT live-tested | None |
|
||||
| Next.js HTTP event ingestion | `app/api/events/route.ts` | SOURCE + TS tests PASS | No live writes performed | None |
|
||||
| Express + Socket.IO ingestion | `server/index.js`, `server/socket/handlers.js` | SOURCE + sync/SDK tests PASS | Not live end-to-end verified | None |
|
||||
| Rate limit, dedupe, payload validation | `server/socket/handlers.js`, `app/api/events/route.ts` | SOURCE + tests PASS | Not live verified | None |
|
||||
| Redis ingestion queue/fallback | `server/index.js:165-193`, `core/data/buffer.ts` | SOURCE + TS storage tests; R-01 ACK durability risk | Not guaranteed lossless on outage | None |
|
||||
| CSV partition/rotation/flush | `server/workers/csvWriter.js`, `core/Storage/csvStorage.ts` | SOURCE + regression; ingestion image CI build PASS | R-02 crash replay semantics NOT confirmed | None |
|
||||
| Compression and S3 archival | `core/Storage/s3Archive.ts`, `core/Storage/csvStorage.ts` | SOURCE + storage tests | No live S3 credentials or archive tests | None |
|
||||
| Data browser, export CSV/JSON/NDJSON | `app/api/export/route.ts`, `app/api/data/route.ts` | SOURCE + TS tests | NOT live-tested | None |
|
||||
| Storage quota / disk admission | `core/Storage/csvStorage.ts` | SOURCE + tests; 507 codes | NOT live-tested | None |
|
||||
| Dashboard, client status, counts | `lib/vconUiHelpers.ts`, `app/vcon/clients/page.tsx` | SOURCE; client status helper tests; stale old regex CI-04 | No live user session proof | None |
|
||||
| Prometheus and metrics bridge | `app/api/prometheus/route.ts`, `server/index.js` | SOURCE + tests | NOT live authenticated | None |
|
||||
| Webhook alerts and SSRF/HMAC | `core/alerts/webhookNotifier.ts` | SOURCE + tests | NOT live-tested | None |
|
||||
| CloudCmd file browser | `server/filesManager.js`, `tests/files-manager.test.ts` | SOURCE; files-manager suite 4 tests PASS | NOT live authenticated | None |
|
||||
| MCP engine (17 permissions) | `server/mcp/mcpEngine.js`, `app/api/mcp/route.ts` | SOURCE + MCP server suite 3 tests PASS; write flags default false | NOT live connected/authenticated | None |
|
||||
| Python SDK v2.2 + compat package | `sdk/python/datastack/datastack/**`, `sdk-python/**` | Windows CI **14/14** PASS | No real external SDK session | None |
|
||||
| Node SDK v2.2 + offline spool | `sdk/node/datastack/**` | Native Windows SDK compile PASS; SDK-specific TS regression PASS | No live external SDK session | None |
|
||||
| PWA/offline shell | `app/**`, `public/**` | SOURCE + phase06 suite PASS | Browser offline not live-tested | None |
|
||||
| Docker Compose stack | `docker/docker-compose.yml` | CI config PASS, ingestion image PASS | Deployed app already serves public health; deployed SHA unverified | None |
|
||||
| Docker web/proxy image | `docker/Dockerfile.web`, `docker/Dockerfile.proxy` | Web layer fail on containerd; proxy unrun | Existing Coolify instance appears online but CI image parity unverified | None |
|
||||
| Health endpoint | `app/api/health/route.ts` | LIVE READ `status:online` on 2026-11-22T00:01:19Z | Confirmed public API liveness; not end-to-end readiness | None |
|
||||
|
||||
## Mandatory post-phase update convention
|
||||
|
||||
After EACH P01/P02/P03 close, amend only affected table rows:
|
||||
- `Feature/capability` (exact added/changed behavior or `UNCHANGED`)
|
||||
- `Source file/line + new SHA`
|
||||
- `CI evidence` (run URL, pass/failed count, build exit)
|
||||
- `Live status` (READ ONLY, AUTHENTICATED VERIFIED, NOT VERIFIED, etc.; no fictitious claims)
|
||||
- `Compatibility` (UI/auth/SDK/API/storage preserved? test proof)
|
||||
- `Risk remaining` and next approval.
|
||||
Do not mark "actual working" simply because a patch compiled. Distinguish source, CI, and actual deployment.
|
||||
## Change log
|
||||
- P00: No feature added/modified. `notes/**` documentation only. 0/3 implementation phases completed.
|
||||
- P01: **CLOSED — 1/3 implementation phases**. CI-01…05 corrected exclusively in package-lock, obsolete bun.lock removal, scoped regression/type tests and Gitea CI harness. **No actual application, UI, backend, API, SDK or production functionality was added, removed or altered.** Gitea #59: committed-lock Linux/Windows clean install PASS; Node SDK builds PASS; all 24 TS suites exit0 with zero timeouts; Next standalone 22/22 pages PASS. One historical #59 test-only declaration TS error fixed; #60 strict TS zero errors and full ESLint PASS. Previous canonical Python SDK 14/14 (#48) preserved but not rerun. No live endpoint mutation or deployment; live data/Redis/S3/MCP actual operational status is not established.
|
||||
- P02: **BLOCKED pending separate approved runtime remediation**. Three disposable fault-injection tests demonstrated existing behavior: positive ACK on Redis write failure with RAM-only data (R-01), duplicate appended event ID after Redis trim failure and retry in web-side buffer (R-02), and public health 200/online when Redis is down (R-03). These are **diagnostic tests, not production fixes**. Zero app/API/UI/SDK/runtime changes, no live deploy. CI #63. P01 remains closed (1/3 phases complete).
|
||||
- P03: pending.
|
||||
|
||||
## P02 Diagnostic Feature Record — 2026-11-22
|
||||
|
||||
- **New production features: NONE.** This phase adds only three disposable failure-injection scenarios across two existing test suites; tests are not production handlers. Existing source/UI/auth/backend/SDK/MCP, Redis/PG/CSV services, Next/Express health interfaces and deployment remain unmodified.
|
||||
- R-01: existing volatile RAM fallback and WS ACK behavior audited, *not corrected*. Do not mark ACK durability as working merely because a diagnostic test proves current behavior.
|
||||
- R-02: existing CSV-before-Redis-trim order audited, *not corrected*. Exactly-once replay safety is **NOT VERIFIED**.
|
||||
- R-03: current public Express health 200 plus `redisConnected:false` is liveness, not dependency readiness. Separate readiness remains **NOT IMPLEMENTED**.
|
||||
- Gitea disposable CI #63: https://dev.ivib.cc/vibtools/DataStack/actions/runs/63. The previous P01 working results remain valid; no live read/write test or production deploy is included in P02.
|
||||
|
||||
|
||||
## P02 Runtime Candidate Feature Delta — 2026-11-22 (NOT RELEASED)
|
||||
|
||||
- **Intended change:** failure cases on socket ingestion report `BUFFER_PERSIST_FAILED` instead of positive ACK when Redis RPUSH rejects; single and batch code paths tested by new disposable assertions. Ordinary success ACK, auth, limits and SDK public interfaces intended unchanged.
|
||||
- **Intended change:** Redis replay flush on both ingestion/Next paths inspects existing client CSV partitions and filters already-stored event IDs before reappend; safe failure leaves Redis queue untrimmed. This prevents the tested post-append/LTRIM replay duplication but does **not** prove transactionally exactly-once delivery or zero performance impact.
|
||||
- **No changes:** application UI/UX, auth, SDK, database schema, Docker, environment, public R-03 health, other features and production runtime. No deployment or live verification.
|
||||
- **Status:** P02 code candidate locally committed, acceptance CI blocked by Gitea unavailability; **NOT CLOSED**, not production-ready. P01 remains only completed phase.
|
||||
|
||||
## P02 Remediation Hardening Register — 2026-11-22
|
||||
|
||||
- **Changed in source, not deployed:** Port 4000 Socket.IO error ACK behavior on Redis write failure; no-Redis mode now waits for CSV flush before success; duplicate ACK checks actual Redis/CSV durability; mixed batch uncertainty gives negative ACK. EventId retry handling is made fail-closed with in-scope handler logic.
|
||||
- **Changed in source, not deployed:** Port 4000 and web-buffer CSV replay after Redis LTRIM failure now checks persisted CSV/CSV.gz event IDs. Existing file rotation/compression and disk errors need focused tests; scanner I/O impacts high-volume performance and does not certify global exactly-once semantics.
|
||||
- **Unchanged:** UI/UX/pages, public R-03 health shape/status, auth/JWT/SDK implementation, database/Prisma, Docker/Compose, environment, unrelated features, production data, live server and deployment.
|
||||
- **Still NOT working as end-to-end guarantee:** HTTP `POST /api/events` currently may send success after Redis RPUSH fails while only RAM contains the event. This is an additional source-observed release blocker, not something fixed by WS error ACK. **P02 NOT CLOSED; P03 NOT STARTED.**
|
||||
- **Evidence:** Gitea #66 initial remediation PASS; #68 exposed same-ID retry bug fixed in current branch; #70 final focused run awaiting terminal confirmation. The original PC main workspace's 16 staged P01 paths remain untouched.
|
||||
@@ -0,0 +1,273 @@
|
||||
# DataStack — Baseline Freeze, Code Proof & Proposed Patch Index
|
||||
|
||||
Frozen source baseline SHA: `d725841ebc828d58cbe90f517da9e600f23c4630` (2026-11-22, Asia/Dhaka).
|
||||
Source verification: exact GitHub/GitLab/Gitea remote `main` and local HEAD matched this SHA. Local working tree clean; local `origin` configured to `MdNurnobi-Dev/DataStack.git`, and its *local tracking ref* was stale (`725d3c5`), so `ahead 5` alone was NOT evidence GitHub `JILLU-Games` was behind. GitHub `JILLU-Games` read-only branch HEAD verified at `d725841ebc828d58cbe90f517da9e600f23c4630`. No force push, ref rewrite or upstream reset authorized.
|
||||
|
||||
## A. Proof excerpts (verbatim short source fragments, exact baseline files/lines)
|
||||
|
||||
### CI-02 — stale lockfile contract (P01)
|
||||
`tests/phase07-deployment.test.ts:648-650`:
|
||||
```ts
|
||||
test("FINAL-DEPLOY-FIX-01: Single npm lockfile, Dockerfile .runtime-logs ownership parity, 8-table prisma sync, and cold-boot MCP bridge hydration", async () => {
|
||||
assert.equal(existsSync(resolve(process.cwd(), "bun.lock")), false, "Stale bun.lock must stay removed");
|
||||
```
|
||||
`git ls-files bun.lock` listed the file on baseline. **Patch reference**: check if any build consumer references it; if none, remove exactly `bun.lock` while preserving `package-lock.json`. Re-run this specific test.
|
||||
|
||||
### CI-04 — stale UI test expectation (P01)
|
||||
`tests/v2-phase01-storage-quotas.test.ts:788-804`:
|
||||
```ts
|
||||
assert.match(clientsPageSrc, /function isClientExpired\(/);
|
||||
assert.match(clientsPageSrc, /const expired = !revoked && isClientExpired\(client\.expiresAt,\s*now\)/);
|
||||
```
|
||||
`app/vcon/clients/page.tsx:70-85`:
|
||||
```ts
|
||||
const counts = useMemo(
|
||||
() => summarizeUiClientCounts(clients, now),
|
||||
[clients, now],
|
||||
);
|
||||
const computedStatus = classifyUiClientStatus(client, now);
|
||||
```
|
||||
`lib/vconUiHelpers.ts:717,730,754` exports `isUiClientExpired`, `classifyUiClientStatus`, `summarizeUiClientCounts`.
|
||||
**Proposed patch shape** (planning-only, not applied):
|
||||
```diff
|
||||
--- a/tests/v2-phase01-storage-quotas.test.ts
|
||||
+++ b/tests/v2-phase01-storage-quotas.test.ts
|
||||
@@ obsolete regex-based UI expectations, lines 788-804 @@
|
||||
- assert.match(clientsPageSrc, /function isClientExpired\(/);
|
||||
+ assert.match(clientsPageSrc, /summarizeUiClientCounts/);
|
||||
+ assert.match(clientsPageSrc, /classifyUiClientStatus/);
|
||||
```
|
||||
Also **replace the other 3 obsolete implementation-detail regexes** with behavioral assertions against exported helper and page filtering/count data; do not just drop coverage. Exact final diff is generated only during approved P01.
|
||||
|
||||
### CI-03 — test-process hang anchor (P01)
|
||||
`core/data/buffer.ts:347-352,379-391`:
|
||||
```ts
|
||||
state.flushTimer = setInterval(() => {
|
||||
void this.flush().catch(() => undefined);
|
||||
}, state.batchFlushIntervalMs);
|
||||
```
|
||||
Run #45 suite exit codes 124: `r3-phase04-ui-metrics-rbac`, `r4-phase03-sdk-deploy-auth`, `r5-phase01-mcp-foundation-logs`, `r5-phase03-mcp-ui`. Timer is a **suspect**, not a proven sole root cause. **Patch reference:** instrument open handles and add narrow teardown in four named tests; `core/data/buffer.ts` is **read-only** unless new approval.
|
||||
|
||||
### CI-05 — compiler-source proof (P01)
|
||||
`tsconfig.json:27`:
|
||||
```json
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"]
|
||||
```
|
||||
Run #45 job 68 examples:
|
||||
```text
|
||||
tests/phase01-auth.test.ts(88,17): error TS2540: Cannot assign to 'NODE_ENV' because it is a read-only property.
|
||||
tests/r5-phase02-mcp-server.test.ts(510,8): error TS18046: 'deniedClientCreate.content' is of type 'unknown'.
|
||||
tests/v2-phase01-storage-quotas.test.ts(762,64): error TS2554: Expected 0 arguments, but got 1.
|
||||
```
|
||||
**Patch reference:** exact 9 test files / line map in `001`. Use correct typings/type guards and current API signatures, not TS ignore or global tsconfig exclusion.
|
||||
|
||||
### CI-01 — Windows clean-install lockfile mismatch (P01)
|
||||
Run #42 job 63:
|
||||
```text
|
||||
npm error Missing: @img/sharp-win32-x64@0.35.5 from lock file
|
||||
npm error Missing: @unrs/resolver-binding-win32-x64-msvc@1.13.0 from lock file
|
||||
```
|
||||
Run #45 job 71 showed success **only after temporary runner** `npm install --package-lock-only`, followed by `npm ci` and Node SDK build. **Patch reference:** `package-lock.json` optional/native dependencies, retain pinned package graph; verify unchanged tracked lock under CI on Linux/Windows.
|
||||
|
||||
### CI-06 — Python runner packages (P03)
|
||||
Run #45 job 67:
|
||||
```text
|
||||
E: Failed to fetch ... python3.9-venv_3.9.2-1+deb11u7_amd64.deb 404 Not Found
|
||||
```
|
||||
`.gitea/workflows/datastack-ci.yml` Python install step uses `apt-get update -qq; apt-get install -y python3 python3-venv python3-pip`. Run #48 job 74 executes 14 tests PASS on Windows. **Patch reference:** CI job Python provisioning only.
|
||||
|
||||
### CI-07 — Docker web layer failure (P03)
|
||||
`docker/Dockerfile.web:13`:
|
||||
```dockerfile
|
||||
COPY --from=dependencies /app/node_modules ./node_modules
|
||||
```
|
||||
Run #50 job 76:
|
||||
```text
|
||||
failed to create diff tar stream: lstat .../app/node_modules/@uiw: no such file or directory
|
||||
```
|
||||
`docker/Dockerfile.server` produced tagged ingestion image; Docker Compose `config --no-interpolate --quiet` PASS. **Patch reference:** `.gitea/workflows/datastack-docker-ci.yml` runner/cache/BuildKit; Dockerfile modification conditional on independent reproduction and new approval.
|
||||
|
||||
### CI-08 — npm advisory summary (P03)
|
||||
Run #50 job 76:
|
||||
```text
|
||||
24 vulnerabilities (23 moderate, 1 high)
|
||||
26 vulnerabilities (25 moderate, 1 high)
|
||||
```
|
||||
**No evidence of specific advisory IDs yet.** Patch reference `package.json`/`package-lock.json` only after isolated `npm audit --json` with package/CVE/runtime attribution. Never add counts or claim 50 unique advisories.
|
||||
|
||||
### R-01 — Redis volatile fallback ACK risk (P02, conditional)
|
||||
`server/index.js:165-193`:
|
||||
```js
|
||||
try {
|
||||
bufferLen = await redis.rpush(REDIS_BUFFER_KEY, ...serialized);
|
||||
redisConnected = true;
|
||||
} catch {
|
||||
redisConnected = false;
|
||||
}
|
||||
// ...
|
||||
bufferQueue.push(...events);
|
||||
return bufferQueue.length;
|
||||
```
|
||||
`server/socket/handlers.js:583-602`:
|
||||
```js
|
||||
bufferQueue.push(event);
|
||||
try {
|
||||
await onBufferPush();
|
||||
} catch (persistErr) {
|
||||
// callback BUFFER_PERSIST_FAILED
|
||||
}
|
||||
if (callback) callback({ success: true, eventId });
|
||||
```
|
||||
**Potential issue**: a successful ACK does not necessarily mean durable storage after Redis failure; test first. Proposed patch is NOT predetermined.
|
||||
|
||||
### R-02 — CSV before Redis trim (P02, conditional)
|
||||
`server/index.js:981-994`:
|
||||
```js
|
||||
const res = await writer.writeBatch(parsedBatch);
|
||||
// ...
|
||||
await redis.ltrim(REDIS_BUFFER_KEY, rawItems.length, -1);
|
||||
```
|
||||
**Potential issue**: crash after partial write or before list trim may replay buffered rows. Test with injected partial failures and compare event IDs before prescribing exactly-once guarantee.
|
||||
|
||||
### R-03 — Health shows service liveness (P02, conditional)
|
||||
`server/index.js:1939-1955`:
|
||||
```js
|
||||
const redisBufferSize = await getRedisBufferLen();
|
||||
res.json({ status: 'online', /* ... */ redisConnected, /* ... */ });
|
||||
```
|
||||
`app/api/health/route.ts:95-105`:
|
||||
```ts
|
||||
const bufferStats = await DataBufferEngine.getBufferStatsAsync();
|
||||
return NextResponse.json({ status: 'online', service: 'DataStack Web API', /* ... */ });
|
||||
```
|
||||
**Potential issue**: liveness is not transactional readiness. Preserve existing public endpoint shape and verify separately.
|
||||
|
||||
## B. Source-to-patch navigation
|
||||
|
||||
- P01: `package-lock.json`; `bun.lock`; `tests/phase07-deployment.test.ts:649`; `tests/v2-phase01-storage-quotas.test.ts:762,783,788-804`; 4 timeout tests; 9 TS test files; `.gitea/workflows/datastack-ci.yml`.
|
||||
- P02 conditional: `server/index.js:165-193,943-994,1939-1956`, `server/socket/handlers.js:583-602`, `server/workers/csvWriter.js:265-323`, `app/api/health/route.ts:95-111`; associated test files. Read-only until fault reproduction.
|
||||
- P03: `.gitea/workflows/datastack-ci.yml`, `datastack-python-ci.yml`, `datastack-docker-ci.yml`, `datastack-eslint-ci.yml`; `package.json` / `package-lock.json` only justified dependency changes. Source Dockerfile edits separately approved only if needed.
|
||||
|
||||
## C. Documentation baseline update record
|
||||
|
||||
This file **freezes the source baseline**, not the future documentation-commit SHA. After adding `notes/**`, record commit SHA and three remote SHAs in `notes/003` and the user-facing result. Subsequent P01 implementation should inspect `git diff d725841ebc828d58cbe90f517da9e600f23c4630..HEAD` and permit only these notes as intervening changes; any unexpected source edits require a new review.
|
||||
|
||||
## D. P01 Actual Patch & CI Closure Proof — 2026-11-22
|
||||
|
||||
Frozen source baseline remains `d725841ebc828d58cbe90f517da9e600f23c4630`, docs baseline `d8ac96e39dad4ea3b241c1d2f16f959c5215701e`. CI-verified implementation snapshot `7d8eebd3dc867e82113343403b63ce1d4ed20584` (Gitea disposable P01 branch). Permanent main closure is single squash commit containing this note; verify post-push three remote refs/content trees.
|
||||
|
||||
### Lock and package integrity evidence (CI-01 / CI-02)
|
||||
|
||||
```json
|
||||
{
|
||||
"node_modules/@napi-rs/wasm-runtime/node_modules/@tybys/wasm-util": {
|
||||
"version": "0.10.5",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
|
||||
"integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
|
||||
"optional": true,
|
||||
"dependencies": {"tslib": "^2.4.0"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The root `@tybys/wasm-util@0.9.0` remains unchanged; 68 optional entries added, 1293 old entries unchanged, none removed/repinned, all added entries with registry tarball and integrity, `package.json` unchanged. `bun.lock` removed after checking no active consumers. Windows and Linux `npm ci --no-audit --no-fund` PASS using committed lock without temporary regeneration.
|
||||
|
||||
### Test-only teardown correction (CI-03 / CI-05)
|
||||
|
||||
`tests/r5-phase01-mcp-foundation-logs.test.ts` local CommonJS require declaration now explicitly includes `stopTimers`, matching the existing runtime export; `test.after` releases ingestion timers and `DataBufferEngine.shutdown()` without any changes to runtime source:
|
||||
|
||||
```ts
|
||||
const ingestionServer = require("../server/index.js") as {
|
||||
setDbPoolForTests: (pool: unknown) => void;
|
||||
syncSettingsFromDatabase: () => Promise<boolean>;
|
||||
stopTimers: () => void;
|
||||
};
|
||||
|
||||
test.after(async () => {
|
||||
ingestionServer.stopTimers();
|
||||
SDKManager.stopActivityFlushTimerForTests();
|
||||
await DataBufferEngine.shutdown();
|
||||
});
|
||||
```
|
||||
|
||||
Remaining CI-05 corrections were confined to 9 test file type contracts; CI-04 replaced old `isClientExpired` page regex expectations with `classifyUiClientStatus` + `summarizeUiClientCounts` behavioral assertions. No TS strictness flags disabled, no global `any` blanket suppression, no SDK/API runtime signature changed.
|
||||
|
||||
### Exact gate results
|
||||
|
||||
- [Run #58](https://dev.ivib.cc/vibtools/DataStack/actions/runs/58): failed at lockfile nested dependency before tests; historical and superseded.
|
||||
- [Run #59](https://dev.ivib.cc/vibtools/DataStack/actions/runs/59): overall failed because exactly one test mock TypeScript declaration lacked `stopTimers`, but separate job results independently verified **24/24 TypeScript suites exit0**, no timeouts, Linux/Windows committed-lock clean npm installs, Node SDK compilation and Next.js standalone build + 22/22 pages all PASS.
|
||||
- [Run #60](https://dev.ivib.cc/vibtools/DataStack/actions/runs/60): focused quality-only retry after exact test-type correction, **strict `npx tsc --noEmit` PASS 0 errors** and **`npm run lint` PASS**.
|
||||
- [Run #48](https://dev.ivib.cc/vibtools/DataStack/actions/runs/48): previous Python SDK 14/14 PASS, no Python source edits or P01 rerun.
|
||||
|
||||
Targeted path/diff audit from prior documentation HEAD: 16 scoped code/test/CI paths plus notes `001–006`; `git diff --check` PASS. P02 remaining R-01…R-03 are conditional reliability risks, not confirmed application bugs. P03 Docker/Python-runner/advisory issues still open. No live app, deployment, database, security defaults or user features changed.
|
||||
|
||||
|
||||
## E. P02 Concrete Code/CI Evidence — 2026-11-22
|
||||
|
||||
**Frozen previous phase:** P01 Gitea/GitHub commit `667a140c4e9e75382bfdcdbe1d3e9eb96f6e808a`. P02 test-only commit `bbe73d91666641743cbec6cf7203f1694094caef` adds 103 lines across exactly two approved test paths. Gitea CI #63: https://dev.ivib.cc/vibtools/DataStack/actions/runs/63. No application source modification.
|
||||
|
||||
### R-01 ACK after Redis RPUSH failure
|
||||
|
||||
`server/index.js:171-192`:
|
||||
|
||||
```js
|
||||
try { bufferLen = await redis.rpush(REDIS_BUFFER_KEY, ...serialized); }
|
||||
catch { redisConnected = false; }
|
||||
// ... Redis failure path
|
||||
bufferQueue.push(...events);
|
||||
return bufferQueue.length;
|
||||
```
|
||||
|
||||
`server/socket/handlers.js:583-602` invokes `await onBufferPush()` and then calls `callback({success:true,eventId})` unless an exception escapes. Test: `tests/phase02-sync.test.ts`, `P02 R-01 diagnostic`, overriding fake Redis `rpush` to reject; check ACK, absent Redis persistence, volatile RAM, and simulated reset. No real process exit.
|
||||
|
||||
### R-02 replay after append-before-trim
|
||||
|
||||
`core/data/buffer.ts:795-809` and Port-4000 `server/index.js:981-993` order `appendBatch()/writeBatch()` before `redis.ltrim()`. Test: `tests/phase03-storage-buffer.test.ts`, `P02 R-02 diagnostic`; inject the *first* LTRIM failure only after successful append, verify still queued, retry flush and count duplicate `eventId` in appended rows. Web-side representative fault-injection; not a complete ingestion-crash certificate.
|
||||
|
||||
### R-03 public status versus dependency readiness
|
||||
|
||||
`server/index.js:1926-1957` catches Redis LLEN error, sets `redisConnected=false`, and returns HTTP 200 `status:online`. Test `P02 R-03 diagnostic` mocks LLEN failure and recovery. This preserves existing public shape rather than implementing a readiness endpoint. PG startup fail-closed coverage remains source-only/NOT VERIFIED.
|
||||
|
||||
**Patch scope:** modified only `tests/phase02-sync.test.ts` and `tests/phase03-storage-buffer.test.ts` (plus notes/001–006). Original local user-staged P01 work preserved. Runtime files examined read-only. No production host, Redis, DB, CSV, API, service, CI workflow, release, or security setting changed.
|
||||
|
||||
|
||||
### CI #63 observed P02 results
|
||||
|
||||
- `P02 R-01 diagnostic: Redis RPUSH failure yields positive WS ACK for volatile RAM-only event` — **ok 15**, test suite `phase02-sync` exit 0. Diagnostic indicates acknowledged event loss on simulated RAM reset when Redis has no record.
|
||||
- `P02 R-03 diagnostic: Redis query failure leaves public ingestion health 200/online` — **ok 16**, same suite exit 0, Redis flag false while liveness stays online.
|
||||
- `P02 R-02 diagnostic: post-CSV Redis trim failure replays identical event on retry` — **ok 18**, `phase03-storage-buffer` suite exit 0; duplicate append after retry reproduced on representative web buffer path. **Direct ingestion Port 4000 CSV worker crash coverage remains outstanding** and should be requested in remediation approval before guarantee changes.
|
||||
- These three diagnostic tests **prove findings, do not close production-readiness**. See Gitea https://dev.ivib.cc/vibtools/DataStack/actions/runs/63; never call run successful until terminal conclusion is confirmed. No server-side source fix applied.
|
||||
|
||||
|
||||
## F. P02 Remediation Candidate Patch Proof — 2026-11-22
|
||||
|
||||
Base: Gitea/GitHub published P02 diagnostic tree `fd57a3518d14bcb8367ce9ab9c3ec306bcfc9898`; GitLab distinct commit, same previous tree. Local candidate commit `44eee8877e40d1683f44502c2a0ba3d437a03b88` on isolated worktree. Initial exact delta: 5 approved source/test paths, 310 insertions and 22 deletions, no application UI, Python SDK, auth, public health route, CI or deployment edit. `git diff --check` and `node --check` on JS files PASS.
|
||||
|
||||
- `server/index.js:pushEventsToRedisOrFallback`: catch RPUSH failure, keep previous RAM buffering, throw sanitized `BUFFER_PERSIST_FAILED`; no positive ACK for that branch.
|
||||
- `server/socket/handlers.js:sync_data/batch_sync`: negative ACK and best-effort claimed idempotency-key rollback with negative retry guard, no change to legitimate duplicate success path or existing auth/limits/error codes.
|
||||
- `server/index.js:flushBuffer` and `core/data/buffer.ts:flush`: scoped streaming CSV/CSV.gz read-before-reappend (parsing quoted/multiline rows), exact client/date/event ID match; failures abort before Redis LTRIM. No changes to `server/workers/csvWriter.js`.
|
||||
- `tests/phase02-sync.test.ts`: R-01 single/batch outage and duplicate claim ACK negative, successful recovery ACK, and unchanged R-03 liveness.
|
||||
- `tests/phase03-storage-buffer.test.ts`: web-side replay verifies exactly one physically stored row; new direct Port 4000 writer Redis-trim failure/recovery proof. All tests on fake Redis and disposable temp CSV paths.
|
||||
|
||||
**Unverified:** Gitea P02 implementation acceptance was unavailable due inaccessible host/connector. Local `npm ci` not confirmed successful. Do not invent a CI run ID or claim full PASS. Full cross-process transactional exactly-once and all Redis claim crash windows are out of proof scope and may require exact additional approval. The streaming dedupe scan changes I/O cost per flush; performance validation before production is required.
|
||||
|
||||
|
||||
### Blocked acceptance evidence — actual tool outcomes
|
||||
|
||||
- JS syntax: local `node --check server/index.js` and `node --check server/socket/handlers.js` PASS.
|
||||
- Source scope: local `git diff --check` PASS; only the five allowed P02 runtime/test paths changed before notes updates.
|
||||
- Gitea: connection returned `UNAVAILABLE: McpServerError: Connection failed`; Git remote `dev.ivib.cc` unresponsive. No Gitea CI run ID exists for candidate `44eee8877e40d1683f44502c2a0ba3d437a03b88`.
|
||||
- Local Windows npm: `npm ci` failed `ETARGET yaml@2.9.1` and cleanup `EPERM` in the isolated worktree, **not** a TypeScript/test result. Dependency changes are out of P02 scope.
|
||||
- Therefore neither TS typecheck nor regression-suite remediation acceptance is established; keep P02 BLOCKED and do not advance P03 or alter any protected runtime/source beyond this approval.
|
||||
|
||||
## F. P02-RUNTIME-REMEDIATION-02 — Exact edge-case proof and scope audit (2026-11-22)
|
||||
|
||||
**Baseline** `fd57a3518d14bcb8367ce9ab9c3ec306bcfc9898`; isolated branch `p02-runtime-remediation-20261122`; patch revision `5c880885378ae0f4fa8dd3a145f9c7055dada635`. Scope: `server/index.js` (RPUSH fallback/onBufferPush/flush), `server/socket/handlers.js` (single/batch ACK + durability verification helper), `core/data/buffer.ts` (flush), `tests/{phase02-sync,phase03-storage-buffer,r4-phase02-ingestion-audit-streaming}.test.ts` and `notes/001–006` only. No other source file/CI workflow/dependency/SDK/UI change.
|
||||
|
||||
**Runtime contract and tests:** configured Redis RPUSH rejection -> negative `BUFFER_PERSIST_FAILED`; Redis-free Socket.IO ACK -> synchronous local CSV flush, with negative ACK on disk error; fail closed on previous Redis idempotency claim unless persisted to Redis buffer or matching physical CSV; recover same eventId after Redis reconnection; mixed batch uncertain duplicate remains negative until persistence proven. R-02 test injects failure after Port 4000 CSV append and before Redis trim, verifies subsequent retry does not add another row, including moved/rotated `.csv.gz`. R-03 `/health` remains unchanged.
|
||||
|
||||
**Test-only HTTP residual diagnostic:** `tests/phase02-sync.test.ts` adds Redis RPUSH failure against `POST /api/events` on a fake Redis. Expected prior behavior: HTTP 200 `success:true` while `DataBufferEngine.getLocalBufferSnapshot()` has the event and Redis buffered list is empty, then simulated RAM loss. This *diagnostic PASS* would confirm a remaining risk, not a completed fix. Source: `app/api/events/route.ts:744-754`, `core/data/buffer.ts:412-442,481-491`, `core/Security/security.ts:230-375`, Node SDK `sdk/node/datastack/index.ts:643-666,916-942`. Those runtime methods are **READ ONLY under current approval**.
|
||||
|
||||
**CI ledger:** [#66](https://dev.ivib.cc/vibtools/DataStack/actions/runs/66) initial in-scope implementation overall SUCCESS; [#68](https://dev.ivib.cc/vibtools/DataStack/actions/runs/68) discovered same-ID retry local claim leak, corrected in subsequent branch commit; [#70](https://dev.ivib.cc/vibtools/DataStack/actions/runs/70) revised source/test acceptance queued/running as of this addendum. Do not assert it PASS without terminal proof.
|
||||
|
||||
**Security/limitations:** never expose Redis backend errors or credentials in ACKs; preserve auth, quotas, rate limits and SDK response fields. Duplicate proof reads no more than 512 recent Redis buffered records and scans up to 256 MiB of CSV partition data with an abort deadline of 1800 ms, refusing uncertain duplicate-success. R-02 streaming CSV scan per flush has unmeasured throughput cost; no globally atomic multi-process exactly-once claim. Unmodified production data, no migrations, no live events, no releases/deploys; original local root staged changes untouched. P02 remains BLOCKED until a separate narrow HTTP durability approval or an equivalent tested safe contract.
|
||||
Generated
+1016
File diff suppressed because it is too large.
Load diff
+92
-8
@@ -164,7 +164,18 @@ function setRedisClientForTests(client) {
|
||||
|
||||
async function pushEventsToRedisOrFallback(events) {
|
||||
if (!events || events.length === 0) return bufferQueue.length;
|
||||
// Failed persistence may leave an unacknowledged RAM event beside an SDK
|
||||
// retry with the same ID. Persist each client/event ID at most once per push.
|
||||
const seen = new Set();
|
||||
events = events.filter((evt) => {
|
||||
if (!evt || !evt.clientId || !evt.eventId) return true;
|
||||
const key = JSON.stringify([evt.clientId, evt.eventId]);
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
const redis = getRedisClient();
|
||||
let persistFailed = false;
|
||||
if (redis) {
|
||||
const serialized = events.map((e) => JSON.stringify(e));
|
||||
let bufferLen = null;
|
||||
@@ -173,6 +184,7 @@ async function pushEventsToRedisOrFallback(events) {
|
||||
redisConnected = true;
|
||||
} catch {
|
||||
redisConnected = false;
|
||||
persistFailed = true;
|
||||
}
|
||||
|
||||
if (bufferLen !== null) {
|
||||
@@ -189,6 +201,11 @@ async function pushEventsToRedisOrFallback(events) {
|
||||
}
|
||||
|
||||
bufferQueue.push(...events);
|
||||
if (persistFailed) {
|
||||
// Keep the volatile fallback for later recovery, but never ACK it as durable.
|
||||
// Suppress sensitive Redis transport details in the client-facing error.
|
||||
throw new Error('BUFFER_PERSIST_FAILED: Redis unavailable; event not durably queued');
|
||||
}
|
||||
return bufferQueue.length;
|
||||
}
|
||||
|
||||
@@ -834,6 +851,61 @@ async function isClientDeletedForFlush(clientId, redis, cache) {
|
||||
}
|
||||
|
||||
async function flushBuffer(options = {}) {
|
||||
|
||||
// P02 R-02: Redis and CSV cannot be committed atomically. Before replaying an
|
||||
// untrimmed Redis batch, check actual CSV partitions for previously written IDs.
|
||||
// Streaming parsing bounds memory and preserves multiline/quoted CSV fields.
|
||||
const excludeAlreadyPersisted = async (events) => {
|
||||
if (!events.length) return events;
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const zlib = require('node:zlib');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const { Writable } = require('node:stream');
|
||||
const { parse } = require('csv-parse');
|
||||
const groups = new Map();
|
||||
for (const event of events) {
|
||||
const clientId = String(event.clientId || 'unknown');
|
||||
const date = writer.extractSafePartitionDate(event.timestamp);
|
||||
const key = JSON.stringify([clientId, date]);
|
||||
if (!groups.has(key)) groups.set(key, { clientId, date, ids: new Set() });
|
||||
groups.get(key).ids.add(String(event.eventId));
|
||||
}
|
||||
const persisted = new Set();
|
||||
for (const [groupKey, group] of groups) {
|
||||
const dir = writer.ensureClientDir(group.clientId);
|
||||
const entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !writer.isPartitionFilename(entry.name) ||
|
||||
writer.extractDateFromFilename(entry.name) !== group.date) continue;
|
||||
const reader = fs.createReadStream(path.join(dir, entry.name));
|
||||
const streams = [reader];
|
||||
if (entry.name.endsWith('.gz')) streams.push(zlib.createGunzip());
|
||||
streams.push(parse({ columns: true, bom: true, skip_empty_lines: true }));
|
||||
streams.push(new Writable({
|
||||
objectMode: true,
|
||||
write(row, _enc, done) {
|
||||
if (row.clientId === group.clientId && group.ids.has(String(row.eventId))) {
|
||||
persisted.add(JSON.stringify([groupKey, String(row.eventId)]));
|
||||
}
|
||||
done();
|
||||
},
|
||||
}));
|
||||
// On read/parse failure, abort without LTRIM: never discard uncertain rows.
|
||||
await pipeline(...streams);
|
||||
}
|
||||
}
|
||||
const batchSeen = new Set();
|
||||
return events.filter((event) => {
|
||||
const key = JSON.stringify([String(event.clientId || 'unknown'),
|
||||
writer.extractSafePartitionDate(event.timestamp)]);
|
||||
const rowKey = JSON.stringify([key, String(event.eventId)]);
|
||||
if (persisted.has(rowKey) || batchSeen.has(rowKey)) return false;
|
||||
batchSeen.add(rowKey);
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
if (pendingRedisWrites.size > 0) {
|
||||
await Promise.allSettled([...pendingRedisWrites]);
|
||||
}
|
||||
@@ -979,9 +1051,12 @@ async function flushBuffer(options = {}) {
|
||||
if (lockLost) break;
|
||||
|
||||
if (parsedBatch.length > 0) {
|
||||
const res = await writer.writeBatch(parsedBatch);
|
||||
totalWritten += res.written;
|
||||
for (const f of res.files) filesSet.add(f);
|
||||
const unwritten = await excludeAlreadyPersisted(parsedBatch);
|
||||
if (unwritten.length > 0) {
|
||||
const res = await writer.writeBatch(unwritten);
|
||||
totalWritten += res.written;
|
||||
for (const f of res.files) filesSet.add(f);
|
||||
}
|
||||
}
|
||||
|
||||
if (Date.now() - lastRenewAt >= renewIntervalMs) {
|
||||
@@ -1022,9 +1097,12 @@ async function flushBuffer(options = {}) {
|
||||
|
||||
if (validBatch.length > 0) {
|
||||
try {
|
||||
const res = await writer.writeBatch(validBatch);
|
||||
totalWritten += res.written;
|
||||
for (const f of res.files) filesSet.add(f);
|
||||
const unwritten = await excludeAlreadyPersisted(validBatch);
|
||||
if (unwritten.length > 0) {
|
||||
const res = await writer.writeBatch(unwritten);
|
||||
totalWritten += res.written;
|
||||
for (const f of res.files) filesSet.add(f);
|
||||
}
|
||||
} catch (err) {
|
||||
bufferQueue.unshift(...validBatch);
|
||||
throw err;
|
||||
@@ -1917,8 +1995,14 @@ const socketHandlersApi = setupSocketHandlers(io, bufferQueue, writer, {
|
||||
return;
|
||||
}
|
||||
|
||||
if (bufferQueue.length >= runtimeConfig.batchFlushThreshold) {
|
||||
void flushBuffer().catch(() => undefined);
|
||||
// Redis is optional. Without it, a positive Socket.IO ACK requires a
|
||||
// completed CSV write, not merely an event sitting in volatile RAM.
|
||||
// Keep existing RAM retry state if the disk write fails.
|
||||
if (bufferQueue.length > 0) {
|
||||
const saved = await flushBuffer();
|
||||
if (saved.lockTimedOut || bufferQueue.length > 0) {
|
||||
throw new Error('BUFFER_PERSIST_FAILED: Event not durably queued');
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
+158
-9
@@ -478,6 +478,84 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
return hasNonEnvelopeKey ? stripped : {};
|
||||
}
|
||||
|
||||
// P02 R-01: an idempotency claim is created before persistence. After a
|
||||
// crash that claim may survive without its event. Prove the event reached
|
||||
// Redis's buffer or a CSV partition before issuing a duplicate-success ACK.
|
||||
async function hasDurableEvent(clientId, eventId, timestamp) {
|
||||
const ackKey = `\u0000durably-acked:${clientId}:${eventId}`;
|
||||
const previousAck = idempotencyMap.get(ackKey);
|
||||
if (typeof previousAck === 'number' && Date.now() - previousAck < IDEMPOTENCY_TTL_MS) {
|
||||
return true;
|
||||
}
|
||||
const redis = getRedisClient();
|
||||
if (redis && typeof redis.lrange === 'function') {
|
||||
try {
|
||||
// Bounded read: reject uncertain old claims instead of loading a huge Redis queue.
|
||||
const queued = await redis.lrange('datastack:buffer:events', -512, -1);
|
||||
if (Array.isArray(queued) && queued.some((raw) => {
|
||||
try {
|
||||
const evt = JSON.parse(raw);
|
||||
return evt && evt.clientId === clientId && evt.eventId === eventId;
|
||||
} catch { return false; }
|
||||
})) {
|
||||
idempotencyMap.set(ackKey, Date.now());
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// Redis cannot prove durability; fall through to read-only CSV proof.
|
||||
}
|
||||
}
|
||||
if (!worker || typeof worker.sanitizeClientId !== 'function' ||
|
||||
typeof worker.extractSafePartitionDate !== 'function' ||
|
||||
typeof worker.isPartitionFilename !== 'function' ||
|
||||
typeof worker.extractDateFromFilename !== 'function') return false;
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const { Writable } = require('node:stream');
|
||||
const { parse } = require('csv-parse');
|
||||
const zlib = require('node:zlib');
|
||||
const aborter = new AbortController();
|
||||
const deadline = setTimeout(() => aborter.abort(), 1800);
|
||||
deadline.unref?.();
|
||||
try {
|
||||
const base = await fs.promises.realpath(worker.baseDir);
|
||||
const directory = path.resolve(base, worker.sanitizeClientId(clientId));
|
||||
const realDir = await fs.promises.realpath(directory);
|
||||
if (!realDir.startsWith(base + path.sep)) return false;
|
||||
const date = worker.extractSafePartitionDate(timestamp);
|
||||
const files = await fs.promises.readdir(realDir, { withFileTypes: true });
|
||||
let scannedBytes = 0;
|
||||
for (const item of files) {
|
||||
if (!item.isFile() || !worker.isPartitionFilename(item.name) ||
|
||||
worker.extractDateFromFilename(item.name) !== date) continue;
|
||||
const filename = path.join(realDir, item.name);
|
||||
scannedBytes += (await fs.promises.stat(filename)).size;
|
||||
if (scannedBytes > 256 * 1024 * 1024) return false;
|
||||
let found = false;
|
||||
const stages = [fs.createReadStream(filename)];
|
||||
if (item.name.endsWith('.gz')) stages.push(zlib.createGunzip());
|
||||
stages.push(parse({ columns: true, bom: true, skip_empty_lines: true }));
|
||||
stages.push(new Writable({
|
||||
objectMode: true,
|
||||
write(row, _encoding, done) {
|
||||
if (row.clientId === clientId && row.eventId === eventId) found = true;
|
||||
done();
|
||||
},
|
||||
}));
|
||||
await pipeline(...stages, { signal: aborter.signal });
|
||||
if (found) {
|
||||
idempotencyMap.set(ackKey, Date.now());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Missing, corrupt, unreadable or slow CSV cannot justify positive ACK.
|
||||
} finally {
|
||||
clearTimeout(deadline);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
io.on("connection", (socket) => {
|
||||
const clientId = socket.data.clientId;
|
||||
socket.join(`client:${clientId}`);
|
||||
@@ -549,6 +627,8 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
: new Date().toISOString();
|
||||
const eventData = extractSingleEventData(payload);
|
||||
|
||||
// A previous Redis write failure can leave an uncommitted idempotency
|
||||
// claim. Never report that claim as a successful durable duplicate.
|
||||
const check = await validateSingleEventAsync(
|
||||
clientId,
|
||||
eventId,
|
||||
@@ -557,8 +637,17 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
);
|
||||
if (!check.allowed) {
|
||||
if (check.duplicate) {
|
||||
if (callback) {
|
||||
callback({ success: true, eventId, note: "DUPLICATE_DROPPED" });
|
||||
if (await hasDurableEvent(clientId, eventId, timestamp)) {
|
||||
idempotencyMap.delete(`\u0000failed-persist:${clientId}:${eventId}`);
|
||||
if (callback) callback({ success: true, eventId, note: "DUPLICATE_DROPPED" });
|
||||
} else {
|
||||
// A stale local claim must not block a valid same-ID SDK retry
|
||||
// after Redis recovers; the Redis claim still guards other workers.
|
||||
idempotencyMap.delete(`${clientId}:${eventId}`);
|
||||
if (callback) callback({
|
||||
success: false, eventId, code: "BUFFER_PERSIST_FAILED",
|
||||
error: "BUFFER_PERSIST_FAILED: Idempotency claim has no durable event",
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -585,6 +674,20 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
try {
|
||||
await onBufferPush();
|
||||
} catch (persistErr) {
|
||||
// Invalidate the pre-persistence idempotency claim so SDK retry can
|
||||
// resubmit after Redis recovers. Keep the volatile RAM event pending.
|
||||
const claimKey = `${clientId}:${eventId}`;
|
||||
idempotencyMap.delete(claimKey);
|
||||
idempotencyMap.set(`\u0000failed-persist:${claimKey}`, Date.now());
|
||||
const claimRedis = getRedisClient();
|
||||
if (claimRedis && typeof claimRedis.del === "function") {
|
||||
try {
|
||||
await claimRedis.del(`${REDIS_IDEMPOTENCY_PREFIX}${claimKey}`);
|
||||
idempotencyMap.delete(claimKey);
|
||||
} catch {
|
||||
// Claim may remain: negative ACK must be retained for retries.
|
||||
}
|
||||
}
|
||||
if (callback) {
|
||||
callback({
|
||||
success: false,
|
||||
@@ -599,6 +702,9 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear any failed local persistence marker only after a durable write.
|
||||
idempotencyMap.delete(`\u0000failed-persist:${clientId}:${eventId}`);
|
||||
idempotencyMap.set(`\u0000durably-acked:${clientId}:${eventId}`, Date.now());
|
||||
if (callback) callback({ success: true, eventId });
|
||||
} catch (err) {
|
||||
if (callback) callback({ success: false, error: err.message });
|
||||
@@ -689,6 +795,8 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
const rateLimitedEventIds = [];
|
||||
const oversizedEventIds = [];
|
||||
const errors = [];
|
||||
const acceptedEventIds = [];
|
||||
let volatileDuplicate = false;
|
||||
|
||||
for (const item of batch) {
|
||||
const safeItem = item && typeof item === "object" ? item : {};
|
||||
@@ -702,7 +810,7 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
: new Date().toISOString();
|
||||
const rawData = extractBatchItemData(safeItem);
|
||||
|
||||
const check = await validateSingleEventAsync(
|
||||
const check = await validateSingleEventAsync(
|
||||
clientId,
|
||||
eventId,
|
||||
rawData,
|
||||
@@ -710,7 +818,16 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
);
|
||||
if (!check.allowed) {
|
||||
if (check.duplicate) {
|
||||
duplicates += 1;
|
||||
if (await hasDurableEvent(clientId, eventId, timestamp)) {
|
||||
idempotencyMap.delete(`\u0000failed-persist:${clientId}:${eventId}`);
|
||||
duplicates += 1;
|
||||
} else {
|
||||
idempotencyMap.delete(`${clientId}:${eventId}`);
|
||||
rejected += 1;
|
||||
volatileDuplicate = true;
|
||||
if (errors.length < 5) errors.push(
|
||||
`${eventId}: BUFFER_PERSIST_FAILED: Idempotency claim has no durable event`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
rejected += 1;
|
||||
@@ -735,6 +852,7 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
payload: check.payloadStr,
|
||||
});
|
||||
processed += 1;
|
||||
acceptedEventIds.push(eventId);
|
||||
}
|
||||
|
||||
if (processed > 0) {
|
||||
@@ -742,6 +860,20 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
try {
|
||||
await onBufferPush();
|
||||
} catch (persistErr) {
|
||||
const claimRedis = getRedisClient();
|
||||
for (const eventId of acceptedEventIds) {
|
||||
const claimKey = `${clientId}:${eventId}`;
|
||||
idempotencyMap.delete(claimKey);
|
||||
idempotencyMap.set(`\u0000failed-persist:${claimKey}`, Date.now());
|
||||
if (claimRedis && typeof claimRedis.del === "function") {
|
||||
try {
|
||||
await claimRedis.del(`${REDIS_IDEMPOTENCY_PREFIX}${claimKey}`);
|
||||
idempotencyMap.delete(claimKey);
|
||||
} catch {
|
||||
// Preserve negative-ACK retry guard if claim removal fails.
|
||||
}
|
||||
}
|
||||
}
|
||||
if (callback) {
|
||||
callback({
|
||||
success: false,
|
||||
@@ -759,12 +891,29 @@ function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
for (const persistedId of acceptedEventIds) {
|
||||
idempotencyMap.delete(`\u0000failed-persist:${clientId}:${persistedId}`);
|
||||
idempotencyMap.set(`\u0000durably-acked:${clientId}:${persistedId}`, Date.now());
|
||||
}
|
||||
// Never ACK a mixed batch as successful while any event remains volatile.
|
||||
if (volatileDuplicate) {
|
||||
if (callback) callback({
|
||||
success: false, processed, rejected, duplicates,
|
||||
code: "BUFFER_PERSIST_FAILED",
|
||||
error: "BUFFER_PERSIST_FAILED: Batch contains non-durable event",
|
||||
errors,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (processed === 0 && duplicates === 0 && rejected > 0) {
|
||||
const code = hitPayloadLimit
|
||||
? "PAYLOAD_TOO_LARGE"
|
||||
: hitRateLimit
|
||||
? "RATE_LIMIT_EXCEEDED"
|
||||
: "BATCH_REJECTED";
|
||||
const code = volatileDuplicate
|
||||
? "BUFFER_PERSIST_FAILED"
|
||||
: hitPayloadLimit
|
||||
? "PAYLOAD_TOO_LARGE"
|
||||
: hitRateLimit
|
||||
? "RATE_LIMIT_EXCEEDED"
|
||||
: "BATCH_REJECTED";
|
||||
if (callback) {
|
||||
callback({
|
||||
success: false,
|
||||
|
||||
@@ -85,7 +85,7 @@ describe("Phase-01 Auth, Secrets, Revocation & Proxy Hardening", () => {
|
||||
});
|
||||
|
||||
it("BUG-01 & BUG-02: fails closed in production when secrets or DB/setup are missing", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
(process.env as Record<string, string | undefined>).NODE_ENV = "production";
|
||||
delete process.env.DATABASE_URL;
|
||||
delete process.env.DATASTACK_ADMIN_SESSION_SECRET;
|
||||
delete process.env.DATASTACK_ADMIN_SETUP_KEY;
|
||||
@@ -557,7 +557,7 @@ describe("Phase-01 Auth, Secrets, Revocation & Proxy Hardening", () => {
|
||||
});
|
||||
|
||||
it("FORENSIC BUG-01: blocks volatile RAM admin setup in production without DATABASE_URL and returns 409 SETUP_REQUIRED on pre-setup login", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
(process.env as Record<string, string | undefined>).NODE_ENV = "production";
|
||||
delete process.env.DATABASE_URL;
|
||||
delete process.env.DATASTACK_ADMIN_PASSWORD;
|
||||
process.env.DATASTACK_ADMIN_SESSION_SECRET =
|
||||
@@ -770,7 +770,7 @@ describe("Phase-01 Auth, Secrets, Revocation & Proxy Hardening", () => {
|
||||
|
||||
try {
|
||||
// 1. Production with empty jwtSecret must not persist empty jwt_secret row into PG
|
||||
process.env.NODE_ENV = "production";
|
||||
(process.env as Record<string, string | undefined>).NODE_ENV = "production";
|
||||
delete process.env.DATASTACK_JWT_SECRET;
|
||||
settingsGlobals.__dataStackAdminSettings = undefined;
|
||||
settingsGlobals.__dataStackSettingsHydrated = false;
|
||||
@@ -791,7 +791,7 @@ describe("Phase-01 Auth, Secrets, Revocation & Proxy Hardening", () => {
|
||||
);
|
||||
|
||||
// 2. Failing PG write must reject (not silently return 200) and must not mutate RAM
|
||||
process.env.NODE_ENV = "test";
|
||||
(process.env as Record<string, string | undefined>).NODE_ENV = "test";
|
||||
process.env.DATASTACK_JWT_SECRET =
|
||||
"valid-jwt-secret-at-least-32-characters-long";
|
||||
AuthService.setSecret(process.env.DATASTACK_JWT_SECRET);
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
interface IngestionServerModule {
|
||||
writer: { baseDir: string };
|
||||
server: import("node:http").Server;
|
||||
io: import("socket.io").Server;
|
||||
bufferQueue: Array<{ clientId: string; eventId: string; timestamp: string; payload: string }>;
|
||||
@@ -1220,3 +1221,232 @@ test("R2 PHASE-02 BUG-10: GET, PATCH (regenerate_token), and DELETE /api/clients
|
||||
SDKManager.deleteClientWithStatsAsync = origDeleteWithStats;
|
||||
}
|
||||
});
|
||||
|
||||
test("P02 R-01 remediation: Redis RPUSH failure rejects non-durable WS ACK", async () => {
|
||||
// Disposable test-only fixture: no production Redis, service, or storage state.
|
||||
const previousThreshold = serverMod.runtimeConfig.batchFlushThreshold;
|
||||
const previousRam = serverMod.bufferQueue.slice();
|
||||
const failingRedis = createSharedMockRedis();
|
||||
failingRedis.rpush = async () => {
|
||||
throw new Error("P02 injected Redis RPUSH outage");
|
||||
};
|
||||
serverMod.setRedisClientForTests(failingRedis);
|
||||
serverMod.runtimeConfig.batchFlushThreshold = 100_000;
|
||||
serverMod.bufferQueue.length = 0;
|
||||
let socket: Socket | undefined;
|
||||
try {
|
||||
const client = await SDKManager.registerClientAsync({
|
||||
clientId: "p02_redis_rpush_failure",
|
||||
name: "P02 Redis RPUSH Failure",
|
||||
rateLimit: 100,
|
||||
});
|
||||
socket = await connectSocket(client.token);
|
||||
const ack = await emitWithAck<{ success: boolean; eventId?: string; code?: string }>(
|
||||
socket, "sync_data",
|
||||
{ eventId: "p02-ack-before-crash-001", data: { value: 42 } },
|
||||
);
|
||||
const committedRows = await failingRedis.lrange("datastack:buffer:events", 0, -1);
|
||||
const volatileRows = serverMod.bufferQueue.filter((e) => e.eventId === "p02-ack-before-crash-001");
|
||||
assert.equal(ack.success, false, "P02 remediation must reject non-durable ACK");
|
||||
assert.equal(ack.code, "BUFFER_PERSIST_FAILED");
|
||||
const sameIdRetry = await emitWithAck<{ success: boolean; code?: string }>(
|
||||
socket, "sync_data",
|
||||
{ eventId: "p02-ack-before-crash-001", data: { value: 42 } },
|
||||
);
|
||||
assert.equal(sameIdRetry.success, false,
|
||||
"Pending idempotency claims must not return false positive duplicate ACK");
|
||||
assert.equal(sameIdRetry.code, "BUFFER_PERSIST_FAILED");
|
||||
const secondRetry = await emitWithAck<{ success: boolean; code?: string }>(
|
||||
socket, "sync_data",
|
||||
{ eventId: "p02-ack-before-crash-001", data: { value: 42 } },
|
||||
);
|
||||
assert.equal(secondRetry.success, false, "A repeated pending claim must remain negative");
|
||||
assert.equal(secondRetry.code, "BUFFER_PERSIST_FAILED");
|
||||
assert.equal(committedRows.length, 0, "Fake Redis has no durable event");
|
||||
assert.equal(volatileRows.length, 1, "Acknowledged event is RAM-only");
|
||||
// Crash model: restart loses RAM but fake Redis survives. No actual process is killed.
|
||||
serverMod.bufferQueue.length = 0;
|
||||
assert.equal((await failingRedis.lrange("datastack:buffer:events", 0, -1)).length, 0);
|
||||
// A new event may ACK only after Redis actually resumes persistence.
|
||||
const healthyRedis = createSharedMockRedis();
|
||||
serverMod.setRedisClientForTests(healthyRedis);
|
||||
const recovered = await emitWithAck<{ success: boolean; eventId?: string }>(
|
||||
socket, "sync_data",
|
||||
{ eventId: "p02-ack-recovered-002", data: { value: 43 } },
|
||||
);
|
||||
assert.equal(recovered.success, true);
|
||||
const recoveredSameId = await emitWithAck<{ success: boolean; code?: string }>(
|
||||
socket, "sync_data",
|
||||
{ eventId: "p02-ack-before-crash-001", data: { value: 42 } },
|
||||
);
|
||||
assert.equal(recoveredSameId.success, true, "Original eventId must be retryable after Redis recovery");
|
||||
assert.equal((await healthyRedis.lrange("datastack:buffer:events", 0, -1)).length, 2);
|
||||
} finally {
|
||||
socket?.disconnect();
|
||||
serverMod.setRedisClientForTests(undefined);
|
||||
serverMod.runtimeConfig.batchFlushThreshold = previousThreshold;
|
||||
serverMod.bufferQueue.splice(0, serverMod.bufferQueue.length, ...previousRam);
|
||||
}
|
||||
});
|
||||
|
||||
test("P02 R-03 diagnostic: Redis query failure leaves public ingestion health 200/online", async () => {
|
||||
const redis = createSharedMockRedis();
|
||||
redis.llen = async () => { throw new Error("P02 simulated Redis health outage"); };
|
||||
serverMod.setRedisClientForTests(redis);
|
||||
try {
|
||||
const res = await fetch(`${ingestionUrl}/health`);
|
||||
assert.equal(res.status, 200, "Legacy liveness status remains backwards-compatible");
|
||||
const body = await res.json() as { status: string; redisConnected: boolean; redisBufferSize: number };
|
||||
assert.equal(body.status, "online");
|
||||
assert.equal(body.redisConnected, false, "Redis failure is represented only in the payload");
|
||||
assert.equal(body.redisBufferSize, 0);
|
||||
const healthyRedis = createSharedMockRedis();
|
||||
serverMod.setRedisClientForTests(healthyRedis);
|
||||
const recovered = await fetch(`${ingestionUrl}/health`);
|
||||
const recoveredBody = await recovered.json() as { redisConnected: boolean };
|
||||
assert.equal(recovered.status, 200);
|
||||
assert.equal(recoveredBody.redisConnected, true);
|
||||
} finally {
|
||||
serverMod.setRedisClientForTests(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test("P02 R-01: batch_sync rejects non-durable Redis writes and pending duplicate claims", async () => {
|
||||
const previousThreshold = serverMod.runtimeConfig.batchFlushThreshold;
|
||||
const previousQueue = serverMod.bufferQueue.slice();
|
||||
const failingRedis = createSharedMockRedis();
|
||||
const recoveredRpush = failingRedis.rpush.bind(failingRedis);
|
||||
failingRedis.rpush = async () => { throw new Error("P02 injected batch Redis outage"); };
|
||||
serverMod.setRedisClientForTests(failingRedis);
|
||||
serverMod.runtimeConfig.batchFlushThreshold = 100_000;
|
||||
serverMod.bufferQueue.length = 0;
|
||||
let socket: Socket | undefined;
|
||||
const payload = [
|
||||
{ eventId: "p02-batch-volatile-1", data: { value: 1 } },
|
||||
{ eventId: "p02-batch-volatile-2", data: { value: 2 } },
|
||||
];
|
||||
try {
|
||||
const client = await SDKManager.registerClientAsync({
|
||||
clientId: "p02_redis_batch_failure",
|
||||
name: "P02 Redis Batch Failure",
|
||||
rateLimit: 100,
|
||||
});
|
||||
socket = await connectSocket(client.token);
|
||||
const ack = await emitWithAck<{ success: boolean; code?: string; processed?: number }>(
|
||||
socket, "batch_sync", payload,
|
||||
);
|
||||
assert.equal(ack.success, false);
|
||||
assert.equal(ack.code, "BUFFER_PERSIST_FAILED");
|
||||
assert.equal(ack.processed, 0);
|
||||
assert.equal((await failingRedis.lrange("datastack:buffer:events", 0, -1)).length, 0);
|
||||
const retry = await emitWithAck<{ success: boolean; code?: string }>(
|
||||
socket, "batch_sync", payload,
|
||||
);
|
||||
assert.equal(retry.success, false);
|
||||
assert.equal(retry.code, "BUFFER_PERSIST_FAILED");
|
||||
failingRedis.rpush = recoveredRpush;
|
||||
const mixed = await emitWithAck<{ success: boolean; code?: string; processed?: number }>(
|
||||
socket, "batch_sync", [payload[0], { eventId: "p02-batch-recovered-3", data: { value: 3 } }],
|
||||
);
|
||||
assert.equal(mixed.success, false, "A mixed recovered/volatile batch cannot ACK success");
|
||||
assert.equal(mixed.code, "BUFFER_PERSIST_FAILED");
|
||||
assert.equal(mixed.processed, 1, "New item is durably queued, old idempotency claim is uncertain");
|
||||
const confirmed = await emitWithAck<{ success: boolean; duplicates?: number }>(
|
||||
socket, "batch_sync", payload,
|
||||
);
|
||||
assert.equal(confirmed.success, true, "Once old events are persisted, duplicates are safely acknowledged");
|
||||
assert.equal(confirmed.duplicates, 2);
|
||||
} finally {
|
||||
socket?.disconnect();
|
||||
serverMod.setRedisClientForTests(undefined);
|
||||
serverMod.runtimeConfig.batchFlushThreshold = previousThreshold;
|
||||
serverMod.bufferQueue.splice(0, serverMod.bufferQueue.length, ...previousQueue);
|
||||
}
|
||||
});
|
||||
|
||||
test("P02 R-01: Redis-free Socket.IO ACK waits for CSV durability and denies disk errors", async () => {
|
||||
const fs = await import("node:fs");
|
||||
const os = await import("node:os");
|
||||
const path = await import("node:path");
|
||||
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "datastack-p02-ack-disk-"));
|
||||
const previousDir = serverMod.writer.baseDir;
|
||||
const previousThreshold = serverMod.runtimeConfig.batchFlushThreshold;
|
||||
const previousQueue = serverMod.bufferQueue.slice();
|
||||
serverMod.writer.baseDir = baseDir;
|
||||
serverMod.runtimeConfig.batchFlushThreshold = 100_000;
|
||||
serverMod.setRedisClientForTests(null);
|
||||
serverMod.bufferQueue.length = 0;
|
||||
let socket: Socket | undefined;
|
||||
try {
|
||||
const client = await SDKManager.registerClientAsync({
|
||||
clientId: "p02_disk_durability", name: "P02 Disk Durability", rateLimit: 100,
|
||||
});
|
||||
socket = await connectSocket(client.token);
|
||||
const accepted = await emitWithAck<{ success: boolean; code?: string }>(
|
||||
socket, "sync_data", { eventId: "p02-disk-ack-001", data: { value: 11 } },
|
||||
);
|
||||
assert.equal(accepted.success, true);
|
||||
const csvPath = path.join(baseDir, client.clientId, new Date().toISOString().slice(0, 10) + ".csv");
|
||||
assert.equal(fs.readFileSync(csvPath, "utf8").includes("p02-disk-ack-001"), true,
|
||||
"A successful ACK requires a completed CSV append when Redis is absent");
|
||||
const blockedBase = path.join(baseDir, "not-a-directory");
|
||||
fs.writeFileSync(blockedBase, "fixture");
|
||||
serverMod.writer.baseDir = blockedBase;
|
||||
const failed = await emitWithAck<{ success: boolean; code?: string }>(
|
||||
socket, "sync_data", { eventId: "p02-disk-ack-002", data: { value: 12 } },
|
||||
);
|
||||
assert.equal(failed.success, false, "CSV failure must never receive a positive ACK");
|
||||
assert.equal(failed.code, "BUFFER_PERSIST_FAILED");
|
||||
serverMod.writer.baseDir = baseDir;
|
||||
const retry = await emitWithAck<{ success: boolean; code?: string }>(
|
||||
socket, "sync_data", { eventId: "p02-disk-ack-002", data: { value: 12 } },
|
||||
);
|
||||
assert.equal(retry.success, true, "The same eventId must recover after disk restoration");
|
||||
const csv = fs.readFileSync(csvPath, "utf8");
|
||||
assert.equal(csv.split("p02-disk-ack-002").length - 1, 1);
|
||||
} finally {
|
||||
socket?.disconnect();
|
||||
serverMod.setRedisClientForTests(undefined);
|
||||
serverMod.writer.baseDir = previousDir;
|
||||
serverMod.runtimeConfig.batchFlushThreshold = previousThreshold;
|
||||
serverMod.bufferQueue.splice(0, serverMod.bufferQueue.length, ...previousQueue);
|
||||
fs.rmSync(baseDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("P02 R-01 diagnostic: HTTP fallback still ACKs RAM-only data after Redis outage (scope blocker)", async () => {
|
||||
// P02 remediation only authorizes Socket.IO ACK and buffer *flush* changes.
|
||||
// Record the separate Port 3000 write/ACK risk; do NOT alter HTTP runtime here.
|
||||
const redis = createSharedMockRedis();
|
||||
redis.rpush = async () => { throw new Error("P02 injected HTTP Redis RPUSH outage"); };
|
||||
const client = await SDKManager.registerClientAsync({
|
||||
clientId: "p02_http_redis_outage", name: "P02 HTTP Redis Outage", rateLimit: 100,
|
||||
});
|
||||
const eventId = "p02-http-ram-only-001";
|
||||
DataBufferEngine.getLocalBufferSnapshot(1);
|
||||
const state = (globalThis as unknown as {
|
||||
__dataStackBufferState?: { buffer: Array<{ eventId: string }>; batchFlushThreshold: number };
|
||||
}).__dataStackBufferState;
|
||||
const previousThreshold = state?.batchFlushThreshold;
|
||||
if (state) state.batchFlushThreshold = 100_000;
|
||||
DataBufferEngine.setRedisClientForTests(redis);
|
||||
try {
|
||||
const response = await postEventsRoute(new NextRequest("http://localhost:3000/api/events", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", authorization: `Bearer ${client.token}` },
|
||||
body: JSON.stringify({ eventId, data: { source: "p02-http-diagnostic" } }),
|
||||
}));
|
||||
const body = await response.json() as { success?: boolean; code?: string };
|
||||
assert.equal(response.status, 200, "Existing HTTP endpoint reports accepted despite failed Redis write");
|
||||
assert.equal(body.success, true);
|
||||
const queued = DataBufferEngine.getLocalBufferSnapshot(1000).filter((evt) => evt.eventId === eventId);
|
||||
assert.equal(queued.length, 1, "Accepted HTTP event is volatile RAM-only");
|
||||
assert.equal((await redis.lrange("datastack:buffer:events", 0, -1)).length, 0);
|
||||
// Simulated process-loss proof: dropping RAM removes the accepted event.
|
||||
if (state) state.buffer = state.buffer.filter((evt) => evt.eventId !== eventId);
|
||||
assert.equal(DataBufferEngine.getLocalBufferSnapshot(1000).some((evt) => evt.eventId === eventId), false);
|
||||
} finally {
|
||||
if (state && previousThreshold !== undefined) state.batchFlushThreshold = previousThreshold;
|
||||
DataBufferEngine.setRedisClientForTests(undefined);
|
||||
}
|
||||
});
|
||||
@@ -1085,10 +1085,10 @@ test("FORENSIC BUG-19: Deleting a client purges RAM, Redis, and Port 4000 buffer
|
||||
|
||||
test("FORENSIC BUG-20: Socket.IO sync_data and batch_sync ACKs wait until async Redis RPUSH completes", async () => {
|
||||
const fakeRedis = new FakeRedisClient();
|
||||
let rpushGateResolve: (() => void) | null = null;
|
||||
const rpushGateControl: { resolve?: () => void } = {};
|
||||
let rpushEnteredResolve: (() => void) | null = null;
|
||||
let rpushGate = new Promise<void>((resolve) => {
|
||||
rpushGateResolve = resolve;
|
||||
rpushGateControl.resolve = resolve;
|
||||
});
|
||||
let rpushEntered = new Promise<void>((resolve) => {
|
||||
rpushEnteredResolve = resolve;
|
||||
@@ -1155,14 +1155,14 @@ test("FORENSIC BUG-20: Socket.IO sync_data and batch_sync ACKs wait until async
|
||||
"sync_data ACK must NOT fire before Redis RPUSH finishes",
|
||||
);
|
||||
|
||||
rpushGateResolve?.();
|
||||
rpushGateControl.resolve?.();
|
||||
const syncAck = await syncAckPromise;
|
||||
assert.equal(syncAck.success, true);
|
||||
assert.equal(await fakeRedis.llen(REDIS_BUFFER_KEY), 1);
|
||||
|
||||
// 2. batch_sync must also wait for Redis RPUSH before ACK
|
||||
rpushGate = new Promise<void>((resolve) => {
|
||||
rpushGateResolve = resolve;
|
||||
rpushGateControl.resolve = resolve;
|
||||
});
|
||||
rpushEntered = new Promise<void>((resolve) => {
|
||||
rpushEnteredResolve = resolve;
|
||||
@@ -1199,7 +1199,7 @@ test("FORENSIC BUG-20: Socket.IO sync_data and batch_sync ACKs wait until async
|
||||
"batch_sync ACK must NOT fire before Redis RPUSH finishes",
|
||||
);
|
||||
|
||||
rpushGateResolve?.();
|
||||
rpushGateControl.resolve?.();
|
||||
const batchAck = await batchAckPromise;
|
||||
assert.equal(batchAck.success, true);
|
||||
assert.equal(batchAck.processed, 2);
|
||||
@@ -1549,3 +1549,101 @@ test("R2 PHASE-03 BUG-15: GET /api/export rejects inverted date range with 400 a
|
||||
assert.match(serverIndexSrc, /const filterClientId =\s*rawClientId && rawClientId !== 'all' \? normalizeClientId\(rawClientId\) : ''/);
|
||||
});
|
||||
|
||||
|
||||
test("P02 R-02 diagnostic: post-CSV Redis trim failure replays identical event on retry", async () => {
|
||||
const redis = new FakeRedisClient();
|
||||
const realTrim = redis.ltrim.bind(redis);
|
||||
let injected = false;
|
||||
redis.ltrim = async (key: string, start: number, stop: number): Promise<"OK"> => {
|
||||
if (key === REDIS_BUFFER_KEY && !injected) {
|
||||
injected = true;
|
||||
throw new Error("P02 simulated crash boundary after CSV append, before Redis trim");
|
||||
}
|
||||
return realTrim(key, start, stop);
|
||||
};
|
||||
const event: DataEvent = {
|
||||
clientId: "p02_csv_replay",
|
||||
eventId: "p02-replay-001",
|
||||
timestamp: "2026-11-22T01:00:00.000Z",
|
||||
payload: JSON.stringify({ marker: "p02" }),
|
||||
};
|
||||
DataBufferEngine.setRedisClientForTests(redis);
|
||||
const originalAppend = CSVStorageManager.appendBatch;
|
||||
const writtenIds: string[] = [];
|
||||
CSVStorageManager.appendBatch = async (events) => {
|
||||
const result = await originalAppend.call(CSVStorageManager, events);
|
||||
writtenIds.push(...events.map((row) => row.eventId));
|
||||
return result;
|
||||
};
|
||||
try {
|
||||
await DataBufferEngine.pushBatchAsync([event]);
|
||||
assert.equal(await redis.llen(REDIS_BUFFER_KEY), 1);
|
||||
await assert.rejects(() => DataBufferEngine.flush(), /P02 simulated crash boundary/);
|
||||
assert.equal(injected, true);
|
||||
assert.equal(writtenIds.filter((id) => id === event.eventId).length, 1);
|
||||
assert.equal(await redis.llen(REDIS_BUFFER_KEY), 1, "Redis still queues previously appended CSV event");
|
||||
await DataBufferEngine.flush();
|
||||
assert.equal(await redis.llen(REDIS_BUFFER_KEY), 0);
|
||||
assert.equal(writtenIds.filter((id) => id === event.eventId).length, 1,
|
||||
"Replay must detect the persisted CSV eventId before attempting another append");
|
||||
const csvPath = path.join(tmpStorageDir, event.clientId, "2026-11-22.csv");
|
||||
const csvContents = fs.readFileSync(csvPath, "utf8");
|
||||
assert.equal(csvContents.split(event.eventId).length - 1, 1,
|
||||
"Exactly one physical CSV row must exist after a failed LTRIM and retry");
|
||||
} finally {
|
||||
CSVStorageManager.appendBatch = originalAppend;
|
||||
DataBufferEngine.setRedisClientForTests(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test("P02 R-02: Port 4000 CSV worker suppresses a crash-window replay after Redis LTRIM error", async () => {
|
||||
const mockRedis = new FakeRedisClient();
|
||||
const originalTrim = mockRedis.ltrim.bind(mockRedis);
|
||||
let failedOnce = false;
|
||||
mockRedis.ltrim = async (key: string, start: number, stop: number): Promise<"OK"> => {
|
||||
if (key === REDIS_BUFFER_KEY && !failedOnce) {
|
||||
failedOnce = true;
|
||||
throw new Error("P02 Port4000 injected post-CSV trim failure");
|
||||
}
|
||||
return originalTrim(key, start, stop);
|
||||
};
|
||||
const ingestion = require("../server/index.js") as IngestionServerModule;
|
||||
const previousDir = ingestion.writer.baseDir;
|
||||
const previousQueue = ingestion.bufferQueue.slice();
|
||||
ingestion.writer.baseDir = tmpStorageDir;
|
||||
ingestion.bufferQueue.length = 0;
|
||||
ingestion.setRedisClientForTests(mockRedis);
|
||||
const evt: DataEvent = {
|
||||
clientId: "p02_ingestion_replay",
|
||||
eventId: "p02-port4000-001",
|
||||
timestamp: "2026-11-22T13:00:00.000Z",
|
||||
payload: JSON.stringify({ stage: "before-ltrim" }),
|
||||
};
|
||||
try {
|
||||
await mockRedis.rpush(REDIS_BUFFER_KEY, JSON.stringify(evt));
|
||||
await assert.rejects(
|
||||
() => ingestion.flushBuffer(),
|
||||
/P02 Port4000 injected post-CSV trim failure/,
|
||||
);
|
||||
assert.equal(failedOnce, true);
|
||||
assert.equal(await mockRedis.llen(REDIS_BUFFER_KEY), 1);
|
||||
const csvPath = path.join(tmpStorageDir, evt.clientId, "2026-11-22.csv");
|
||||
assert.equal(fs.readFileSync(csvPath, "utf8").split(evt.eventId).length - 1, 1);
|
||||
// Crash/restart may occur after daily part rotation and archive compression.
|
||||
// Verify replay detection against an actual rotated .csv.gz partition.
|
||||
const zlib = await import("node:zlib");
|
||||
const archivedPath = path.join(tmpStorageDir, evt.clientId, "2026-11-22-part2.csv.gz");
|
||||
fs.writeFileSync(archivedPath, zlib.gzipSync(fs.readFileSync(csvPath)));
|
||||
fs.unlinkSync(csvPath);
|
||||
const recovered = await ingestion.flushBuffer();
|
||||
assert.equal(recovered.written, 0, "Recovered compressed replay must not append again");
|
||||
assert.equal(await mockRedis.llen(REDIS_BUFFER_KEY), 0);
|
||||
assert.equal(fs.existsSync(csvPath), false, "No duplicate active CSV partition should be created");
|
||||
const archivedRows = zlib.gunzipSync(fs.readFileSync(archivedPath)).toString("utf8");
|
||||
assert.equal(archivedRows.split(evt.eventId).length - 1, 1);
|
||||
} finally {
|
||||
ingestion.writer.baseDir = previousDir;
|
||||
ingestion.bufferQueue.splice(0, ingestion.bufferQueue.length, ...previousQueue);
|
||||
ingestion.setRedisClientForTests(undefined);
|
||||
}
|
||||
});
|
||||
@@ -172,7 +172,7 @@ test("R3-Phase-01 [BUG-03]: Client SDK JWTs omit hardcoded 30d exp so Never-Expi
|
||||
test("R3-Phase-01 [BUG-04 & BUG-15]: Viewer blocked (403) on POST /api/events and Operator blocked (403) on POST /api/storage/s3-test", async () => {
|
||||
resetAdminStateForTests();
|
||||
await createInitialAdmin("r3-owner@datastack.dev", "OwnerPassword123!");
|
||||
const sessionSecret = getAdminSessionSecret();
|
||||
const sessionSecret = getAdminSessionSecret()!;
|
||||
const suffix = Date.now();
|
||||
const viewerEmail = `r3viewer_${suffix}@datastack.dev`;
|
||||
const operatorEmail = `r3operator_${suffix}@datastack.dev`;
|
||||
@@ -182,13 +182,11 @@ test("R3-Phase-01 [BUG-04 & BUG-15]: Viewer blocked (403) on POST /api/events an
|
||||
email: viewerEmail,
|
||||
password: "ViewerPassword123!",
|
||||
role: "viewer",
|
||||
displayName: "R3 Viewer",
|
||||
});
|
||||
const operator = await createAdminTeamMemberAsync({
|
||||
email: operatorEmail,
|
||||
password: "OperatorPassword123!",
|
||||
role: "operator",
|
||||
displayName: "R3 Operator",
|
||||
});
|
||||
await SDKManager.registerClientAsync({
|
||||
clientId,
|
||||
@@ -292,7 +290,7 @@ test("R3-Phase-01 [BUG-06]: Locked webhook secret does not break unrelated setti
|
||||
|
||||
const ownerToken = await createAdminSessionToken(
|
||||
owner.email,
|
||||
getAdminSessionSecret(),
|
||||
getAdminSessionSecret()!,
|
||||
Date.now() + 3600_000,
|
||||
owner.tokenVersion,
|
||||
owner.role,
|
||||
@@ -427,7 +425,7 @@ test("R3-Phase-01 [BUG-10]: Brute-force 429 admin login lockout dispatches ADMIN
|
||||
assert.equal(dispatchedBodies[0].instance, "DataStack");
|
||||
} finally {
|
||||
global.fetch = origFetch;
|
||||
await clearAdminLoginAttempts(email, getAdminSessionSecret(), testIp);
|
||||
await clearAdminLoginAttempts(email, getAdminSessionSecret()!, testIp);
|
||||
await SettingsManager.updateSettingsAsync({
|
||||
enableWebhookAlerts: false,
|
||||
webhookUrl: "",
|
||||
|
||||
@@ -40,7 +40,7 @@ function writeGzipCsv(filePath: string, content: string): void {
|
||||
|
||||
async function createOwnerCookie(): Promise<string> {
|
||||
delete process.env.DATABASE_URL;
|
||||
const sessionSecret = getAdminSessionSecret();
|
||||
const sessionSecret = getAdminSessionSecret()!;
|
||||
resetAdminStateForTests();
|
||||
const ownerEmail = "owner-r3p2@datastack.local";
|
||||
await createInitialAdmin(ownerEmail, "StrongPassword123!");
|
||||
|
||||
@@ -5,6 +5,7 @@ import test from "node:test";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET as prometheusGet } from "../app/api/prometheus/route";
|
||||
import { SettingsManager } from "../core/adminSettings/settingsManager";
|
||||
import { DataBufferEngine } from "../core/data/buffer";
|
||||
import { ApiEngine } from "../core/apiEngine/apiService";
|
||||
import {
|
||||
createAdminSessionToken,
|
||||
@@ -24,6 +25,11 @@ import {
|
||||
summarizeUiClientCounts,
|
||||
} from "../lib/vconUiHelpers";
|
||||
|
||||
test.after(async () => {
|
||||
SDKManager.stopActivityFlushTimerForTests();
|
||||
await DataBufferEngine.shutdown();
|
||||
});
|
||||
|
||||
async function makeOwnerCookie(): Promise<string> {
|
||||
resetAdminStateForTests();
|
||||
await createInitialAdmin("r3-p4-owner@datastack.dev", "R3Phase04Pass!");
|
||||
|
||||
@@ -96,7 +96,7 @@ function restoreEnv(): void {
|
||||
async function createOwnerCookie(email = "r4p1-owner@datastack.dev"): Promise<string> {
|
||||
resetAdminStateForTests();
|
||||
await createInitialAdmin(email, "OwnerPassword123!");
|
||||
const secret = getAdminSessionSecret();
|
||||
const secret = getAdminSessionSecret()!;
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
secret,
|
||||
@@ -531,7 +531,7 @@ test("R4-Phase-01 [AUDIT-09 / ERR-R4-04 & ERR-R4-05]: Fail-loud audit DB degrade
|
||||
assert.equal(unauthSync.status, 401);
|
||||
|
||||
// Owner session v1 works before logout/revocation
|
||||
const secret = getAdminSessionSecret();
|
||||
const secret = getAdminSessionSecret()!;
|
||||
const ownerTokenV1 = await createAdminSessionToken(
|
||||
"r4-audit-owner@datastack.dev",
|
||||
secret,
|
||||
|
||||
@@ -5,6 +5,7 @@ import fsp from "node:fs/promises";
|
||||
import http from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import type { Request, Response } from "express";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
@@ -81,7 +82,7 @@ async function createOwnerCookie(
|
||||
): Promise<string> {
|
||||
resetAdminStateForTests();
|
||||
await createInitialAdmin(email, "OwnerPassword123!");
|
||||
const secret = getAdminSessionSecret();
|
||||
const secret = getAdminSessionSecret()!;
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
secret,
|
||||
@@ -329,13 +330,13 @@ test("R4-Phase-02 AUDIT-06: Governance audit logging for /api/export, Files Mana
|
||||
getDbPool: () => null,
|
||||
}),
|
||||
);
|
||||
ramApp.put("/vcon/files-engine/api/v1/fs/sample.csv", (_req: express.Request, res: express.Response) => {
|
||||
ramApp.put("/vcon/files-engine/api/v1/fs/sample.csv", (_req: Request, res: Response) => {
|
||||
res.status(200).json({ ok: true });
|
||||
});
|
||||
ramApp.put("/vcon/files-engine/api/v1/rename", (_req: express.Request, res: express.Response) => {
|
||||
ramApp.put("/vcon/files-engine/api/v1/rename", (_req: Request, res: Response) => {
|
||||
res.status(200).json({ ok: true });
|
||||
});
|
||||
ramApp.delete("/vcon/files-engine/api/v1/fs/sample.csv", (_req: express.Request, res: express.Response) => {
|
||||
ramApp.delete("/vcon/files-engine/api/v1/fs/sample.csv", (_req: Request, res: Response) => {
|
||||
res.status(403).json({ ok: false }); // non-2xx should NOT emit mutation audit
|
||||
});
|
||||
|
||||
@@ -404,7 +405,7 @@ test("R4-Phase-02 AUDIT-06: Governance audit logging for /api/export, Files Mana
|
||||
getDbPool: () => mockDbPool,
|
||||
}),
|
||||
);
|
||||
pgApp.delete("/vcon/files-engine/api/v1/fs/obsolete.csv", (_req: express.Request, res: express.Response) => {
|
||||
pgApp.delete("/vcon/files-engine/api/v1/fs/obsolete.csv", (_req: Request, res: Response) => {
|
||||
res.status(200).json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -775,3 +776,60 @@ test("R4-Phase-02 AUDIT-12 / ERR-R4-08: Streaming S3 upload & streaming .csv.gz
|
||||
assert.equal(fs.existsSync(tmpDir), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("P02 R-01: stale pre-persistence Redis claim after restart never yields a false duplicate ACK", async () => {
|
||||
// A fresh Socket.IO handler has no in-process ACK cache, but Redis retained
|
||||
// the idempotency claim from a hypothetical crash before Redis RPUSH.
|
||||
const client = await SDKManager.registerClientAsync({
|
||||
clientId: "p02_stale_claim", name: "P02 Stale Claim", rateLimit: 200,
|
||||
});
|
||||
const eventId = "p02-not-yet-persisted-001";
|
||||
const stored = [] as string[];
|
||||
const redis = {
|
||||
status: "ready",
|
||||
async get(key: string) {
|
||||
return key === `datastack:idem:${client.clientId}:${eventId}` ? "1" : null;
|
||||
},
|
||||
async set() { return null; },
|
||||
async incr() { return 1; },
|
||||
async pexpire() { return 1; },
|
||||
async lrange() { return stored; },
|
||||
};
|
||||
const httpServer = http.createServer();
|
||||
const io = new Server(httpServer);
|
||||
setupSocketHandlers(io, [], null, {
|
||||
getRuntimeConfig: () => ({
|
||||
jwtSecret: "datastack-jwt-default-secret-key-32-chars-long",
|
||||
maxEventsPerSec: 200, maxPayloadSizeBytes: 100 * 1024, enableIdempotency: true,
|
||||
}),
|
||||
verifyClientInDb: async () => ({ allowed: true, rateLimit: 200 }),
|
||||
getRedisClient: () => redis,
|
||||
onBufferPush: async () => undefined,
|
||||
});
|
||||
let socket: ReturnType<typeof ioClient> | null = null;
|
||||
try {
|
||||
await new Promise<void>((resolve) => httpServer.listen(0, "127.0.0.1", resolve));
|
||||
const port = (httpServer.address() as AddressInfo).port;
|
||||
socket = ioClient(`http://127.0.0.1:${port}`, { auth: { token: client.token }, transports: ["websocket"] });
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket!.once("connect", resolve);
|
||||
socket!.once("connect_error", reject);
|
||||
});
|
||||
const sendDuplicate = () => new Promise<{ success: boolean; code?: string; note?: string }>((resolve, reject) => {
|
||||
socket!.timeout(3000).emit("sync_data", { eventId, data: { seq: 1 } },
|
||||
(err: Error | null, ack: { success: boolean; code?: string; note?: string }) => {
|
||||
if (err) reject(err); else resolve(ack);
|
||||
});
|
||||
});
|
||||
const uncertain = await sendDuplicate();
|
||||
assert.equal(uncertain.success, false, "Redis idempotency claim alone is not a persistence proof");
|
||||
assert.equal(uncertain.code, "BUFFER_PERSIST_FAILED");
|
||||
stored.push(JSON.stringify({ clientId: client.clientId, eventId }));
|
||||
const durable = await sendDuplicate();
|
||||
assert.equal(durable.success, true, "Same claim is a valid duplicate only after its event is durable");
|
||||
assert.equal(durable.note, "DUPLICATE_DROPPED");
|
||||
} finally {
|
||||
socket?.disconnect();
|
||||
await new Promise<void>((resolve) => io.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, it } from 'node:test';
|
||||
import { after, afterEach, beforeEach, describe, it } from 'node:test';
|
||||
import { NextRequest } from 'next/server';
|
||||
import { POST as setupPost } from '../app/api/auth/setup/route';
|
||||
import { GET as filesStatusGet } from '../app/api/files/status/route';
|
||||
@@ -13,9 +13,14 @@ import {
|
||||
getAdminSessionSecret,
|
||||
} from '../core/auth/adminSession';
|
||||
import { resetAdminStateForTests } from '../core/auth/adminUsers';
|
||||
import { DataBufferEngine } from '../core/data/buffer';
|
||||
import { middleware } from '../middleware';
|
||||
import { DataStack, DiskSpooler } from '../sdk/node/datastack';
|
||||
|
||||
after(async () => {
|
||||
await DataBufferEngine.shutdown();
|
||||
});
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
|
||||
@@ -35,6 +35,7 @@ import { SDKManager } from "../core/sdk/sdkManager";
|
||||
import { getInternalIngestionHeaders } from "../core/Security/security";
|
||||
import { SSRFBlockedError } from "../core/Security/ssrfGuard";
|
||||
import { CSVStorageManager } from "../core/Storage/csvStorage";
|
||||
import { DataBufferEngine } from "../core/data/buffer";
|
||||
import { middleware } from "../middleware";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
@@ -78,8 +79,15 @@ const cjsRuntimeLogCapture = require("../server/runtimeLogCapture.js") as {
|
||||
const ingestionServer = require("../server/index.js") as {
|
||||
setDbPoolForTests: (pool: unknown) => void;
|
||||
syncSettingsFromDatabase: () => Promise<boolean>;
|
||||
stopTimers: () => void;
|
||||
};
|
||||
|
||||
test.after(async () => {
|
||||
ingestionServer.stopTimers();
|
||||
SDKManager.stopActivityFlushTimerForTests();
|
||||
await DataBufferEngine.shutdown();
|
||||
});
|
||||
|
||||
test("R5-Phase-01 [MCP-AUDIT-02 / ERR-R5-02]: Runtime log capture scrubs secrets, rotates at 2MB, filters/tails safely, and handles missing dirs gracefully", async () => {
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "datastack-r5-logs-"));
|
||||
const logsDir = path.join(tmpDir, ".runtime-logs");
|
||||
|
||||
@@ -507,7 +507,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.equal(deniedClientCreate.isError, true);
|
||||
const deniedPayload = JSON.parse(
|
||||
(deniedClientCreate.content[0] as { text: string }).text,
|
||||
((deniedClientCreate.content as Array<{ text: string }>)[0]).text,
|
||||
) as { code: string; permission: string };
|
||||
assert.equal(deniedPayload.code, "MCP_PERMISSION_DENIED");
|
||||
assert.equal(deniedPayload.permission, "clients_create");
|
||||
@@ -521,7 +521,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.notEqual(createdToolRes.isError, true);
|
||||
const createdPayload = JSON.parse(
|
||||
(createdToolRes.content[0] as { text: string }).text,
|
||||
((createdToolRes.content as Array<{ text: string }>)[0]).text,
|
||||
) as { success: boolean; client: { clientId: string; rateLimit: number; token?: string } };
|
||||
assert.equal(createdPayload.success, true);
|
||||
assert.equal(createdPayload.client.clientId, testClientId);
|
||||
@@ -535,7 +535,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.equal(traversalRes.isError, true);
|
||||
assert.equal(
|
||||
(JSON.parse((traversalRes.content[0] as { text: string }).text) as { code: string }).code,
|
||||
(JSON.parse(((traversalRes.content as Array<{ text: string }>)[0]).text) as { code: string }).code,
|
||||
"PATH_OUTSIDE_ROOT",
|
||||
);
|
||||
|
||||
@@ -546,7 +546,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.equal(symlinkRes.isError, true);
|
||||
assert.equal(
|
||||
(JSON.parse((symlinkRes.content[0] as { text: string }).text) as { code: string }).code,
|
||||
(JSON.parse(((symlinkRes.content as Array<{ text: string }>)[0]).text) as { code: string }).code,
|
||||
"SYMLINK_FORBIDDEN",
|
||||
);
|
||||
}
|
||||
@@ -557,7 +557,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.equal(lockReadRes.isError, true);
|
||||
assert.equal(
|
||||
(JSON.parse((lockReadRes.content[0] as { text: string }).text) as { code: string }).code,
|
||||
(JSON.parse(((lockReadRes.content as Array<{ text: string }>)[0]).text) as { code: string }).code,
|
||||
"LOCKFILE_PROTECTED",
|
||||
);
|
||||
|
||||
@@ -567,7 +567,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.equal(lockedFileUploadRes.isError, true);
|
||||
assert.equal(
|
||||
(JSON.parse((lockedFileUploadRes.content[0] as { text: string }).text) as { code: string })
|
||||
(JSON.parse(((lockedFileUploadRes.content as Array<{ text: string }>)[0]).text) as { code: string })
|
||||
.code,
|
||||
"LOCKFILE_PROTECTED",
|
||||
);
|
||||
@@ -578,7 +578,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.equal(logWriteRes.isError, true);
|
||||
assert.equal(
|
||||
(JSON.parse((logWriteRes.content[0] as { text: string }).text) as { code: string }).code,
|
||||
(JSON.parse(((logWriteRes.content as Array<{ text: string }>)[0]).text) as { code: string }).code,
|
||||
"PROTECTED_LOG_DIR",
|
||||
);
|
||||
|
||||
@@ -601,7 +601,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.notEqual(dlRes.isError, true);
|
||||
assert.equal(
|
||||
(JSON.parse((dlRes.content[0] as { text: string }).text) as { content: string }).content,
|
||||
(JSON.parse(((dlRes.content as Array<{ text: string }>)[0]).text) as { content: string }).content,
|
||||
"alpha gamma",
|
||||
);
|
||||
|
||||
@@ -610,7 +610,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
arguments: { path: "data" },
|
||||
});
|
||||
assert.notEqual(listRes.isError, true);
|
||||
const listParsed = JSON.parse((listRes.content[0] as { text: string }).text) as {
|
||||
const listParsed = JSON.parse(((listRes.content as Array<{ text: string }>)[0]).text) as {
|
||||
entries: Array<{ name: string }>;
|
||||
};
|
||||
assert.ok(listParsed.entries.some((e) => e.name === "active.csv"));
|
||||
@@ -632,7 +632,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.notEqual(metricsRes.isError, true);
|
||||
assert.equal(
|
||||
(JSON.parse((metricsRes.content[0] as { text: string }).text) as { success: boolean }).success,
|
||||
(JSON.parse(((metricsRes.content as Array<{ text: string }>)[0]).text) as { success: boolean }).success,
|
||||
true,
|
||||
);
|
||||
|
||||
@@ -641,7 +641,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
arguments: { action: "flush" },
|
||||
});
|
||||
assert.notEqual(flushRes.isError, true);
|
||||
const flushPayload = JSON.parse((flushRes.content[0] as { text: string }).text) as {
|
||||
const flushPayload = JSON.parse(((flushRes.content as Array<{ text: string }>)[0]).text) as {
|
||||
success: boolean;
|
||||
ingestionFlushed: number;
|
||||
};
|
||||
@@ -654,7 +654,7 @@ test("R5-Phase-02 [MCP-AUDIT-01/06/07 & ERR-R5-03/04/05/06]: Port 4000 MCP serve
|
||||
});
|
||||
assert.equal(coolifySsrfRes.isError, true);
|
||||
assert.equal(
|
||||
(JSON.parse((coolifySsrfRes.content[0] as { text: string }).text) as { code: string }).code,
|
||||
(JSON.parse(((coolifySsrfRes.content as Array<{ text: string }>)[0]).text) as { code: string }).code,
|
||||
"SSRF_BLOCKED_HOST",
|
||||
);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import path from "node:path";
|
||||
import test from "node:test";
|
||||
|
||||
import { MCP_PERMISSION_DEFINITIONS } from "../core/mcp/mcpSettings";
|
||||
import { DataBufferEngine } from "../core/data/buffer";
|
||||
import {
|
||||
applyCategoryPermissionToggle,
|
||||
applyMcpPermissionPreset,
|
||||
@@ -23,6 +24,10 @@ import {
|
||||
|
||||
const DEFINITIONS = MCP_PERMISSION_DEFINITIONS as readonly McpPermissionDefinitionView[];
|
||||
|
||||
test.after(async () => {
|
||||
await DataBufferEngine.shutdown();
|
||||
});
|
||||
|
||||
test("R5-Phase-03 [lib/mcpUiHelpers.ts]: URL builder, AI client JSON snippets, permission grouping/presets, bridge status, and diff payload", () => {
|
||||
// 1. Endpoint URL builder
|
||||
assert.equal(
|
||||
|
||||
@@ -43,6 +43,8 @@ import {
|
||||
uploadFileToS3,
|
||||
} from "../core/Storage/s3Archive";
|
||||
import {
|
||||
classifyUiClientStatus,
|
||||
summarizeUiClientCounts,
|
||||
DEFAULT_EDITABLE_SETTINGS,
|
||||
settingsToNumericDrafts,
|
||||
validateEditableSettingsDraft,
|
||||
@@ -759,7 +761,7 @@ test("V2-Audit-Phase-03 [BUG-V2-AUDIT-01, BUG-V2-AUDIT-07, BUG-V2-AUDIT-10]: Dis
|
||||
bsize: 4096,
|
||||
}));
|
||||
|
||||
const snapshot = await CSVStorageManager.getDiskUsageAsync(true);
|
||||
const snapshot = await CSVStorageManager.getDiskUsageAsync();
|
||||
assert.equal(snapshot.available, true);
|
||||
assert.equal(snapshot.usedPct, 25);
|
||||
assert.equal(snapshot.totalBytes, 2000 * 4096);
|
||||
@@ -780,29 +782,30 @@ test("V2-Audit-Phase-03 [BUG-V2-AUDIT-01, BUG-V2-AUDIT-07, BUG-V2-AUDIT-10]: Dis
|
||||
CSVStorageManager.setStatfsOverrideForTests(async () => {
|
||||
throw new Error("Simulated statfs failure");
|
||||
});
|
||||
const fallbackSnapshot = await CSVStorageManager.getDiskUsageAsync(true);
|
||||
const fallbackSnapshot = await CSVStorageManager.getDiskUsageAsync();
|
||||
assert.equal(fallbackSnapshot.available, false);
|
||||
assert.equal(fallbackSnapshot.freeBytes, 0);
|
||||
assert.equal(fallbackSnapshot.availableBytes, 0);
|
||||
|
||||
// 2. BUG-V2-AUDIT-07: app/vcon/clients/page.tsx defines isClientExpired and excludes expired tokens from onlineCount, pendingCount, and online/pending filter tabs
|
||||
// 2. BUG-V2-AUDIT-07: shared status classifier excludes expired clients from active counters.
|
||||
const clientsPageSrc = await fs.readFile(
|
||||
path.join(process.cwd(), "app/vcon/clients/page.tsx"),
|
||||
"utf8",
|
||||
);
|
||||
assert.match(clientsPageSrc, /function isClientExpired\(/);
|
||||
assert.match(
|
||||
clientsPageSrc,
|
||||
/const expired = !revoked && isClientExpired\(client\.expiresAt,\s*now\)/,
|
||||
);
|
||||
assert.match(
|
||||
clientsPageSrc,
|
||||
/!isClientExpired\(client\.expiresAt,\s*now\)/,
|
||||
);
|
||||
assert.match(
|
||||
clientsPageSrc,
|
||||
/const pending =\s*client\.status === 'active' && !expired && !client\.lastActive/,
|
||||
);
|
||||
assert.match(clientsPageSrc, /summarizeUiClientCounts\(clients, now\)/);
|
||||
assert.match(clientsPageSrc, /classifyUiClientStatus\(client, now\)/);
|
||||
const now = Date.parse("2026-11-21T10:00:00.000Z");
|
||||
const expiredClient = { status: "active" as const, expiresAt: "2020-01-01T00:00:00.000Z", lastActive: "2026-11-21T09:59:50.000Z" };
|
||||
const pendingClient = { status: "active" as const, expiresAt: null, lastActive: undefined };
|
||||
const onlineClient = { status: "active" as const, expiresAt: null, lastActive: "2026-11-21T09:59:50.000Z" };
|
||||
assert.equal(classifyUiClientStatus(expiredClient, now), "expired");
|
||||
assert.equal(classifyUiClientStatus(pendingClient, now), "pending");
|
||||
assert.equal(classifyUiClientStatus(onlineClient, now), "online");
|
||||
const summary = summarizeUiClientCounts([expiredClient, pendingClient, onlineClient], now);
|
||||
assert.equal(summary.expired, 1);
|
||||
assert.equal(summary.online, 1);
|
||||
assert.equal(summary.pending, 1);
|
||||
assert.equal(summary.active, 2);
|
||||
|
||||
// 3. BUG-V2-AUDIT-10: ExportWorkspace.tsx and app/vcon/storage/page.tsx render CSV.GZ badge for compressed .csv.gz partitions
|
||||
const exportWorkspaceSrc = await fs.readFile(
|
||||
|
||||
@@ -331,7 +331,7 @@ test("V2-Phase-02 [HTTP & Socket Ingestion Security]: Per-client IP allowlist (4
|
||||
token: string,
|
||||
bypassCache?: boolean,
|
||||
clientIp?: string,
|
||||
) => Promise<{ ok: boolean; reason?: string }>;
|
||||
) => Promise<{ allowed: boolean; code?: string; reason?: string }>;
|
||||
setDbPoolForTests: (pool: unknown) => void;
|
||||
stopTimers: () => void;
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user