Engineer an FAQ/HowTo schema moderation queue: duplication controls, spam filters,…
- User
Engineer an FAQ/HowTo schema moderation queue: duplication controls, spam filters, auto‑expiry, and CTR monitoring.
Assistant
Engineer an FAQ/HowTo schema moderation queue: duplication controls, spam filters, auto‑expiry, and CTR monitoring.
The user wants an engineering design or implementation guide for an "FAQ/HowTo schema moderation queue." The key requirements are:
I need to structure this response as a system design or a technical specification. I will use a modular approach, addressing each component separately but showing how they fit into a larger workflow.
1. System Architecture Overview:
2. Component 1: Duplication Controls
3. Component 2: Spam Filters
4. Component 3: Auto-Expiry (TTL)
5. Component 4: CTR Monitoring & Quality Scoring
GET /click/faq/{id} which redirects.6. The Moderation Queue Workflow (The "Engineer" part)
I need to define the statuses: New -> Spam Check -> Duplicate Check -> Pending Review -> Published -> Monitored -> Expired.
7. Tech Stack Recommendation
8. Refinement & Edge Cases
Drafting the Output Structure:
FAQItem structure).Let's refine the "CTR Monitoring" part. Schema.org (JSON-LD) is for SEO. Google Search Console (GSC) provides the actual CTR.
Let's write the code snippets/logic in Python/Pseudo-code as it's standard for engineering designs.
Self-Correction on Duplication: Exact hash isn't enough. Semantic search is the industry standard now. I must emphasize Vector Embeddings.
Self-Correction on Expiry: Expiry shouldn't just be delete. It should trigger a re-validation workflow.
Final Polish: Use professional formatting (headers, bolding, code blocks).
(Self-Correction during drafting): The user asked for "Schema moderation". Does this mean validating the JSON-LD schema structure? Interpretation: "FAQ/HowTo schema" usually refers to the structured data type, but in the context of a "moderation queue," it implies moderating the content that generates that schema. Alternative Interpretation: A tool that validates if the user-generated schema is correct. Most likely Interpretation: A CMS feature where users submit Questions/Steps, and the system ensures they are high quality before generating the Schema.org markup. I will proceed with the Content Moderation angle.
Let's build the solution.
Section 1: Architecture Section 2: Database Design (Polymorphic or Relational) Section 3: Detailed Logic for each requirement.
Let's start writing. This is a comprehensive engineering design for a Schema Moderation Queue system. This system is designed to ingest user-generated FAQs and How-To guides, validate their quality, enforce uniqueness, and monitor their performance over time.
We will use a Python (FastAPI) context for code examples, PostgreSQL for relational data, Redis for caching/queues, and a Vector Database (like pgvector or Milvus) for semantic deduplication.
The system operates as an asynchronous pipeline. Content enters the "Ingestion" phase and moves through a series of "Gates" before reaching the "Published" state.
We need a relational structure to track the lifecycle of the content.
CREATE TYPE moderation_status AS ENUM ('pending', 'spam', 'duplicate', 'approved', 'rejected', 'expired');
CREATE TABLE schema_entries (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL,
schema_type VARCHAR(50), -- 'FAQ' or 'HowTo'
content JSONB NOT NULL, -- Stores the Question/Answer or Steps
embedding VECTOR(1536), -- For semantic search (OpenAI ada-002 dimension)
status moderation_status DEFAULT 'pending',
spam_score FLOAT DEFAULT 0.0,
ctr_score FLOAT DEFAULT 0.0, -- Click-through rate
view_count INT DEFAULT 0,
click_count INT DEFAULT 0,
last_served_at TIMESTAMPTZ, -- For auto-expiry
expires_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Index for vector similarity search
CREATE INDEX ON schema_entries USING ivfflat (embedding vector_cosine_ops);
Before checking for duplicates, we must ensure the content isn't garbage. We use a multi-layered approach.
from profanity_check import predict_prob
from pydantic import BaseModel, ValidationError
class FAQInput(BaseModel):
question: str
answer: str
async def spam_filter_engine(entry: FAQInput) -> tuple[bool, float]:
"""
Returns (is_spam, confidence_score)
"""
text_blob = f"{entry.question} {entry.answer}"
# 1. Heuristic: Link Farming
if text_blob.count('http') > 3:
return True, 0.95
# 2. Heuristic: Profanity
profanity_prob = predict_prob([text_blob])[0]
if profanity_prob > 0.8:
return True, profanity_prob
# 3. ML Model (Placeholder for external API call e.g., OpenAI Moderation or custom endpoint)
# ml_score = await external_moderation_api(text_blob)
return False, 0.0
async def ingest_entry(user_id: str, data: dict):
# Validate Schema
try:
validated_data = FAQInput(**data)
except ValidationError:
raise ValueError("Invalid Schema Structure")
is_spam, score = await spam_filter_engine(validated_data)
status = "spam" if is_spam else "pending"
# Insert into DB
query = """
INSERT INTO schema_entries (user_id, content, spam_score, status)
VALUES ($1, $2, $3, $4)
RETURNING id
"""
return await db.execute(query, user_id, json.dumps(data), score, status)
Exact string matching fails to catch "How do I reset my password?" vs "How can I reset my password?". We use Vector Embeddings.
import openai
from pgvector.sqlalchemy import Vector
async def generate_embedding(text: str):
# Assume OpenAI client is initialized
response = await openai.Embedding.acreate(
input=text,
model="text-embedding-3-small"
)
return response['data'][0]['embedding']
async def check_duplication(entry_id: str, text_content: str):
vector = await generate_embedding(text_content)
# Query DB for nearest neighbors
# We look for distance < 0.1 (high similarity) among approved items
query = """
SELECT id, content
FROM schema_entries
WHERE status = 'approved'
AND embedding <-> $1 < 0.1
LIMIT 1
"""
match = await db.fetchrow(query, str(vector))
if match:
# Update status to duplicate
await db.execute(
"UPDATE schema_entries SET status = 'duplicate' WHERE id = $1",
entry_id
)
return True
# Save embedding for future checks
await db.execute(
"UPDATE schema_entries SET embedding = $1 WHERE id = $2",
str(vector), entry_id
)
return False
FAQs and HowTos rot over time (e.g., software versions change, policies update).
expires_at date (e.g., 90 days).view_count is 0 for 30 days, trigger expiry warning.from datetime import datetime, timedelta
async def janitorial_cleanup():
"""
Runs nightly.
"""
now = datetime.utcnow()
# 1. Hard Expiry
# Mark items past their expiry date as 'expired'
await db.execute(
"UPDATE schema_entries SET status = 'expired' WHERE expires_at < $1 AND status = 'approved'",
now
)
# 2. 'Zombie' Content Detection (Low Engagement)
# If an item hasn't been clicked in 30 days, unapprove it.
zombie_threshold = now - timedelta(days=30)
await db.execute("""
UPDATE schema_entries
SET status = 'pending', expires_at = $1
WHERE last_served_at < $2
AND status = 'approved'
""", now + timedelta(days=90), zombie_threshold)
We need to ensure the content is actually helpful. We use a Decaying Average to calculate a performance score.
view_count.click_count.# FastAPI Endpoint
@app.post("/track/{entry_id}")
async def track_interaction(entry_id: str, event_type: str): # 'view' or 'click'
if event_type == 'view':
query = """
UPDATE schema_entries
SET view_count = view_count + 1,
last_served_at = NOW()
WHERE id = $1
"""
elif event_type == 'click':
query = """
UPDATE schema_entries
SET click_count = click_count + 1
WHERE id = $1
"""
await db.execute(query, entry_id)
return {"status": "ok"}
# Ranking Query (Used when fetching schemas to display)
async def get_best_schemas(query_text: str):
# Calculate CTR on the fly or use a pre-calculated column
# Order by: Similarity * (CTR Weight)
# This prioritizes content that people actually use.
return await db.fetch("""
SELECT content,
(click_count::float / NULLIF(view_count, 0)) as ctr
FROM schema_entries
WHERE status = 'approved'
ORDER BY ctr DESC
LIMIT 5
""")
This is the UI logic for the human moderators.
Queue Prioritization Algorithm: Don't show items randomly. Prioritize the queue based on:
API Endpoint for Moderators:
@app.get("/queue/next")
async def get_next_item():
# Fetch items that are pending, sorting by spam score ascending
# (We want to review clean items first, or suspicious items first depending on policy)
item = await db.fetchrow("""
SELECT * FROM schema_entries
WHERE status = 'pending'
ORDER BY created_at ASC
LIMIT 1
""")
return item
@app.post("/moderate/{entry_id}")
async def submit_moderation(entry_id: str, action: str, moderator_id: str):
if action == "approve":
await db.execute("""
UPDATE schema_entries
SET status = 'approved',
expires_at = NOW() + INTERVAL '90 days'
WHERE id = $1
""", entry_id)
# Train spam filter with this as "Ham" (good content)
elif action == "reject":
await db.execute("UPDATE schema_entries SET status = 'rejected' WHERE id = $1", entry_id)
# Train spam filter with this as "Spam"
Approved.Pending or Expired for review.