Files
Patrícia Santos ee774c6d37
ai-news-writer-ci / test (pull_request) Failing after 30s
feat(ops): BIT-14772 database and caching improvements
- Add DB_SCHEMA.md documenting article-index JSONL, all PostgreSQL
  analytics tables (engagement_events, article_analytics, daily_metrics,
  category_benchmarks), in-memory caches, and O(n) benchmark notes
- Add three missing composite indexes to analytics schema migrations
  (idx_engagement_captured_date, idx_article_published_date,
  idx_daily_metrics_post_date)
- Add src/analytics/maintenance.js: daily retention purge for all
  analytics tables plus VACUUM ANALYZE; configurable via env vars
- Add src/store/file-lock.js: POSIX O_CREAT|O_EXCL advisory lock with
  stale-lock cleanup; prevents TOCTOU races on article-log writes
- Wire file-lock into article-log: appendArticleRecord and
  updateArticleMetadata (including slug uniqueness check) now run inside
  the lock, preventing duplicate-slug races between concurrent processes
- Add src/listener/guid-store.js: persistent GUID deduplication store
  with atomic save, 2000-GUID cap, and FIFO trim to 1500
- Wire guid-store into rss-listener: GUIDs now load from disk on startup
  and are saved atomically before on_new_articles fires, so listener
  deduplication survives process restarts
- Add tests: file-lock.test.js (6 cases), guid-store.test.js (10 cases);
  all 45 tests pass
