惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Cloudflare Blog
T
Tenable Blog
V
Vulnerabilities – Threatpost
T
Troy Hunt's Blog
SecWiki News
SecWiki News
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Secure Thoughts
Cyberwarzone
Cyberwarzone
A
Arctic Wolf
H
Heimdal Security Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
N
News and Events Feed by Topic
The Hacker News
The Hacker News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cisco Talos Blog
Cisco Talos Blog
Stack Overflow Blog
Stack Overflow Blog
J
Java Code Geeks
Forbes - Security
Forbes - Security
Security Archives - TechRepublic
Security Archives - TechRepublic
Project Zero
Project Zero
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Microsoft Azure Blog
Microsoft Azure Blog
T
Tor Project blog
WordPress大学
WordPress大学
AWS News Blog
AWS News Blog
Jina AI
Jina AI
阮一峰的网络日志
阮一峰的网络日志
Cloudbric
Cloudbric
O
OpenAI News
U
Unit 42
Google DeepMind News
Google DeepMind News
Simon Willison's Weblog
Simon Willison's Weblog
Recorded Future
Recorded Future
N
News | PayPal Newsroom
S
Schneier on Security
F
Full Disclosure
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
P
Privacy International News Feed
L
LINUX DO - 最新话题
F
Fortinet All Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
CERT Recently Published Vulnerability Notes
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Recent Announcements
Recent Announcements

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How Sarva keeps the same GPU multipler on the cost side and the earn side without the ledger drifting
Aman Sachan · 2026-06-20 · via DEV Community

Aman Sachan

Sarva is a hub-and-spoke compute grid — a FastAPI backend, a Next.js 14 dashboard, and a Python node agent that runs on contributor machines. This post is not about the hub-and-spoke pattern (that one is well-trodden). It's about the one piece of business logic I was most worried about getting right: the moment a job is assigned, how do you decide what it costs the submitter, what the node earns, and how do you make sure the audit log captures enough state to reconstruct any disagreement after the fact.

I am writing this after the third time I rewrote submit_job and complete_job. The first two versions diverged — they used different gr() lookups, different rounding, and a "credit" abstraction that quietly lost precision. This is the version that has been live on Railway for the last few weeks, and it is the one I am willing to defend.

The formula is the same on both sides, but the inputs differ

There are two multiplier functions, both tiny:

GPU_MULT = {
    "rtx-4090": 3.0, "rtx-5090": 3.0, "rtx-3090": 2.5,
    "rtx-4070": 2.5, "rtx-3060": 2.0, "rtx-2070": 2.0,
    "gtx-1080ti": 1.5, "gtx-1080": 1.5, "gtx-1660": 1.3, "cpu": 0.8
}
GEO_RATE = {"in": 0.7, "india": 0.7, "us": 1.0, "uk": 1.0, "eu": 0.95}
PLATFORM_FEE = 0.20

def qs(g: str) -> float: return GPU_MULT.get(g.lower(), 1.0)
def gr(r: str) -> float: return GEO_RATE.get(r.lower(), 1.0)

qs() is the node's quality score — set once at registration, never changes. gr() is a per-user region rate. Both functions are called on the cost side and the earn side. The catch is whose gr() you use on each side, and that asymmetry is intentional.

On submission, the cost is what the submitter pays

