Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b83a50b11b | ||
|
|
bbe73d9166 | ||
|
|
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'
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# 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.
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# 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.
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# 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.
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# 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.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# 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.
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
# 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.
|
||||||
Generated
+1016
File diff suppressed because it is too large.
Load diff
@@ -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 () => {
|
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.DATABASE_URL;
|
||||||
delete process.env.DATASTACK_ADMIN_SESSION_SECRET;
|
delete process.env.DATASTACK_ADMIN_SESSION_SECRET;
|
||||||
delete process.env.DATASTACK_ADMIN_SETUP_KEY;
|
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 () => {
|
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.DATABASE_URL;
|
||||||
delete process.env.DATASTACK_ADMIN_PASSWORD;
|
delete process.env.DATASTACK_ADMIN_PASSWORD;
|
||||||
process.env.DATASTACK_ADMIN_SESSION_SECRET =
|
process.env.DATASTACK_ADMIN_SESSION_SECRET =
|
||||||
@@ -770,7 +770,7 @@ describe("Phase-01 Auth, Secrets, Revocation & Proxy Hardening", () => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. Production with empty jwtSecret must not persist empty jwt_secret row into PG
|
// 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;
|
delete process.env.DATASTACK_JWT_SECRET;
|
||||||
settingsGlobals.__dataStackAdminSettings = undefined;
|
settingsGlobals.__dataStackAdminSettings = undefined;
|
||||||
settingsGlobals.__dataStackSettingsHydrated = false;
|
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
|
// 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 =
|
process.env.DATASTACK_JWT_SECRET =
|
||||||
"valid-jwt-secret-at-least-32-characters-long";
|
"valid-jwt-secret-at-least-32-characters-long";
|
||||||
AuthService.setSecret(process.env.DATASTACK_JWT_SECRET);
|
AuthService.setSecret(process.env.DATASTACK_JWT_SECRET);
|
||||||
|
|||||||
@@ -1220,3 +1220,64 @@ test("R2 PHASE-02 BUG-10: GET, PATCH (regenerate_token), and DELETE /api/clients
|
|||||||
SDKManager.deleteClientWithStatsAsync = origDeleteWithStats;
|
SDKManager.deleteClientWithStatsAsync = origDeleteWithStats;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("P02 R-01 diagnostic: Redis RPUSH failure yields positive WS ACK for volatile RAM-only event", 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, true, "Existing handler currently sends a positive ACK after Redis failure");
|
||||||
|
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);
|
||||||
|
} 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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 () => {
|
test("FORENSIC BUG-20: Socket.IO sync_data and batch_sync ACKs wait until async Redis RPUSH completes", async () => {
|
||||||
const fakeRedis = new FakeRedisClient();
|
const fakeRedis = new FakeRedisClient();
|
||||||
let rpushGateResolve: (() => void) | null = null;
|
const rpushGateControl: { resolve?: () => void } = {};
|
||||||
let rpushEnteredResolve: (() => void) | null = null;
|
let rpushEnteredResolve: (() => void) | null = null;
|
||||||
let rpushGate = new Promise<void>((resolve) => {
|
let rpushGate = new Promise<void>((resolve) => {
|
||||||
rpushGateResolve = resolve;
|
rpushGateControl.resolve = resolve;
|
||||||
});
|
});
|
||||||
let rpushEntered = new Promise<void>((resolve) => {
|
let rpushEntered = new Promise<void>((resolve) => {
|
||||||
rpushEnteredResolve = 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",
|
"sync_data ACK must NOT fire before Redis RPUSH finishes",
|
||||||
);
|
);
|
||||||
|
|
||||||
rpushGateResolve?.();
|
rpushGateControl.resolve?.();
|
||||||
const syncAck = await syncAckPromise;
|
const syncAck = await syncAckPromise;
|
||||||
assert.equal(syncAck.success, true);
|
assert.equal(syncAck.success, true);
|
||||||
assert.equal(await fakeRedis.llen(REDIS_BUFFER_KEY), 1);
|
assert.equal(await fakeRedis.llen(REDIS_BUFFER_KEY), 1);
|
||||||
|
|
||||||
// 2. batch_sync must also wait for Redis RPUSH before ACK
|
// 2. batch_sync must also wait for Redis RPUSH before ACK
|
||||||
rpushGate = new Promise<void>((resolve) => {
|
rpushGate = new Promise<void>((resolve) => {
|
||||||
rpushGateResolve = resolve;
|
rpushGateControl.resolve = resolve;
|
||||||
});
|
});
|
||||||
rpushEntered = new Promise<void>((resolve) => {
|
rpushEntered = new Promise<void>((resolve) => {
|
||||||
rpushEnteredResolve = 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",
|
"batch_sync ACK must NOT fire before Redis RPUSH finishes",
|
||||||
);
|
);
|
||||||
|
|
||||||
rpushGateResolve?.();
|
rpushGateControl.resolve?.();
|
||||||
const batchAck = await batchAckPromise;
|
const batchAck = await batchAckPromise;
|
||||||
assert.equal(batchAck.success, true);
|
assert.equal(batchAck.success, true);
|
||||||
assert.equal(batchAck.processed, 2);
|
assert.equal(batchAck.processed, 2);
|
||||||
@@ -1549,3 +1549,45 @@ 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\) : ''/);
|
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, 2,
|
||||||
|
"A second flush appends the same eventId again after failed trim: at-least-once, not exactly-once");
|
||||||
|
} finally {
|
||||||
|
CSVStorageManager.appendBatch = originalAppend;
|
||||||
|
DataBufferEngine.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 () => {
|
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();
|
resetAdminStateForTests();
|
||||||
await createInitialAdmin("r3-owner@datastack.dev", "OwnerPassword123!");
|
await createInitialAdmin("r3-owner@datastack.dev", "OwnerPassword123!");
|
||||||
const sessionSecret = getAdminSessionSecret();
|
const sessionSecret = getAdminSessionSecret()!;
|
||||||
const suffix = Date.now();
|
const suffix = Date.now();
|
||||||
const viewerEmail = `r3viewer_${suffix}@datastack.dev`;
|
const viewerEmail = `r3viewer_${suffix}@datastack.dev`;
|
||||||
const operatorEmail = `r3operator_${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,
|
email: viewerEmail,
|
||||||
password: "ViewerPassword123!",
|
password: "ViewerPassword123!",
|
||||||
role: "viewer",
|
role: "viewer",
|
||||||
displayName: "R3 Viewer",
|
|
||||||
});
|
});
|
||||||
const operator = await createAdminTeamMemberAsync({
|
const operator = await createAdminTeamMemberAsync({
|
||||||
email: operatorEmail,
|
email: operatorEmail,
|
||||||
password: "OperatorPassword123!",
|
password: "OperatorPassword123!",
|
||||||
role: "operator",
|
role: "operator",
|
||||||
displayName: "R3 Operator",
|
|
||||||
});
|
});
|
||||||
await SDKManager.registerClientAsync({
|
await SDKManager.registerClientAsync({
|
||||||
clientId,
|
clientId,
|
||||||
@@ -292,7 +290,7 @@ test("R3-Phase-01 [BUG-06]: Locked webhook secret does not break unrelated setti
|
|||||||
|
|
||||||
const ownerToken = await createAdminSessionToken(
|
const ownerToken = await createAdminSessionToken(
|
||||||
owner.email,
|
owner.email,
|
||||||
getAdminSessionSecret(),
|
getAdminSessionSecret()!,
|
||||||
Date.now() + 3600_000,
|
Date.now() + 3600_000,
|
||||||
owner.tokenVersion,
|
owner.tokenVersion,
|
||||||
owner.role,
|
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");
|
assert.equal(dispatchedBodies[0].instance, "DataStack");
|
||||||
} finally {
|
} finally {
|
||||||
global.fetch = origFetch;
|
global.fetch = origFetch;
|
||||||
await clearAdminLoginAttempts(email, getAdminSessionSecret(), testIp);
|
await clearAdminLoginAttempts(email, getAdminSessionSecret()!, testIp);
|
||||||
await SettingsManager.updateSettingsAsync({
|
await SettingsManager.updateSettingsAsync({
|
||||||
enableWebhookAlerts: false,
|
enableWebhookAlerts: false,
|
||||||
webhookUrl: "",
|
webhookUrl: "",
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ function writeGzipCsv(filePath: string, content: string): void {
|
|||||||
|
|
||||||
async function createOwnerCookie(): Promise<string> {
|
async function createOwnerCookie(): Promise<string> {
|
||||||
delete process.env.DATABASE_URL;
|
delete process.env.DATABASE_URL;
|
||||||
const sessionSecret = getAdminSessionSecret();
|
const sessionSecret = getAdminSessionSecret()!;
|
||||||
resetAdminStateForTests();
|
resetAdminStateForTests();
|
||||||
const ownerEmail = "owner-r3p2@datastack.local";
|
const ownerEmail = "owner-r3p2@datastack.local";
|
||||||
await createInitialAdmin(ownerEmail, "StrongPassword123!");
|
await createInitialAdmin(ownerEmail, "StrongPassword123!");
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import test from "node:test";
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { GET as prometheusGet } from "../app/api/prometheus/route";
|
import { GET as prometheusGet } from "../app/api/prometheus/route";
|
||||||
import { SettingsManager } from "../core/adminSettings/settingsManager";
|
import { SettingsManager } from "../core/adminSettings/settingsManager";
|
||||||
|
import { DataBufferEngine } from "../core/data/buffer";
|
||||||
import { ApiEngine } from "../core/apiEngine/apiService";
|
import { ApiEngine } from "../core/apiEngine/apiService";
|
||||||
import {
|
import {
|
||||||
createAdminSessionToken,
|
createAdminSessionToken,
|
||||||
@@ -24,6 +25,11 @@ import {
|
|||||||
summarizeUiClientCounts,
|
summarizeUiClientCounts,
|
||||||
} from "../lib/vconUiHelpers";
|
} from "../lib/vconUiHelpers";
|
||||||
|
|
||||||
|
test.after(async () => {
|
||||||
|
SDKManager.stopActivityFlushTimerForTests();
|
||||||
|
await DataBufferEngine.shutdown();
|
||||||
|
});
|
||||||
|
|
||||||
async function makeOwnerCookie(): Promise<string> {
|
async function makeOwnerCookie(): Promise<string> {
|
||||||
resetAdminStateForTests();
|
resetAdminStateForTests();
|
||||||
await createInitialAdmin("r3-p4-owner@datastack.dev", "R3Phase04Pass!");
|
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> {
|
async function createOwnerCookie(email = "r4p1-owner@datastack.dev"): Promise<string> {
|
||||||
resetAdminStateForTests();
|
resetAdminStateForTests();
|
||||||
await createInitialAdmin(email, "OwnerPassword123!");
|
await createInitialAdmin(email, "OwnerPassword123!");
|
||||||
const secret = getAdminSessionSecret();
|
const secret = getAdminSessionSecret()!;
|
||||||
const token = await createAdminSessionToken(
|
const token = await createAdminSessionToken(
|
||||||
email,
|
email,
|
||||||
secret,
|
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);
|
assert.equal(unauthSync.status, 401);
|
||||||
|
|
||||||
// Owner session v1 works before logout/revocation
|
// Owner session v1 works before logout/revocation
|
||||||
const secret = getAdminSessionSecret();
|
const secret = getAdminSessionSecret()!;
|
||||||
const ownerTokenV1 = await createAdminSessionToken(
|
const ownerTokenV1 = await createAdminSessionToken(
|
||||||
"r4-audit-owner@datastack.dev",
|
"r4-audit-owner@datastack.dev",
|
||||||
secret,
|
secret,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import fsp from "node:fs/promises";
|
|||||||
import http from "node:http";
|
import http from "node:http";
|
||||||
import { createRequire } from "node:module";
|
import { createRequire } from "node:module";
|
||||||
import type { AddressInfo } from "node:net";
|
import type { AddressInfo } from "node:net";
|
||||||
|
import type { Request, Response } from "express";
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
@@ -81,7 +82,7 @@ async function createOwnerCookie(
|
|||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
resetAdminStateForTests();
|
resetAdminStateForTests();
|
||||||
await createInitialAdmin(email, "OwnerPassword123!");
|
await createInitialAdmin(email, "OwnerPassword123!");
|
||||||
const secret = getAdminSessionSecret();
|
const secret = getAdminSessionSecret()!;
|
||||||
const token = await createAdminSessionToken(
|
const token = await createAdminSessionToken(
|
||||||
email,
|
email,
|
||||||
secret,
|
secret,
|
||||||
@@ -329,13 +330,13 @@ test("R4-Phase-02 AUDIT-06: Governance audit logging for /api/export, Files Mana
|
|||||||
getDbPool: () => null,
|
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 });
|
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 });
|
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
|
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,
|
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 });
|
res.status(200).json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import fs from 'node:fs';
|
|||||||
import { createRequire } from 'node:module';
|
import { createRequire } from 'node:module';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
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 { NextRequest } from 'next/server';
|
||||||
import { POST as setupPost } from '../app/api/auth/setup/route';
|
import { POST as setupPost } from '../app/api/auth/setup/route';
|
||||||
import { GET as filesStatusGet } from '../app/api/files/status/route';
|
import { GET as filesStatusGet } from '../app/api/files/status/route';
|
||||||
@@ -13,9 +13,14 @@ import {
|
|||||||
getAdminSessionSecret,
|
getAdminSessionSecret,
|
||||||
} from '../core/auth/adminSession';
|
} from '../core/auth/adminSession';
|
||||||
import { resetAdminStateForTests } from '../core/auth/adminUsers';
|
import { resetAdminStateForTests } from '../core/auth/adminUsers';
|
||||||
|
import { DataBufferEngine } from '../core/data/buffer';
|
||||||
import { middleware } from '../middleware';
|
import { middleware } from '../middleware';
|
||||||
import { DataStack, DiskSpooler } from '../sdk/node/datastack';
|
import { DataStack, DiskSpooler } from '../sdk/node/datastack';
|
||||||
|
|
||||||
|
after(async () => {
|
||||||
|
await DataBufferEngine.shutdown();
|
||||||
|
});
|
||||||
|
|
||||||
const require = createRequire(import.meta.url);
|
const require = createRequire(import.meta.url);
|
||||||
const ORIGINAL_ENV = { ...process.env };
|
const ORIGINAL_ENV = { ...process.env };
|
||||||
const ORIGINAL_FETCH = globalThis.fetch;
|
const ORIGINAL_FETCH = globalThis.fetch;
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import { SDKManager } from "../core/sdk/sdkManager";
|
|||||||
import { getInternalIngestionHeaders } from "../core/Security/security";
|
import { getInternalIngestionHeaders } from "../core/Security/security";
|
||||||
import { SSRFBlockedError } from "../core/Security/ssrfGuard";
|
import { SSRFBlockedError } from "../core/Security/ssrfGuard";
|
||||||
import { CSVStorageManager } from "../core/Storage/csvStorage";
|
import { CSVStorageManager } from "../core/Storage/csvStorage";
|
||||||
|
import { DataBufferEngine } from "../core/data/buffer";
|
||||||
import { middleware } from "../middleware";
|
import { middleware } from "../middleware";
|
||||||
|
|
||||||
const require = createRequire(import.meta.url);
|
const require = createRequire(import.meta.url);
|
||||||
@@ -78,8 +79,15 @@ const cjsRuntimeLogCapture = require("../server/runtimeLogCapture.js") as {
|
|||||||
const ingestionServer = require("../server/index.js") as {
|
const ingestionServer = require("../server/index.js") as {
|
||||||
setDbPoolForTests: (pool: unknown) => void;
|
setDbPoolForTests: (pool: unknown) => void;
|
||||||
syncSettingsFromDatabase: () => Promise<boolean>;
|
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 () => {
|
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 tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "datastack-r5-logs-"));
|
||||||
const logsDir = path.join(tmpDir, ".runtime-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);
|
assert.equal(deniedClientCreate.isError, true);
|
||||||
const deniedPayload = JSON.parse(
|
const deniedPayload = JSON.parse(
|
||||||
(deniedClientCreate.content[0] as { text: string }).text,
|
((deniedClientCreate.content as Array<{ text: string }>)[0]).text,
|
||||||
) as { code: string; permission: string };
|
) as { code: string; permission: string };
|
||||||
assert.equal(deniedPayload.code, "MCP_PERMISSION_DENIED");
|
assert.equal(deniedPayload.code, "MCP_PERMISSION_DENIED");
|
||||||
assert.equal(deniedPayload.permission, "clients_create");
|
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);
|
assert.notEqual(createdToolRes.isError, true);
|
||||||
const createdPayload = JSON.parse(
|
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 } };
|
) as { success: boolean; client: { clientId: string; rateLimit: number; token?: string } };
|
||||||
assert.equal(createdPayload.success, true);
|
assert.equal(createdPayload.success, true);
|
||||||
assert.equal(createdPayload.client.clientId, testClientId);
|
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(traversalRes.isError, true);
|
||||||
assert.equal(
|
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",
|
"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(symlinkRes.isError, true);
|
||||||
assert.equal(
|
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",
|
"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(lockReadRes.isError, true);
|
||||||
assert.equal(
|
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",
|
"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(lockedFileUploadRes.isError, true);
|
||||||
assert.equal(
|
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,
|
.code,
|
||||||
"LOCKFILE_PROTECTED",
|
"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(logWriteRes.isError, true);
|
||||||
assert.equal(
|
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",
|
"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.notEqual(dlRes.isError, true);
|
||||||
assert.equal(
|
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",
|
"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" },
|
arguments: { path: "data" },
|
||||||
});
|
});
|
||||||
assert.notEqual(listRes.isError, true);
|
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 }>;
|
entries: Array<{ name: string }>;
|
||||||
};
|
};
|
||||||
assert.ok(listParsed.entries.some((e) => e.name === "active.csv"));
|
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.notEqual(metricsRes.isError, true);
|
||||||
assert.equal(
|
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,
|
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" },
|
arguments: { action: "flush" },
|
||||||
});
|
});
|
||||||
assert.notEqual(flushRes.isError, true);
|
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;
|
success: boolean;
|
||||||
ingestionFlushed: number;
|
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(coolifySsrfRes.isError, true);
|
||||||
assert.equal(
|
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",
|
"SSRF_BLOCKED_HOST",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import path from "node:path";
|
|||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
|
|
||||||
import { MCP_PERMISSION_DEFINITIONS } from "../core/mcp/mcpSettings";
|
import { MCP_PERMISSION_DEFINITIONS } from "../core/mcp/mcpSettings";
|
||||||
|
import { DataBufferEngine } from "../core/data/buffer";
|
||||||
import {
|
import {
|
||||||
applyCategoryPermissionToggle,
|
applyCategoryPermissionToggle,
|
||||||
applyMcpPermissionPreset,
|
applyMcpPermissionPreset,
|
||||||
@@ -23,6 +24,10 @@ import {
|
|||||||
|
|
||||||
const DEFINITIONS = MCP_PERMISSION_DEFINITIONS as readonly McpPermissionDefinitionView[];
|
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", () => {
|
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
|
// 1. Endpoint URL builder
|
||||||
assert.equal(
|
assert.equal(
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ import {
|
|||||||
uploadFileToS3,
|
uploadFileToS3,
|
||||||
} from "../core/Storage/s3Archive";
|
} from "../core/Storage/s3Archive";
|
||||||
import {
|
import {
|
||||||
|
classifyUiClientStatus,
|
||||||
|
summarizeUiClientCounts,
|
||||||
DEFAULT_EDITABLE_SETTINGS,
|
DEFAULT_EDITABLE_SETTINGS,
|
||||||
settingsToNumericDrafts,
|
settingsToNumericDrafts,
|
||||||
validateEditableSettingsDraft,
|
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,
|
bsize: 4096,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const snapshot = await CSVStorageManager.getDiskUsageAsync(true);
|
const snapshot = await CSVStorageManager.getDiskUsageAsync();
|
||||||
assert.equal(snapshot.available, true);
|
assert.equal(snapshot.available, true);
|
||||||
assert.equal(snapshot.usedPct, 25);
|
assert.equal(snapshot.usedPct, 25);
|
||||||
assert.equal(snapshot.totalBytes, 2000 * 4096);
|
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 () => {
|
CSVStorageManager.setStatfsOverrideForTests(async () => {
|
||||||
throw new Error("Simulated statfs failure");
|
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.available, false);
|
||||||
assert.equal(fallbackSnapshot.freeBytes, 0);
|
assert.equal(fallbackSnapshot.freeBytes, 0);
|
||||||
assert.equal(fallbackSnapshot.availableBytes, 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(
|
const clientsPageSrc = await fs.readFile(
|
||||||
path.join(process.cwd(), "app/vcon/clients/page.tsx"),
|
path.join(process.cwd(), "app/vcon/clients/page.tsx"),
|
||||||
"utf8",
|
"utf8",
|
||||||
);
|
);
|
||||||
assert.match(clientsPageSrc, /function isClientExpired\(/);
|
assert.match(clientsPageSrc, /summarizeUiClientCounts\(clients, now\)/);
|
||||||
assert.match(
|
assert.match(clientsPageSrc, /classifyUiClientStatus\(client, now\)/);
|
||||||
clientsPageSrc,
|
const now = Date.parse("2026-11-21T10:00:00.000Z");
|
||||||
/const expired = !revoked && isClientExpired\(client\.expiresAt,\s*now\)/,
|
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 };
|
||||||
assert.match(
|
const onlineClient = { status: "active" as const, expiresAt: null, lastActive: "2026-11-21T09:59:50.000Z" };
|
||||||
clientsPageSrc,
|
assert.equal(classifyUiClientStatus(expiredClient, now), "expired");
|
||||||
/!isClientExpired\(client\.expiresAt,\s*now\)/,
|
assert.equal(classifyUiClientStatus(pendingClient, now), "pending");
|
||||||
);
|
assert.equal(classifyUiClientStatus(onlineClient, now), "online");
|
||||||
assert.match(
|
const summary = summarizeUiClientCounts([expiredClient, pendingClient, onlineClient], now);
|
||||||
clientsPageSrc,
|
assert.equal(summary.expired, 1);
|
||||||
/const pending =\s*client\.status === 'active' && !expired && !client\.lastActive/,
|
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
|
// 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(
|
const exportWorkspaceSrc = await fs.readFile(
|
||||||
|
|||||||
@@ -331,7 +331,7 @@ test("V2-Phase-02 [HTTP & Socket Ingestion Security]: Per-client IP allowlist (4
|
|||||||
token: string,
|
token: string,
|
||||||
bypassCache?: boolean,
|
bypassCache?: boolean,
|
||||||
clientIp?: string,
|
clientIp?: string,
|
||||||
) => Promise<{ ok: boolean; reason?: string }>;
|
) => Promise<{ allowed: boolean; code?: string; reason?: string }>;
|
||||||
setDbPoolForTests: (pool: unknown) => void;
|
setDbPoolForTests: (pool: unknown) => void;
|
||||||
stopTimers: () => void;
|
stopTimers: () => void;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in new issue
Block a user