- Add data/listener-guid-store.json and data/*.json to .gitignore
2026-04-27 22:55:59 +00:00

8.1 KiB

Database & Caching: Schema and Strategy Reference

Updated: 2026-04-27 — BIT-14772


1. Article Index (JSONL file store)

Path: data/article-index.jsonl (override: ARTICLE_LOG_PATH)

Each line is a JSON object representing one published/generated article.

Field Type Description
at ISO timestamp Record creation time (used as row ID when slug is empty)
title string Article headline
subtitle string Article sub-headline
slug string URL slug — used as primary row ID when non-empty
summary string (≤500 chars) AI-generated summary
wp_link string | null WordPress published URL
site_name string | null Target WordPress site
mode write | listen | unknown How the article was generated
editorial_status pending | approved | rejected Editorial workflow state
tags string[] | null Up to 20 tags
category string | null Article category
sources {url, publication}[] | null Up to 10 source references
quality_score integer | null AI quality assessment score
quality_issues string[] | null Up to 10 quality flags
quality_status string | null Overall quality verdict

Row identity: slug when non-empty; at (ISO timestamp) otherwise.

Retention: file is trimmed to the last 10,000 lines when it exceeds 2 MB. Configure with:

  • ARTICLE_LOG_MAX_LINES (default: 10,000)
  • ARTICLE_LOG_TRIM_AT_BYTES (default: 2,097,152)

Concurrency safety: all write operations (appendArticleRecord, updateArticleMetadata) acquire an advisory file lock at <log_path>.lock before reading or writing. The slug uniqueness check runs inside the lock to prevent race conditions between concurrent processes.


2. PostgreSQL Analytics Database

Connection env vars:

Var Default Notes
ANALYTICS_DB_HOST localhost
ANALYTICS_DB_PORT 5432
ANALYTICS_DB_NAME ai_news_analytics
ANALYTICS_DB_USER postgres
ANALYTICS_DB_PASSWORD (empty)
ANALYTICS_DB_POOL_SIZE 10 Max pool connections

2.1 engagement_events

Raw engagement events captured from WordPress.

Column Type Constraints
id BIGSERIAL PK
post_id INTEGER NOT NULL
event_type VARCHAR(20) CHECK: view | share | comment
event_count INTEGER DEFAULT 1
captured_at TIMESTAMP NOT NULL
recorded_at TIMESTAMP DEFAULT NOW()

Indexes:

  • idx_engagement_post_captured — (post_id, captured_at DESC) — per-post time range queries
  • idx_engagement_type_recorded — (event_type, recorded_at DESC) — type-filtered queries
  • idx_engagement_captured_date — (DATE(captured_at)) — daily aggregation queries

Retention: delete rows older than ANALYTICS_ENGAGEMENT_RETENTION_DAYS days (default: 90).

2.2 article_analytics

Denormalized article metadata for analytics joins.

Column Type Constraints
post_id INTEGER PK
slug VARCHAR(255) UNIQUE
title TEXT
category VARCHAR(100)
published_at TIMESTAMP NOT NULL
site_name VARCHAR(100)
custom_meta JSONB NOT NULL DEFAULT {}
updated_at TIMESTAMP DEFAULT NOW()

Indexes:

  • idx_article_category_published — (category, published_at DESC) — category dashboard filters
  • idx_article_analytics_custom_meta — GIN on custom_meta — JSONB field queries
  • idx_article_published_date — (DATE(published_at)) — date-based dashboard filters

2.3 daily_metrics

Pre-aggregated daily engagement per article.

Column Type Constraints
id BIGSERIAL PK
post_id INTEGER FK → article_analytics.post_id
period_date DATE NOT NULL
views INTEGER DEFAULT 0
shares INTEGER DEFAULT 0
comments INTEGER DEFAULT 0
aggregated_at TIMESTAMP DEFAULT NOW()

Constraints: UNIQUE (post_id, period_date)

Indexes:

  • idx_daily_metrics_date — (period_date DESC) — time-range queries
  • idx_daily_metrics_post — (post_id) — single-article lookup
  • idx_daily_metrics_post_date — (post_id, period_date DESC) — combined post+time filter

Retention: delete rows where period_date < today - ANALYTICS_DAILY_METRICS_RETENTION_DAYS (default: 365).

2.4 category_benchmarks

Aggregated percentile stats per category per day.

Column Type Constraints
id BIGSERIAL PK
category VARCHAR(100) NOT NULL
period_date DATE NOT NULL
metric_type VARCHAR(20) CHECK: views | shares | comments
avg_value DECIMAL(12,2)
percentile_50 DECIMAL(12,2)
percentile_75 DECIMAL(12,2)
percentile_90 DECIMAL(12,2)
article_count INTEGER DEFAULT 0
computed_at TIMESTAMP DEFAULT NOW()

Constraints: UNIQUE (category, period_date, metric_type)

Indexes:

  • idx_category_benchmarks_lookup — (category, period_date DESC) — benchmark queries

Retention: delete rows where period_date < today - ANALYTICS_BENCHMARKS_RETENTION_DAYS (default: 365).

2.5 schema_version

Column Type Notes
id SERIAL PK
version INT NOT NULL
applied_at TIMESTAMP DEFAULT NOW()

3. In-Memory Caches

3.1 RSS GUID Store

Module: src/listener/guid-store.js Persistence: data/listener-guid-store.json (override: GUID_STORE_PATH)

Tracks seen article GUIDs across listener ticks to prevent duplicate processing.

Property Value
Max size 2,000 GUIDs
Trim-to 1,500 GUIDs (when cap exceeded)
Eviction policy Oldest GUIDs dropped (FIFO trim)
Persistence Saved to disk after each tick with new articles; loaded on process start
TTL None — GUIDs expire only when trimmed

Restart safety: the store is written atomically (temp file + rename) before calling on_new_articles. A process restart re-reads the file and continues deduplication from the last known state.

3.2 Circuit Breaker State

Module: src/crawler/circuit-breaker.js

Per-source state machine preventing hammering of failing RSS feeds.

Property Value
Storage In-memory Map (process lifetime)
Failure threshold 3 consecutive failures → OPEN
Window size 5 observations
Open timeout 5 minutes → transitions to HALF_OPEN
Persistence None — resets on process restart

3.3 Queue Backpressure

Module: src/queue/backpressure.js

Property Value
Max in-flight 5 articles (configurable)
Storage In-memory counters
Persistence None

4. Maintenance Policy

Module: src/analytics/maintenance.js

Run runMaintenanceCycle() on a daily schedule (e.g. via node-cron at 03:00).

Task Default retention Env override
Purge engagement_events 90 days ANALYTICS_ENGAGEMENT_RETENTION_DAYS
Purge daily_metrics 365 days ANALYTICS_DAILY_METRICS_RETENTION_DAYS
Purge category_benchmarks 365 days ANALYTICS_BENCHMARKS_RETENTION_DAYS
VACUUM ANALYZE all tables After every purge —

getTableStats() returns row counts and sizes for all analytics tables — useful for monitoring dashboards.

Integrating the maintenance cron

const cron = require('node-cron');
const { runMaintenanceCycle } = require('./src/analytics/maintenance');

// Daily at 03:00 local time
cron.schedule('0 3 * * *', async () => {
  await runMaintenanceCycle();
});

5. Access Pattern Benchmarks

The following operations have O(n) cost on the article JSONL log (n = number of lines):

Operation Cost Mitigation
readLastArticles(limit) O(n) read Capped at 500 results; log capped at 10K lines
validateSlugUniqueness O(n) scan Runs inside file lock; acceptable at ≤10K lines
trimArticleLogIfNeeded O(n) rewrite Triggered only when file exceeds 2 MB
updateArticleMetadata O(n) rewrite Serialized via file lock

All PostgreSQL queries use indexed access patterns. See indexes in Section 2.