@app.post("/jobs/submit")
def submit_job(type: str, submitter_id: str, script: str = None,
               slices: int = 1, priority: int = 0,
               db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == submitter_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    gpu_cost = {"ml": 2.5, "gaming": 3.0, "compute": 1.0}.get(type.lower(), 1.0)
    cost = slices * gpu_cost * gr(user.region)        # ← submitter's region
    final_cost = 0.0 if user.tier == UserTier.GOD else cost
    if user.tier != UserTier.GOD and user.balance < final_cost:
        raise HTTPException(status_code=400,
            detail=f"Insufficient credits. Need {final_cost}, have {user.balance}")
    job = Job(id=job_id, type=type, status=JobStatus.PENDING,
              submitter_id=submitter_id, script=script,
              slices=slices, credits_cost=final_cost, priority=priority)
    db.add(job)
    if user.tier != UserTier.GOD:
        user.balance -= final_cost
        user.spent_total += final_cost
        tx = Transaction(... type="spend", amount=-final_cost, ...)
        db.add(tx)
    audit(db, "job_submitted", {"job_id": job_id, "type": type, "submitter_id": submitter_id})
    db.commit()

Two things to notice:

  1. gr(user.region) is the submitter's rate. A submitter in India pays 0.7x the headline price. A submitter in the US pays 1.0x. The intent is to make compute cheaper where bandwidth and power are cheaper.
  2. The Job.credits_cost is locked at submission time. If the node that eventually runs the job is in a different region, that does not retroactively change the cost. This was a deliberate decision: re-pricing mid-flight would let a malicious node wait until a "cheap" job was assigned, then run it on a "premium" node and demand re-pricing. The cost is the cost.

On completion, the earn is what the node's owner gets

@app.post("/jobs/{job_id}/complete")
def complete_job(job_id: str, result_cid: str = None, error: str = None,
                 db: Session = Depends(get_db)):
    job = db.query(Job).filter(Job.id == job_id).first()
    # ... mark COMPLETED / FAILED ...
    if job.assigned_node_id:
        node = db.query(Node).filter(Node.id == job.assigned_node_id).first()
        if node:
            node.status = NodeStatus.ONLINE
            if job.credits_cost > 0 and not error:
                earn_mult = qs(node.gpu_tier) * gr(node.region)   # ← node's region
                earned = job.credits_cost * earn_mult * (1 - PLATFORM_FEE)
                owner = db.query(User).filter(User.id == node.owner_id).first()
                if owner:
                    owner.balance += earned
                    owner.earned_total += earned
                    tx = Transaction(..., type="earn", amount=earned,
                                     job_id=job_id, ...)
                    db.add(tx)
    audit(db, "job_completed", {"job_id": job_id, "error": error})
    db.commit()

gr(node.region) here is the node's region, not the submitter's. A node in India running a job submitted by a US user gets 0.7x — the cheaper-region rate flows through to the earner. This is symmetric in spirit (cheap power → cheap earn), but the two gr() calls are in different functions, hours apart in real time, and called with different arguments. That asymmetry used to be a source of bugs. I eventually settled on the rule: "use the subject's region, always."

PLATFORM_FEE = 0.20 is taken off the top of the earn, not added to the cost. So the 20% comes from what the node would have earned, not from the submitter's pocket. This is the part where a lot of decentralized-compute projects get the framing wrong: "we take 20% from the worker" sounds bad; "the worker keeps 80% of whatever the submitter paid" sounds fine. They are the same number. The latter framing is what we ship.

The audit log is the actual safety net

The credit math is small enough to hold in your head. The reason I sleep at night is audit(db, ...). Every state-changing operation writes a row to audit_logs with a type and a data JSON blob:

def audit(db: Session, log_type: str, data: dict):
    log = AuditLog(id=uuid.uuid4().hex[:12], type=log_type, data=data)
    db.add(log)

The events I currently log: user_registered, node_registered, job_submitted, job_assigned, job_completed, topup, cashout. The data blob is whatever I have at the time of the call — it is not normalized. That is a deliberate choice. The alternative is a clean event schema, but clean event schemas are how you end up with event_v2 and a migration that nobody wants to run. The JSON blob is messy but it is complete: if a node owner and the platform disagree about whether a job ran, the audit log has the job_id, the node_id, the error field, and the timestamp. I can replay the credit math from the audit log and the immutable transactions table to figure out who owes whom what.

There is a /logs endpoint that returns the most recent 50 entries. It is the first thing I check when somebody opens a ticket.

What I deliberately did not build yet

  1. No per-job gr() snapshot on the Job row. The Job table stores credits_cost (locked), but not the gr() value at submission time. If we ever change the GEO_RATE dict and a dispute arises, the audit log + transactions table is enough to reconstruct — but it is annoying, not instant. I am 70% convinced this is fine and 30% convinced I should add a cost_gr_snapshot column to the Job row tomorrow.
  2. No reconciliation cron. The users.balance is the source of truth, but I do not yet have a job that walks every user's transactions and asserts balance == sum(tx.amount). I run this query by hand once a week. It is fine for a few hundred users. It is not fine at 10,000.
  3. No MIN_DISK_GB enforcement on assignment. The node agent reports diskFreeGb at registration but the orchestrator does not check it before handing out a job. This is on the list.
  4. God-tier bypass is a single line. final_cost = 0.0 if user.tier == UserTier.GOD else cost lets the god user submit anything for free. That is intentional for dev, but it is not gated by environment, and a single leaked god user ID in production would be a small catastrophe. I am aware.

What I'd love feedback on

The pricing formula is the single thing I would want a second pair of eyes on. Specifically:

  • Is the "use the subject's region on each side" rule defensible, or should I be using the job's region (locked at submission from the submitter) for both calls?
  • Should PLATFORM_FEE be a flat 20%, or should it scale with slices (lower for short jobs, higher for long ones) so that the platform has a stronger incentive to keep cheap jobs flowing?
  • Is the audit-log-as-JSON-blob pattern something to grow out of before we hit 1,000 users, or is it the kind of thing I can defend long-term?

Sarva is open source at github.com/AmSach/sarva — the monorepo is /backend (FastAPI + Postgres), /frontend (Next.js 14), and /node (Python agent). The backend is live on Railway, the dashboard is on Vercel, and the node agent is a single-file Python script you can run on any machine with HUB_URL and AUTH_TOKEN set.

If you have shipped a two-sided credit ledger before, I'd genuinely like to know whether the audit-blob approach scales or whether I am about to regret it. Comments welcome.


Tags: python, fastapi, opensource, distributed