release: v1.3.1 - Pipeline Queue Integration, OCR Fix, Worker Compatibility

Major Changes:
- Pipeline Queue integration completed (internal.file + pipeline.commands)
- Fixed old job_worker database compatibility with new command_queue table
- Compiled Swift OCR binary (was missing, causing empty OCR results)
- Added deep scan functionality through re-scan API

Fixes:
- Changed CommandJob.id from i32 to i64 for database compatibility
- Added UUID generation in create_command (message_id field)
- Fixed claim_pending_commands to query queue_name = 'internal.file'
- Fixed field mappings: command_id → message_id, job_type → command_type
- Added support for 'processing' status in CommandJobStatus

Queue System:
- internal.file queue: for register/unregister/re-scan commands (job_worker)
- pipeline.commands queue: for vectorize/store_asrx/etc commands (pipeline_worker)

Documentation:
- Added comprehensive queue system documentation
- Created M4 workspace status reports
- Updated AGENTS.md with queue system details
This commit is contained in:
Accusys
2026-10-12 10:00:51 +08:00
parent 0a18e70639
commit 63fbbe1225
418 changed files with 44084 additions and 4280 deletions
+268
View File
@@ -0,0 +1,268 @@
-- ============================================
-- MarkBase Command Queue Schema
-- ============================================
-- Version: 1.0
-- Date: 2026-10-11
-- Description: 统一命令队列表结构
-- ============================================
-- ============================================
-- 1. 命令队列表
-- ============================================
CREATE TABLE IF NOT EXISTS command_queue (
-- 消息 ID
id BIGSERIAL PRIMARY KEY,
message_id VARCHAR(36) NOT NULL UNIQUE,
-- 队列信息
queue_name VARCHAR(255) NOT NULL,
queue_type VARCHAR(50) NOT NULL, -- 'internal' | 'external' | 'agent' | 'system'
-- 命令信息
command_type VARCHAR(100) NOT NULL,
command_category VARCHAR(100),
command_action VARCHAR(100),
-- 消息内容
key VARCHAR(255),
value JSONB NOT NULL,
-- 优先级
priority SMALLINT DEFAULT 2, -- 0=Critical, 1=High, 2=Normal, 3=Low
-- Billing 信息
request_id VARCHAR(36),
key_id VARCHAR(36),
billing_context JSONB,
token_usage JSONB,
cost_usd DECIMAL(10, 6),
-- 状态管理
status VARCHAR(20) DEFAULT 'pending', -- 'pending' | 'processing' | 'completed' | 'failed'
consumer_group VARCHAR(255),
consumer_id VARCHAR(255),
-- 重试机制
retry_count INTEGER DEFAULT 0,
max_retries INTEGER DEFAULT 3,
last_error TEXT,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
scheduled_at TIMESTAMP WITH TIME ZONE,
processing_started_at TIMESTAMP WITH TIME ZONE,
processing_completed_at TIMESTAMP WITH TIME ZONE,
-- 约束
CONSTRAINT valid_queue_type CHECK (queue_type IN ('internal', 'external', 'agent', 'system')),
CONSTRAINT valid_status CHECK (status IN ('pending', 'processing', 'completed', 'failed')),
CONSTRAINT valid_priority CHECK (priority >= 0 AND priority <= 3)
);
-- 创建索引
CREATE INDEX idx_command_queue_name ON command_queue(queue_name, priority, created_at);
CREATE INDEX idx_command_status ON command_queue(status, created_at);
CREATE INDEX idx_command_consumer ON command_queue(consumer_group, consumer_id);
CREATE INDEX idx_command_type ON command_queue(command_type, created_at);
CREATE INDEX idx_command_billing ON command_queue(request_id, key_id);
CREATE INDEX idx_command_scheduled ON command_queue(scheduled_at, status);
-- ============================================
-- 2. 命令执行日志表
-- ============================================
CREATE TABLE IF NOT EXISTS command_execution_log (
id BIGSERIAL PRIMARY KEY,
message_id VARCHAR(36) NOT NULL,
-- 执行信息
handler VARCHAR(255),
action VARCHAR(255),
-- 执行结果
status VARCHAR(20), -- 'success' | 'error' | 'timeout'
result JSONB,
error_message TEXT,
-- 性能指标
duration_ms INTEGER,
tokens_used INTEGER,
cost_usd DECIMAL(10, 6),
-- 时间戳
executed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- 约束
FOREIGN KEY (message_id) REFERENCES command_queue(message_id) ON DELETE CASCADE,
CONSTRAINT valid_exec_status CHECK (status IN ('success', 'error', 'timeout'))
);
CREATE INDEX idx_exec_log_message ON command_execution_log(message_id, executed_at);
CREATE INDEX idx_exec_log_status ON command_execution_log(status, executed_at);
CREATE INDEX idx_exec_log_handler ON command_execution_log(handler, executed_at);
-- ============================================
-- 3. Agent 订阅表
-- ============================================
CREATE TABLE IF NOT EXISTS agent_subscriptions (
id SERIAL PRIMARY KEY,
agent_id VARCHAR(255) NOT NULL,
queue_name VARCHAR(255) NOT NULL,
consumer_group VARCHAR(255) NOT NULL,
-- 订阅状态
active BOOLEAN DEFAULT true,
last_message_at TIMESTAMP WITH TIME ZONE,
message_count BIGINT DEFAULT 0,
-- 配置
auto_commit BOOLEAN DEFAULT true,
max_batch_size INTEGER DEFAULT 10,
timeout_ms INTEGER DEFAULT 5000,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- 约束
UNIQUE(agent_id, queue_name)
);
CREATE INDEX idx_agent_subs_agent ON agent_subscriptions(agent_id);
CREATE INDEX idx_agent_subs_queue ON agent_subscriptions(queue_name);
-- ============================================
-- 4. 队列路由配置表
-- ============================================
CREATE TABLE IF NOT EXISTS queue_routes (
id SERIAL PRIMARY KEY,
command_type VARCHAR(100) NOT NULL,
command_category VARCHAR(100),
-- 路由信息
queue_name VARCHAR(255) NOT NULL,
handler VARCHAR(255) NOT NULL,
priority SMALLINT DEFAULT 2,
billing_required BOOLEAN DEFAULT true,
-- 配置
max_retries INTEGER DEFAULT 3,
timeout_ms INTEGER DEFAULT 30000,
-- 状态
active BOOLEAN DEFAULT true,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- 约束
UNIQUE(command_type, command_category)
);
CREATE INDEX idx_queue_routes_type ON queue_routes(command_type);
CREATE INDEX idx_queue_routes_queue ON queue_routes(queue_name);
-- ============================================
-- 5. 插入默认路由配置
-- ============================================
INSERT INTO queue_routes (command_type, command_category, queue_name, handler, priority, billing_required) VALUES
-- 内部命令
('internal', 'video_registration', 'internal.video', 'video_registration_handler', 2, true),
('internal', 'file_processing', 'internal.file', 'file_processing_handler', 2, true),
('internal', 'file_deletion', 'internal.file', 'file_deletion_handler', 3, true),
('internal', 'embedding_generation', 'internal.data', 'embedding_handler', 2, true),
('internal', 'index_rebuild', 'internal.data', 'index_rebuild_handler', 3, true),
('internal', 'cache_clear', 'internal.system', 'cache_handler', 3, false),
('internal', 'worker_restart', 'internal.system', 'worker_handler', 1, false),
('internal', 'service_health_check', 'internal.system', 'health_check_handler', 2, false),
('internal', 'configuration_update', 'internal.system', 'config_handler', 1, false),
('internal', 'database_migration', 'internal.system', 'migration_handler', 0, false),
('internal', 'vector_sync', 'internal.data', 'vector_sync_handler', 2, true),
('internal', 'identity_merging', 'internal.data', 'identity_merge_handler', 3, true),
-- 外部命令
('external', 'api_request', 'external.api', 'api_request_handler', 1, true),
('external', 'user_command', 'external.user', 'user_command_handler', 1, true),
('external', 'webhook_trigger', 'external.webhook', 'webhook_handler', 2, true),
('external', 'integration_sync', 'external.integration', 'integration_handler', 3, true),
('external', 'external_api_call', 'external.api', 'external_api_handler', 2, true),
-- Agent 命令
('agent', 'agent_task', 'agent.tasks', 'agent_task_handler', 0, false),
('agent', 'agent_query', 'agent.queries', 'agent_query_handler', 0, false),
('agent', 'agent_response', 'agent.responses', 'agent_response_handler', 0, false),
('agent', 'agent_message', 'agent.messages', 'agent_message_handler', 0, false),
('agent', 'agent_broadcast', 'agent.broadcasts', 'agent_broadcast_handler', 0, false),
('agent', 'agent_subscribe', 'agent.subscriptions', 'agent_subscribe_handler', 0, false)
ON CONFLICT (command_type, command_category) DO NOTHING;
-- ============================================
-- 6. 队列统计视图
-- ============================================
CREATE OR REPLACE VIEW queue_statistics AS
SELECT
queue_name,
queue_type,
COUNT(*) as total_messages,
COUNT(*) FILTER (WHERE status = 'pending') as pending_count,
COUNT(*) FILTER (WHERE status = 'processing') as processing_count,
COUNT(*) FILTER (WHERE status = 'completed') as completed_count,
COUNT(*) FILTER (WHERE status = 'failed') as failed_count,
AVG(EXTRACT(EPOCH FROM (processing_completed_at - processing_started_at)) * 1000) FILTER (WHERE status = 'completed') as avg_duration_ms,
MIN(created_at) as oldest_message,
MAX(created_at) as newest_message
FROM command_queue
GROUP BY queue_name, queue_type
ORDER BY queue_name;
-- ============================================
-- 7. 性能优化触发器
-- ============================================
CREATE OR REPLACE FUNCTION update_command_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER update_agent_subscriptions_timestamp
BEFORE UPDATE ON agent_subscriptions
FOR EACH ROW
EXECUTE FUNCTION update_command_timestamp();
CREATE TRIGGER update_queue_routes_timestamp
BEFORE UPDATE ON queue_routes
FOR EACH ROW
EXECUTE FUNCTION update_command_timestamp();
-- ============================================
-- 8. 清理过期消息存储过程
-- ============================================
CREATE OR REPLACE PROCEDURE cleanup_old_commands(
days_to_keep INTEGER DEFAULT 30
)
LANGUAGE plpgsql
AS $$
BEGIN
-- 删除执行日志
DELETE FROM command_execution_log
WHERE executed_at < NOW() - (days_to_keep || ' days')::INTERVAL
AND message_id IN (
SELECT message_id FROM command_queue
WHERE status IN ('completed', 'failed')
);
-- 删除已完成的消息
DELETE FROM command_queue
WHERE status IN ('completed', 'failed')
AND processing_completed_at < NOW() - (days_to_keep || ' days')::INTERVAL;
RAISE NOTICE 'Cleaned up commands older than % days', days_to_keep;
END;
$$;
-- ============================================
-- Schema 创建完成
-- ============================================
+73
View File
@@ -0,0 +1,73 @@
-- ============================================
-- Pipeline Queue 集成
-- ============================================
-- Version: 1.0
-- Date: 2026-10-11
-- Description: Pipeline 命令队列路由配置
-- ============================================
-- ============================================
-- 1. 插入 Pipeline 命令路由
-- ============================================
INSERT INTO queue_routes (command_type, command_category, queue_name, handler, priority, billing_required) VALUES
-- Pipeline 操作
('internal', 'pipeline_store_asrx', 'pipeline.commands', 'pipeline_worker', 1, false),
('internal', 'pipeline_execute_rule1', 'pipeline.commands', 'pipeline_worker', 2, false),
('internal', 'pipeline_vectorize', 'pipeline.commands', 'pipeline_worker', 3, false),
('internal', 'pipeline_phase1_pack', 'pipeline.commands', 'pipeline_worker', 2, false),
('internal', 'pipeline_mark_complete', 'pipeline.commands', 'pipeline_worker', 1, false),
('internal', 'pipeline_execute_rule3', 'pipeline.commands', 'pipeline_worker', 2, false),
('internal', 'pipeline_reindex_embeddings', 'pipeline.commands', 'pipeline_worker', 3, false)
ON CONFLICT (command_type, command_category) DO NOTHING;
-- ============================================
-- 2. 创建 Pipeline 进度追踪表
-- ============================================
CREATE TABLE IF NOT EXISTS pipeline_progress (
id SERIAL PRIMARY KEY,
command_id VARCHAR(36) NOT NULL UNIQUE,
file_uuid VARCHAR(32) NOT NULL,
command_type VARCHAR(50) NOT NULL,
-- 进度
progress INTEGER DEFAULT 0, -- 0-100
message TEXT,
processed_count BIGINT DEFAULT 0,
total_count BIGINT DEFAULT 0,
-- 状态
status VARCHAR(20) DEFAULT 'processing',
error_message TEXT,
-- 时间戳
started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
completed_at TIMESTAMP WITH TIME ZONE,
-- 索引
FOREIGN KEY (command_id) REFERENCES command_queue(message_id) ON DELETE CASCADE
);
CREATE INDEX idx_pipeline_progress_file ON pipeline_progress(file_uuid, started_at);
CREATE INDEX idx_pipeline_progress_status ON pipeline_progress(status, started_at);
-- ============================================
-- 3. 创建 Pipeline 执行日志视图
-- ============================================
CREATE OR REPLACE VIEW pipeline_execution_stats AS
SELECT
command_category,
COUNT(*) as total_executions,
COUNT(*) FILTER (WHERE status = 'completed') as successful,
COUNT(*) FILTER (WHERE status = 'failed') as failed,
AVG(EXTRACT(EPOCH FROM (processing_completed_at - processing_started_at)) * 1000) FILTER (WHERE status = 'completed') as avg_duration_ms,
MIN(processing_started_at) as first_execution,
MAX(processing_started_at) as last_execution
FROM command_queue
WHERE command_type = 'internal'
AND command_category LIKE 'pipeline_%'
GROUP BY command_category
ORDER BY command_category;
-- ============================================
-- Schema 扩展完成
-- ============================================
+352
View File
@@ -0,0 +1,352 @@
-- ============================================
-- MarkBase Queue Extensions - Messenger, Log, Billing
-- ============================================
-- Version: 1.0
-- Date: 2026-10-11
-- Description: 扩展队列系统,支持消息传递、日志、计费
-- ============================================
-- ============================================
-- 1. 消息队列表
-- ============================================
CREATE TABLE IF NOT EXISTS message_queue (
id BIGSERIAL PRIMARY KEY,
message_id VARCHAR(36) NOT NULL UNIQUE,
queue_name VARCHAR(255) NOT NULL,
-- 消息类型
message_type VARCHAR(20) NOT NULL, -- 'command' | 'event' | 'status' | 'log' | 'error' | 'heartbeat'
-- 来源
source_type JSONB NOT NULL,
source_component VARCHAR(255),
-- 目标
target VARCHAR(255),
-- 优先级
priority INTEGER DEFAULT 2, -- 0-3
-- 内容
payload JSONB NOT NULL,
metadata JSONB DEFAULT '{}',
-- 投递选项
persistent BOOLEAN DEFAULT true,
retry_count INTEGER DEFAULT 0,
require_ack BOOLEAN DEFAULT false,
-- 状态管理
status VARCHAR(20) DEFAULT 'pending',
delivered_to VARCHAR(255),
delivered_at TIMESTAMP WITH TIME ZONE,
acknowledged_by VARCHAR(255),
acknowledged_at TIMESTAMP WITH TIME ZONE,
processed_at TIMESTAMP WITH TIME ZONE,
failed_at TIMESTAMP WITH TIME ZONE,
error_message TEXT,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
expires_at TIMESTAMP WITH TIME ZONE,
-- 约束
CONSTRAINT valid_message_status CHECK (status IN ('pending', 'delivered', 'acknowledged', 'processed', 'failed', 'expired'))
);
CREATE INDEX idx_message_queue_name ON message_queue(queue_name, priority, created_at);
CREATE INDEX idx_message_queue_status ON message_queue(status, created_at);
CREATE INDEX idx_message_queue_delivered ON message_queue(delivered_to, status);
-- ============================================
-- 2. 消息订阅表
-- ============================================
CREATE TABLE IF NOT EXISTS message_subscriptions (
id SERIAL PRIMARY KEY,
subscription_id VARCHAR(36) NOT NULL UNIQUE,
queue_name VARCHAR(255) NOT NULL,
subscriber_id VARCHAR(255) NOT NULL,
-- 过滤器
filter JSONB,
-- 状态
active BOOLEAN DEFAULT true,
last_message_at TIMESTAMP WITH TIME ZONE,
message_count BIGINT DEFAULT 0,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- 约束
UNIQUE(queue_name, subscriber_id)
);
CREATE INDEX idx_message_subs_queue ON message_subscriptions(queue_name);
CREATE INDEX idx_message_subs_subscriber ON message_subscriptions(subscriber_id);
-- ============================================
-- 3. 系统日志表
-- ============================================
CREATE TABLE IF NOT EXISTS system_logs (
id BIGSERIAL PRIMARY KEY,
log_id VARCHAR(36) NOT NULL UNIQUE,
timestamp TIMESTAMP WITH TIME ZONE NOT NULL,
-- 日志级别 (0=Trace, 1=Debug, 2=Info, 3=Warn, 4=Error, 5=Fatal)
level INTEGER NOT NULL,
-- 来源
source VARCHAR(50) NOT NULL,
component VARCHAR(255) NOT NULL,
-- 消息
message TEXT NOT NULL,
context JSONB,
-- 追踪
trace_id VARCHAR(36),
span_id VARCHAR(36),
-- 关联
user_id VARCHAR(36),
request_id VARCHAR(36),
-- 性能
duration_ms BIGINT,
-- 错误信息
error_type VARCHAR(255),
error_message TEXT,
stack_trace TEXT,
-- 索引
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_system_logs_timestamp ON system_logs(timestamp DESC);
CREATE INDEX idx_system_logs_level ON system_logs(level, timestamp);
CREATE INDEX idx_system_logs_source ON system_logs(source, component, timestamp);
CREATE INDEX idx_system_logs_trace ON system_logs(trace_id);
CREATE INDEX idx_system_logs_user ON system_logs(user_id, timestamp);
-- ============================================
-- 4. 计费使用表
-- ============================================
CREATE TABLE IF NOT EXISTS billing_usage (
id BIGSERIAL PRIMARY KEY,
record_id VARCHAR(36) NOT NULL UNIQUE,
key_id VARCHAR(36) NOT NULL,
-- 服务信息
service VARCHAR(50) NOT NULL,
model VARCHAR(100),
-- Token 使用
input_tokens INTEGER NOT NULL,
output_tokens INTEGER NOT NULL,
total_tokens INTEGER NOT NULL,
-- 成本
cost_usd DOUBLE PRECISION DEFAULT 0.0,
-- 性能
duration_ms BIGINT,
-- 关联
request_id VARCHAR(36),
queue_name VARCHAR(255),
message_id VARCHAR(36),
-- 状态
status VARCHAR(20) DEFAULT 'success',
-- 时间戳
timestamp TIMESTAMP WITH TIME ZONE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_billing_usage_key ON billing_usage(key_id, timestamp);
CREATE INDEX idx_billing_usage_service ON billing_usage(service, timestamp);
CREATE INDEX idx_billing_usage_period ON billing_usage(key_id, date_trunc('month', timestamp));
-- ============================================
-- 5. 计费 Quota 表
-- ============================================
CREATE TABLE IF NOT EXISTS billing_quotas (
id SERIAL PRIMARY KEY,
key_id VARCHAR(36) NOT NULL UNIQUE,
-- 限制
monthly_token_limit BIGINT DEFAULT 1000000,
daily_token_limit BIGINT DEFAULT 100000,
hourly_token_limit BIGINT DEFAULT 10000,
monthly_cost_limit DOUBLE PRECISION DEFAULT 100.0,
-- 当前使用
monthly_token_used BIGINT DEFAULT 0,
daily_token_used BIGINT DEFAULT 0,
hourly_token_used BIGINT DEFAULT 0,
monthly_cost_used DOUBLE PRECISION DEFAULT 0.0,
-- 超额
allow_overage BOOLEAN DEFAULT false,
overage_rate DOUBLE PRECISION DEFAULT 0.0,
-- 重置
last_month_reset TIMESTAMP WITH TIME ZONE,
last_day_reset TIMESTAMP WITH TIME ZONE,
last_hour_reset TIMESTAMP WITH TIME ZONE,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_billing_quotas_key ON billing_quotas(key_id);
-- ============================================
-- 6. 计费费率表
-- ============================================
CREATE TABLE IF NOT EXISTS billing_rates (
id SERIAL PRIMARY KEY,
service VARCHAR(50) NOT NULL,
model VARCHAR(100),
-- 费率 (每 1000 tokens)
input_rate_per_1k DOUBLE PRECISION DEFAULT 0.0,
output_rate_per_1k DOUBLE PRECISION DEFAULT 0.0,
-- 有效期
effective_from TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
effective_to TIMESTAMP WITH TIME ZONE,
-- 约束
UNIQUE(service, model, effective_from)
);
CREATE INDEX idx_billing_rates_service ON billing_rates(service, effective_from);
-- 插入默认费率
INSERT INTO billing_rates (service, model, input_rate_per_1k, output_rate_per_1k) VALUES
('vlm', 'gemma-4-12b-it', 0.0001, 0.0002),
('chat', 'gemma-4-12b-it', 0.00005, 0.0001),
('embedding', 'embeddinggemma-300m', 0.00001, 0.0),
('agent', 'gpt-4', 0.03, 0.06),
('search', NULL, 0.0, 0.0)
ON CONFLICT DO NOTHING;
-- ============================================
-- 7. 计费周期表
-- ============================================
CREATE TABLE IF NOT EXISTS billing_periods (
id SERIAL PRIMARY KEY,
key_id VARCHAR(36) NOT NULL,
period_month VARCHAR(7) NOT NULL,
-- 周期
period_start TIMESTAMP WITH TIME ZONE NOT NULL,
period_end TIMESTAMP WITH TIME ZONE NOT NULL,
-- 统计
total_tokens BIGINT DEFAULT 0,
total_cost DOUBLE PRECISION DEFAULT 0.0,
-- 明细
service_breakdown JSONB DEFAULT '{}',
model_breakdown JSONB DEFAULT '{}',
-- 请求统计
request_count BIGINT DEFAULT 0,
error_count BIGINT DEFAULT 0,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- 约束
UNIQUE(key_id, period_month)
);
CREATE INDEX idx_billing_periods_key ON billing_periods(key_id, period_month);
-- ============================================
-- 8. 计费警报表
-- ============================================
CREATE TABLE IF NOT EXISTS billing_alerts (
id SERIAL PRIMARY KEY,
key_id VARCHAR(36) NOT NULL UNIQUE,
-- 警报配置
threshold_percentage DOUBLE PRECISION DEFAULT 80.0,
notify_email VARCHAR(255),
notify_webhook VARCHAR(255),
enabled BOOLEAN DEFAULT true,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_billing_alerts_key ON billing_alerts(key_id);
-- ============================================
-- 9. 触发器和函数
-- ============================================
CREATE OR REPLACE FUNCTION update_billing_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER update_billing_quotas_timestamp
BEFORE UPDATE ON billing_quotas
FOR EACH ROW
EXECUTE FUNCTION update_billing_timestamp();
CREATE TRIGGER update_billing_periods_timestamp
BEFORE UPDATE ON billing_periods
FOR EACH ROW
EXECUTE FUNCTION update_billing_timestamp();
CREATE TRIGGER update_billing_alerts_timestamp
BEFORE UPDATE ON billing_alerts
FOR EACH ROW
EXECUTE FUNCTION update_billing_timestamp();
-- ============================================
-- 10. 清理存储过程
-- ============================================
CREATE OR REPLACE PROCEDURE cleanup_old_logs(
days_to_keep INTEGER DEFAULT 30
)
LANGUAGE plpgsql
AS $$
BEGIN
DELETE FROM system_logs
WHERE timestamp < NOW() - (days_to_keep || ' days')::INTERVAL;
RAISE NOTICE 'Cleaned up logs older than % days', days_to_keep;
END;
$$;
CREATE OR REPLACE PROCEDURE cleanup_old_messages(
days_to_keep INTEGER DEFAULT 7
)
LANGUAGE plpgsql
AS $$
BEGIN
DELETE FROM message_queue
WHERE status IN ('processed', 'failed', 'expired')
AND created_at < NOW() - (days_to_keep || ' days')::INTERVAL;
RAISE NOTICE 'Cleaned up messages older than % days', days_to_keep;
END;
$$;
-- ============================================
-- Schema 扩展完成
-- ============================================
+158
View File
@@ -0,0 +1,158 @@
-- ============================================
-- Replay System Schema
-- ============================================
-- Date: 2026-10-11
-- Purpose: Implement command replay functionality for stability testing
-- Features: Idempotency verification, batch replay, scenario testing
-- ============================================
-- 1. Replay Sessions 表
CREATE TABLE replay_sessions (
id BIGSERIAL PRIMARY KEY,
-- Session 信息
session_id VARCHAR(36) NOT NULL UNIQUE DEFAULT replace(gen_random_uuid()::text, '-', ''),
session_name VARCHAR(255),
replay_type VARCHAR(20) NOT NULL CHECK (
replay_type IN ('success', 'failed', 'batch', 'scenario')
),
-- 源命令过滤条件
source_filter JSONB NOT NULL DEFAULT '{}',
-- 配置
config JSONB NOT NULL DEFAULT '{}',
-- 执行状态
status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (
status IN ('pending', 'running', 'paused', 'completed', 'failed', 'cancelled')
),
-- 统计信息
total_commands INTEGER DEFAULT 0,
processed_commands INTEGER DEFAULT 0,
succeeded_commands INTEGER DEFAULT 0,
failed_commands INTEGER DEFAULT 0,
skipped_commands INTEGER DEFAULT 0,
-- 结果对比
comparison_results JSONB DEFAULT '[]',
-- 性能指标
started_at TIMESTAMP WITH TIME ZONE,
completed_at TIMESTAMP WITH TIME ZONE,
duration_secs DOUBLE PRECISION,
-- 错误信息
error_message TEXT,
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- 用户信息
user_id BIGINT
);
-- 索引
CREATE INDEX idx_replay_sessions_status ON replay_sessions (status, created_at);
CREATE INDEX idx_replay_sessions_type ON replay_sessions (replay_type, created_at);
CREATE INDEX idx_replay_sessions_user ON replay_sessions (user_id, created_at);
COMMENT ON TABLE replay_sessions IS 'Replay session for stability testing';
COMMENT ON COLUMN replay_sessions.replay_type IS 'success=verify idempotency, failed=test recovery, batch=stress test, scenario=test specific flow';
COMMENT ON COLUMN replay_sessions.source_filter IS 'Filter criteria for source commands';
COMMENT ON COLUMN replay_sessions.config IS 'Replay configuration (concurrency, delay, etc.)';
-- 2. Replay Commands 表
CREATE TABLE replay_commands (
id BIGSERIAL PRIMARY KEY,
-- 关联信息
session_id VARCHAR(36) NOT NULL,
original_command_id VARCHAR(36) NOT NULL,
replay_command_id VARCHAR(36),
-- 执行状态
status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (
status IN ('pending', 'running', 'completed', 'failed', 'skipped')
),
-- 原始命令信息
original_job_type VARCHAR(20),
original_file_path VARCHAR(512),
original_file_uuid VARCHAR(32),
original_payload JSONB,
-- 结果对比
original_result JSONB,
replay_result JSONB,
comparison_status VARCHAR(20) CHECK (
comparison_status IN ('match', 'mismatch', 'error', 'skipped')
),
differences JSONB,
-- 性能指标
original_duration_secs DOUBLE PRECISION,
replay_duration_secs DOUBLE PRECISION,
-- 错误信息
error_message TEXT,
retry_count INTEGER DEFAULT 0,
-- 时间戳
started_at TIMESTAMP WITH TIME ZONE,
completed_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- 外键
FOREIGN KEY (session_id) REFERENCES replay_sessions(session_id) ON DELETE CASCADE
);
-- 索引
CREATE INDEX idx_replay_commands_session ON replay_commands (session_id);
CREATE INDEX idx_replay_commands_status ON replay_commands (status);
CREATE INDEX idx_replay_commands_original ON replay_commands (original_command_id);
COMMENT ON TABLE replay_commands IS 'Individual command replay tracking';
COMMENT ON COLUMN replay_commands.comparison_status IS 'match=identical result, mismatch=difference detected, error=failed';
-- 3. 触发器:自动更新 updated_at
CREATE OR REPLACE FUNCTION update_replay_sessions_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_update_replay_sessions_updated_at
BEFORE UPDATE ON replay_sessions
FOR EACH ROW
EXECUTE FUNCTION update_replay_sessions_updated_at();
-- 4. 视图:Replay 统计
CREATE VIEW replay_stats AS
SELECT
replay_type,
status,
COUNT(*) as session_count,
AVG(duration_secs) as avg_duration_secs,
AVG(succeeded_commands::FLOAT / NULLIF(total_commands, 0)) as avg_success_rate
FROM replay_sessions
WHERE status = 'completed'
GROUP BY replay_type, status;
COMMENT ON VIEW replay_stats IS 'Replay session statistics';
-- ============================================
-- 示例数据(测试用)
-- ============================================
-- 插入测试 session
-- INSERT INTO replay_sessions (session_name, replay_type, source_filter, config)
-- VALUES ('Test idempotency', 'success', '{"limit": 10}', '{"concurrency": 5}');
-- ============================================
-- Migration 完成
-- ============================================
+248
View File
@@ -0,0 +1,248 @@
-- ============================================
-- VLM Request Queue Schema (Kafka-inspired)
-- ============================================
-- Date: 2026-10-11
-- Purpose: Implement VLM request queue with priority scheduling,
-- dead letter queue, and consumer offset tracking
-- Design: Based on Kafka concepts (append-only log, offset tracking,
-- partition by request_type, priority queue)
-- ============================================
-- 1. 消息表
CREATE TABLE vlm_requests (
-- Offset (单调递增)
id BIGSERIAL PRIMARY KEY,
-- 分区键
request_type VARCHAR(20) NOT NULL CHECK (
request_type IN ('agent_vlm', 'scene_vlm', 'face_vlm')
),
-- 优先级 (0 = 最高)
priority INTEGER DEFAULT 1 CHECK (priority >= 0 AND priority <= 10),
-- 状态
status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (
status IN ('pending', 'processing', 'completed', 'failed', 'timeout')
),
-- 消息内容
payload JSONB NOT NULL,
/*
Example payload for Scene VLM:
{
"image_path": "/output/uuid/scenes/frame_001.jpg",
"prompt": "Describe this scene in detail...",
"max_tokens": 800,
"file_uuid": "384b0ff44aaaa1f1",
"scene_index": 5,
"language": "en"
}
Example payload for Agent VLM:
{
"image_path": "/output/uuid/frame.jpg",
"prompt": "Analyze this frame...",
"max_tokens": 300,
"context": "User asked: What is in this scene?"
}
*/
-- 结果
result TEXT,
error TEXT,
-- 处理信息
processing_time_ms BIGINT,
retry_count INTEGER DEFAULT 0 CHECK (retry_count >= 0),
-- 时间戳
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
started_at TIMESTAMP WITH TIME ZONE,
completed_at TIMESTAMP WITH TIME ZONE,
-- 约束
CONSTRAINT valid_processing_time CHECK (
processing_time_ms IS NULL OR processing_time_ms >= 0
)
);
-- 索引 (支持高效查询)
-- 1. Poll 索引: 用于 Worker 拉取待处理消息
-- 按优先级和创建时间排序,只索引 pending 状态
CREATE INDEX idx_vlm_requests_poll ON vlm_requests (
request_type, priority, created_at
) WHERE status = 'pending';
-- 2. 状态索引: 用于监控和查询
CREATE INDEX idx_vlm_requests_status ON vlm_requests (status, created_at);
-- 3. 文件索引: 用于按文件查询请求
CREATE INDEX idx_vlm_requests_file ON vlm_requests (
(payload->>'file_uuid')
);
-- 4. 场景索引: 用于 Scene VLM 按场景查询
CREATE INDEX idx_vlm_requests_scene ON vlm_requests (
(payload->>'file_uuid'),
(payload->>'scene_index')
) WHERE request_type = 'scene_vlm';
-- 注释
COMMENT ON TABLE vlm_requests IS 'VLM request message log (Kafka-inspired design)';
COMMENT ON COLUMN vlm_requests.id IS 'Offset (auto-increment, used for tracking)';
COMMENT ON COLUMN vlm_requests.request_type IS 'Partition key (agent_vlm, scene_vlm, face_vlm)';
COMMENT ON COLUMN vlm_requests.priority IS 'Priority (0 = highest, used for priority scheduling)';
COMMENT ON COLUMN vlm_requests.status IS 'Message status (pending, processing, completed, failed, timeout)';
COMMENT ON COLUMN vlm_requests.payload IS 'Request payload (JSON format)';
COMMENT ON COLUMN vlm_requests.retry_count IS 'Retry count for failed requests';
-- 2. 死信队列
CREATE TABLE vlm_dlq (
id BIGSERIAL PRIMARY KEY,
-- 原始消息信息
original_id BIGINT NOT NULL,
original_request_type VARCHAR(20) NOT NULL,
original_priority INTEGER NOT NULL,
original_payload JSONB NOT NULL,
-- 错误信息
error TEXT NOT NULL,
retry_count INTEGER NOT NULL,
-- 时间戳
failed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- 外键 (如果原消息被删除,DLQ 记录也删除)
FOREIGN KEY (original_id) REFERENCES vlm_requests(id) ON DELETE CASCADE
);
-- 索引
CREATE INDEX idx_vlm_dlq_failed_at ON vlm_dlq (failed_at);
CREATE INDEX idx_vlm_dlq_original_id ON vlm_dlq (original_id);
COMMENT ON TABLE vlm_dlq IS 'Dead letter queue for failed VLM requests';
COMMENT ON COLUMN vlm_dlq.original_id IS 'Original request ID (offset)';
COMMENT ON COLUMN vlm_dlq.error IS 'Error message';
COMMENT ON COLUMN vlm_dlq.retry_count IS 'Number of retries before failure';
-- 3. Consumer Offset 追踪 (类似 Kafka __consumer_offsets)
CREATE TABLE vlm_consumer_offsets (
id SERIAL PRIMARY KEY,
-- Consumer ID (worker_0, worker_1, worker_2)
consumer_id VARCHAR(50) NOT NULL UNIQUE,
-- 当前 Offset
current_offset BIGINT NOT NULL DEFAULT 0,
-- 统计信息
total_processed BIGINT DEFAULT 0,
total_succeeded BIGINT DEFAULT 0,
total_failed BIGINT DEFAULT 0,
-- 时间戳
last_poll_at TIMESTAMP WITH TIME ZONE,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- 初始化 Workers
INSERT INTO vlm_consumer_offsets (consumer_id) VALUES
('worker_0'), -- Agent VLM (P0, highest priority)
('worker_1'), -- Scene/Face VLM (P1)
('worker_2'); -- Scene/Face VLM (P1)
COMMENT ON TABLE vlm_consumer_offsets IS 'Consumer offset tracking (similar to Kafka __consumer_offsets)';
COMMENT ON COLUMN vlm_consumer_offsets.consumer_id IS 'Worker ID (worker_0, worker_1, worker_2)';
COMMENT ON COLUMN vlm_consumer_offsets.current_offset IS 'Current processing offset';
COMMENT ON COLUMN vlm_consumer_offsets.total_processed IS 'Total processed requests';
COMMENT ON COLUMN vlm_consumer_offsets.total_succeeded IS 'Successfully processed requests';
COMMENT ON COLUMN vlm_consumer_offsets.total_failed IS 'Failed requests';
-- 4. 监控视图
CREATE VIEW vlm_queue_stats AS
SELECT
request_type,
status,
COUNT(*) as count,
AVG(processing_time_ms) as avg_processing_time_ms,
MIN(processing_time_ms) as min_processing_time_ms,
MAX(processing_time_ms) as max_processing_time_ms
FROM vlm_requests
WHERE status IN ('pending', 'processing', 'completed')
GROUP BY request_type, status;
COMMENT ON VIEW vlm_queue_stats IS 'Queue statistics for monitoring';
-- 5. 辅助函数: 获取下一个 offset
CREATE OR REPLACE FUNCTION get_next_vlm_offset()
RETURNS BIGINT AS $$
BEGIN
RETURN nextval('vlm_requests_id_seq');
END;
$$ LANGUAGE plpgsql;
COMMENT ON FUNCTION get_next_vlm_offset() IS 'Get next VLM request offset (for pre-allocation)';
-- 6. 触发器: 自动更新 updated_at
CREATE OR REPLACE FUNCTION update_vlm_consumer_offsets_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_update_vlm_consumer_offsets_updated_at
BEFORE UPDATE ON vlm_consumer_offsets
FOR EACH ROW
EXECUTE FUNCTION update_vlm_consumer_offsets_updated_at();
-- 7. 分区表 (可选,未来性能优化)
-- 如果请求量很大,可以按 request_type 分区
-- 目前先不分区,等数据量上来后再优化
-- ============================================
-- 验证 Schema
-- ============================================
-- 验证表创建
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'vlm_requests') THEN
RAISE EXCEPTION 'Table vlm_requests not created';
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'vlm_dlq') THEN
RAISE EXCEPTION 'Table vlm_dlq not created';
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'vlm_consumer_offsets') THEN
RAISE EXCEPTION 'Table vlm_consumer_offsets not created';
END IF;
RAISE NOTICE 'VLM queue schema created successfully';
END
$$;
-- ============================================
-- 示例数据 (测试用)
-- ============================================
-- 插入测试消息
INSERT INTO vlm_requests (request_type, priority, payload) VALUES
('agent_vlm', 0, '{"image_path": "/test/frame.jpg", "prompt": "Test", "max_tokens": 300}'),
('scene_vlm', 1, '{"image_path": "/test/scene.jpg", "prompt": "Test scene", "max_tokens": 800, "file_uuid": "test-uuid", "scene_index": 0}');
-- 清理测试数据
DELETE FROM vlm_requests WHERE id <= 2;
-- ============================================
-- Migration 完成
-- ============================================
-- VLM Request Queue Schema 创建完成
-- 支持优先级调度、死信队列、Offset 追踪
-- 基于 Kafka 设计理念,适应单机 PostgreSQL 部署
-- 未来可扩展到分布式环境