今日已更新 329 条资讯 | 累计 40774 条内容
关于我们

标签:#orm

找到 427 篇相关文章

AI 资讯

What a Kubernetes controller actually does when you break something

⚡ TL;DR Four things about controller mechanics are widely half-understood: what Reconcile receives, where its work comes from, what a periodic resync is, and what a predicate turns off. I built an operator, broke it five ways, and measured each mechanism directly. The reconcile function runs in 2.71ms mean, 77/77 under 25ms , a short resync period costs zero additional API requests , and GenerationChangedPredicate cut steady-state reconciles by 48.5% without touching live repair at all. That last combination is the one that matters at scale. Repo, raw data, and harness: kirPoNik/k8s-drift-operator . 🧩 The four barriers Everyone who runs Kubernetes knows the platform repairs itself. Delete a pod, it comes back. Scale a Deployment by accident, something puts it back. Almost nobody who relies on that property can say how it works, and the gaps are specific and consequential. I keep meeting the same four: People think a controller is told what changed. It is not, and the reason it is not is the single most important design decision in Kubernetes. People think a controller polls the API server. It does not, and knowing what it does instead tells you where your API load actually comes from. People think a resync is a re-check against the cluster. It is not, which is why a short resync period is nearly free — and why the number that is expensive sits somewhere else entirely. People treat a predicate as a pure optimisation. It is a filter with a silent cost, and the cost is not the one the documentation warns you about first. So I built the smallest system that has the self-healing property, broke it on purpose ten times per failure mode, and instrumented each of those four mechanisms until I could state what it does rather than what it is said to do. What I built. One CRD called Echo , holding an image, a replica count, and a greeting. A controller keeps three child objects in sync with it — a Deployment, a Service, and a ConfigMap holding the greeting — with owner referen

2026-09-08 原文 →
AI 资讯

Three PHP-FPM failure modes and how to actually diagnose them

Tuning guides talk about throughput. Nobody pages you about throughput. They page you about symptoms, and the useful skill is mapping a symptom back to a cause before you spend money on hardware. Three failure modes account for most of what I find on inherited servers. Each has a distinct signature. The 502 nobody can reproduce Server has 8GB. PHP-FPM is set to 100 workers. Each worker uses 60MB under load. That's 6GB of PHP, plus MariaDB, plus Nginx, plus the OS. Under normal traffic you never approach 100 workers, so it looks fine for months. Then a marketing email goes out, concurrency spikes, and the kernel runs out of memory. The OOM killer picks a process and terminates it, usually the biggest one, which is a PHP-FPM worker holding an in-flight request. User gets a 502. The application log has nothing, because the process died before it could write anything. Nginx logs recv() failed (104: Connection reset by peer) . Ten minutes later everything looks normal. sudo dmesg -T | grep -i "killed process" sudo journalctl -k | grep -i oom Hits there mean you don't have a mystery. You have a pm.max_children value nobody checked against real memory. The site that degrades all day and resets overnight TTFB is 180ms at 8am. By 4pm it's 900ms. Nobody deployed. Overnight it's fast again because something restarted PHP-FPM. That's OPcache running out of room. When the cache fills, it stops caching new scripts or wipes and rebuilds, and every miss pays full parse-and-compile again. It degrades gradually, which is why it goes unnoticed for months. The counters are oom_restarts and hash_restarts from opcache_get_status() . Here's the part that trips people up. OPcache state is per SAPI. Run that function from the CLI and you're reading the CLI cache, which is empty, separate, and tells you nothing about your site. You have to ask through PHP-FPM. <?php // drop in webroot, lock to your IP, delete when done $allowed = [ '203.0.113.42' ]; if ( ! in_array ( $_SERVER [ 'REMOTE_ADDR'

2026-09-07 原文 →
AI 资讯

Embedding a web UI into a native desktop application comes with a price

I thought embedding a web UI into a native desktop application would be the easy part. After all... macOS has WebKit. Linux has GTK WebKit. Windows has WebView2. One API per platform, smaller installers, native look & feel. Sounds perfect. Then reality arrived. macOS 🍎 Honestly, this was the easiest platform. System WebKit is there. It behaves consistently. No additional runtime. No installer surprises. Exactly what you'd expect from a platform component. 10/10 Linux 🐧 Things became... more interesting. GTK WebKit works, but suddenly packaging starts to matter. An AppImage built on one distribution may refuse to start on another because some required WebKitGTK library isn't available. Your application itself is perfectly fine. The user's system just doesn't happen to provide exactly the version your build expects. You quickly discover that "works on my machine" has many regional dialects. 7/10 Windows 🪟 This one surprised me the most. Unlike macOS, the web view isn't really just "there." Using WebView2 means depending on the Edge WebView runtime. If the runtime isn't installed, congratulations—you now need another installer. So your installer may install something whose purpose is to allow your application to display HTML. Not exactly the dependency story I was hoping for. 2/10 Meeting in the middle At some point I asked myself: Why am I spending time debugging operating-system packaging instead of building my application? So I tried CEF (Chromium Embedded Framework). Yes... The application becomes larger. Quite a bit larger. But in exchange: • Same rendering engine everywhere. • Same JavaScript engine everywhere. • Same debugging experience. • Same HTML/CSS behavior. • No Linux WebKit dependency lottery. • No separate WebView runtime installation on Windows. • One code path across all desktop platforms. Ironically, shipping your own browser turned out to be simpler than relying on the browser already "provided" by the operating system. It's one of those engineering

2026-09-07 原文 →
AI 资讯

Why Adding an Index Won't Fix Your Slow COUNT(*) in PostgreSQL

COUNT(*) looks like a trivial operation: SELECT COUNT ( * ) FROM orders ; The query asks for a single number, but that doesn't mean PostgreSQL can produce it with a constant-time read from some internal counter. When we need an exact count, PostgreSQL has to determine how many rows are actually part of the visible result set for that query. On large tables, that work can become a meaningful chunk of total execution time. And the problem doesn't just go away by throwing an index at it. The useful question isn't "do I have an index?" It's: How many rows does PostgreSQL actually need to examine to compute this count — and can that work be reduced? Why COUNT(*) Can Be Expensive in PostgreSQL PostgreSQL uses MVCC — Multi-Version Concurrency Control — to manage concurrent access to data. That's what lets multiple transactions work at the same time while each sees a consistent view of the database. But it also means row visibility depends on the snapshot the query is running under. That's why PostgreSQL can't answer: SELECT COUNT ( * ) FROM orders ; by simply reading an exact counter stored somewhere in the table's metadata. To return an exact result, it has to process the rows — or an index structure representing those rows — and determine which ones are part of the visible result. On a small table, that cost is invisible. On a table with millions of rows, the amount of work starts to matter. Which leads to an important distinction: returning a single row from COUNT(*) does not mean processing a single row. How to Analyze a COUNT with EXPLAIN ANALYZE Before reaching for an index, it's worth looking at what PostgreSQL is actually doing. Say we have this query: SELECT COUNT ( * ) FROM orders WHERE status = 'completed' ; We can analyze it with: EXPLAIN ( ANALYZE , BUFFERS ) SELECT COUNT ( * ) FROM orders WHERE status = 'completed' ; The goal isn't to hunt for an Index Scan by default. Worth checking instead: the scan type estimated rows vs. actual rows processed rows discard

2026-09-07 原文 →
AI 资讯

Why XopProtector Is a Lightweight Alternative to Commercial Android App Protection

Android App Protection Shouldn't Come at the Cost of Performance: The Lightweight Approach of XopProtector Android application protection has always involved a difficult trade-off. Stronger protection often means: Larger APK size Longer protection/build time Higher runtime overhead Slower application startup For large Android applications, these costs can become especially noticeable. XopProtector takes a different approach: strong protection with a focus on build efficiency, small APK overhead, and fast runtime startup. 300MB APK Protection in Under 5 Minutes For large Android projects, protection time is an important part of the development workflow. If protecting a 300MB APK takes 10–20 minutes or longer, it can significantly slow down: CI/CD pipelines Regression testing Beta releases Production builds Daily development XopProtector is designed to minimize unnecessary processing and optimize the protection pipeline for DEX, native libraries, and protected runtime data. In our testing environment, a 300MB-class APK can be protected within 5 minutes . This makes APK protection much more practical for frequent builds and automated CI/CD workflows. Actual protection time depends on hardware, APK structure, number of DEX files, native libraries, and the selected protection configuration. Small APK Size Overhead Protection should not mean dramatically increasing the APK size. Some protection solutions introduce significant additional runtime components or duplicated protected data, which can result in noticeable APK growth. XopProtector focuses on keeping the protection runtime lightweight and minimizing unnecessary additional data. The goal is simple: Original APK ↓ XopProtector ↓ Protected APK Protection ↑ Security ↑ APK overhead ↓ Build time ↓ Runtime overhead ↓ For large applications, keeping the size overhead low can be just as important as the protection itself. Fast Startup After Protection Build time is only one part of the equation. What users ultimately exper

2026-09-07 原文 →
AI 资讯

Why I Rewrote Four Services in Go

I had four small services. Each one was a Model Context Protocol adapter — a thin wrapper that lets an AI agent call out to some external thing. One talked to Replicate for image generation. One talked to a Nostr-friendly social poster. One was a Git-aware research helper. One was a Tavily-powered web search. They were all written in Python. They all ran on Knative on a small Kubernetes cluster. They all worked. And they were all just slightly too slow to use. A six-second cold start is fine for nothing. It is the precisely wrong amount of time — slow enough to be noticed, fast enough to feel almost loaded. An AI agent waiting six seconds for a single tool call does not know it is waiting for a cold start; it just knows the tool is sluggish. The user does not know either. The user just thinks the agent is broken. And six seconds was a good day. Some of the services took longer. So I rewrote them in Go. This is what that cost me, and what the measurements actually were before and after. The actual problem Cold starts on serverless platforms are an old problem with a well-known shape. The platform spins your container up only when traffic arrives, so the first request after an idle period pays the full startup tax — image pull (or warm cache hit), container start, language runtime initialisation, application bootstrap. For Python, application bootstrap is where the bill arrives. The interpreter has to start. import statements run. The dependency tree gets walked. If you have ever wondered why a hello world Flask app feels so much heavier than a hello world Go binary, this is why. Python is doing real work before your code runs. Go has already started. On a small Kubernetes cluster — small as in I am paying for it personally — you do not keep a fleet of warm replicas around. You scale-to-zero. You scale-to-zero because that is the entire point of using serverless on small infrastructure. The trade-off is that every idle service eats a cold start the next time it is inv

2026-09-06 原文 →
AI 资讯

It Fit in Memory and Was Still Unusable — Do the Bandwidth Arithmetic First

Originally published on hexisteme notes . "Will it fit on our hardware?" is the wrong first question. It's the one everyone asks, because it's free to answer — the thing either loads or it doesn't. Throughput costs you a measurement. So the capacity gate passes, and it feels like the decision is made. The measurement Mac Mini M4, 24GB unified memory, ~120GB/s memory bandwidth. A 27B model, IQ4_XS quantized, 15GB on disk. Capacity gate: pass. Metal's recommendedMaxWorkingSet is 17.76GB, the model is 15GB, ollama ps reports 100% GPU resident. No swap, no spillover. By every "does it fit" criterion this is a clean win. Generation: 5.6 tokens/second. That's not a usable interactive worker. It's barely a usable batch worker. And nothing about the capacity check hinted at it. The arithmetic that would have told me in advance Autoregressive generation reads the entire model's weights once per token. So: ceiling ≈ memory bandwidth ÷ bytes touched per operation = 120 GB/s ÷ 15 GB = 8 tokens/second Measured 5.6 against a ceiling of 8. Ratio 0.70. That ratio is the whole verdict. When measured throughput is a large fraction of the arithmetic ceiling, you are bandwidth-bound , and you now know something concrete: the bottleneck is not your configuration, not memory pressure, not thermal throttling. It's how fast bytes move. Rule of thumb I now use: ratio ≥ 0.5 → bandwidth-bound, and size-reduction fixes are dead. Why "just quantize harder" doesn't work The natural move when capacity is tight is to shrink. Lower quantization, smaller batch, heavier compression. It's the reflex, and in a bandwidth-bound regime it's close to useless. I was considering Q3_K_M at 13.8GB. Run the same division: 120 ÷ 13.8 = 8.7 tokens/second (up from 8) Under 9% more throughput. For a real drop in output quality, because quantization error doesn't scale linearly with size the way bandwidth does — you give up more than you get, every time, in this regime. I killed that plan without downloading anythin

2026-09-06 原文 →
AI 资讯

19 OOM kills in 9 days: diagnosing a shared-hosting WordPress before the rebuild

Nineteen OOM kills in nine days. Ten WordPress apps on a 32GB shared box. One of them a client site that took a CPU spike on 14 July during a paid campaign burst, and pushed the whole tenant into the wall. This post is the diagnosis before the rebuild. What we actually found when we stopped guessing. Two layers of Cloudflare, one page cache plugin, one preloader being silently challenged, and a language subpath that was cold every time it mattered. I'm writing it partly for anyone who runs multi-tenant WordPress on Cloudways or similar, and partly as a reminder for future-me. There's a checklist at the end. Steal it. The client is anonymized throughout. Every number is real. The stack Traffic hits two Cloudflare layers before it reaches origin. Both are Cloudflare, but they're different zones on different accounts, and they own different things. [ visitor ] ↓ [ Upstream Cloudflare zone (managed by a third party) ] ← DNS, SSL, HTML edge cache ↓ [ Cloudflare Enterprise add-on sold by Cloudways ] ← WAF, bot, rate limit, AI crawler block ↓ [ Cloudways origin: nginx + PHP-FPM ] ↓ [ WordPress + WPML + Elementor + FlyingPress ] Two Cloudflares isn't a mistake. The domain has been on Cloudflare via an upstream party since before the site moved to Cloudways. When Cloudways later offered a Cloudflare Enterprise add-on for its security stack, we kept both. We manage the Cloudways side. We don't own the upstream zone, which shapes what we can and can't do without a request going out. The trap is that both layers can cache HTML, and both can serve security challenges. If nobody writes down which layer does what, they fight. Our ownership split ended up like this: Layer Owns Upstream Cloudflare (third party) DNS, SSL, HTML edge cache, purge lifecycle Cloudways CF Enterprise add-on WAF, bot management, rate limiting, AI crawler blocking, ScrapeShield, Browser Integrity Check FlyingPress Origin page cache, Cloudflare integration pointed at the upstream zone, purge rules Cloudways "

2026-09-06 原文 →
AI 资讯

Looking at what we are Building

So now that you have a basic understanding of how Terraform works , before you start running any terraform command against a real AWS account, two things need to happen: you need an identity Terraform can authenticate as, and you need a mental picture of what you're about to create, so the plan output in Part 4 isn't just a list of unfamiliar resource names. Never Use Your AWS Root User! The root user (the email/password you signed up to AWS with) can do anything , including closing the account. It should basically never be used day-to-day. Instead, create a dedicated IAM user just for this project. In real life you would create a dedicated IAM user for your CI/CD pipeline to automate deployments: AWS Console → IAM → Users → Create user (e.g. terraform-voting-app ). Do not enable AWS Console access, this user only needs programmatic access, i.e. an API key pair. The AWS managed policy AdministratorAccess is the path of least friction, and is what you should use for the IAM user to test things out. but in real life you would go with least privilege approach, learn more about it in AWS EKS IAM policy examples . On the user's Security credentials tab → Create access key → choose "Command Line Interface (CLI)". You'll get an Access Key ID and a Secret Access Key , store them somewhere safe, we will be needing them later. Give Terraform those Credentials The rule: credentials never go inside a .tf file, and never inside terraform.tfvars . So in your local machine or CI/CD pipeline you need to export AWS_ACCESS_KEY_ID , AWS_SECRET_ACCESS_KEY , and AWS_REGION as environment variables in the shell. Then you won't be needing aws configure or aws login step anywhere, the aws provider has no access_key / secret_key arguments of its own, so it falls back to the AWS SDK's standard credential chain, which checks these exact environment variables first. The AWS CLI and, later kubectl read the same variables. In my local machine I do export an env variable files using a shell scrip

2026-09-06 原文 →
AI 资讯

What actually happens in a database index (and why half of them do nothing)

Same query. Same table. Same million rows. One day it takes 4 seconds . The next day, 4 milliseconds . Nothing changed in the data. The only thing that changed was one line — you added an index . Four seconds to four milliseconds is a thousand times faster, from one line of SQL. But here's the part nobody tells you: half the indexes people add do nothing. The query stays slow, the writes get slower, and they can't figure out why. By the end of this you'll know what an index actually is — and the one rule that decides whether yours even gets used. Prefer to watch? Full walkthrough with the B-tree lookup animation: With no index: a full table scan You ask the database for one user by email. With no index, what does it do? It reads the first row. Not a match. The second row. Not a match. It keeps going — every single row — until it finds yours or runs out. A million rows, a million checks. SELECT * FROM users WHERE email = 'vlad@stack.dev' ; With no index, that WHERE line has only one way to run: look at all of them. The work grows with the table — ten times the rows, ten times the wait. That's a full table scan , and that's your four seconds. What an index actually is Most people picture an index as a copy of the table, or some kind of cache. It's neither. An index is a sorted map — just the column you search on, kept in order, with a pointer back to the full row. And the shape it's sorted into has a name: a B-tree (the default index in both Postgres and MySQL — technically a B+ tree). At the top, one node — the root . It splits into a few branches . Each branch splits again, down to the leaves , where the pointers to the rows actually live. Every node is sorted. The root doesn't hold your data — it holds signposts . Emails before "M"? Go left. "N" and after? Go right. Each step throws away half the tree, or more. You're never reading rows. You're following signs. The walk: three hops, not a million rows Watch what the lookup actually does: The root — one hop. A branc

2026-09-06 原文 →
AI 资讯

Fifty seconds for half a megabyte: the optimisation that fixed the constant, not the order

A cryptography library had a bottleneck no test could see : encrypting half a megabyte took fifty seconds. Every test passed. They had been passing for months. The cause is a trap that keeps recurring: a correct, well-documented optimisation that fixes the constant and not the order — and whose comment, precisely because it is well written, convinces the reader the problem is already solved. What the code did Quipu renders encrypted data as a sequence of symbols. To do that it converts the whole message into a single huge integer and repeatedly divides it to extract digits, the same way you would convert a base-10 number to base 2 by hand. The code did not divide one digit at a time. It carried a sensible optimisation: divide by the largest power of the base that fits in a machine word, extracting nine digits per pass instead of one. The comment explaining it opened by saying that doing it one at a time would be quadratic , and then described the improvement. All true. And the result was still quadratic: extracting nine digits per pass divides the work by nine; it does not change how the work grows. That sentence — "doing it this way would be quadratic" — reads in the past tense, as if it described the previous state. It described the current one. The measurement, which is the only thing that says so Size Time Factor per doubling 64 KiB 0.79 s — 128 KiB 3.16 s ×4.0 256 KiB 12.6 s ×4.0 512 KiB 50.7 s ×4.0 Exactly four, three times running. That is textbook quadratic: every time the input doubles, the time quadruples. Extrapolating, ten megabytes would have cost about five and a half hours . And here is the point: a correctness test sees none of this . A slow algorithm produces exactly the same bytes as a fast one. The suite stayed green, and would have stayed green forever. The fix is two hundred years old Nothing had to be invented. Divide-and-conquer radix conversion is a classical algorithm: instead of peeling digits off one end, you split the number in half — div

2026-09-06 原文 →
AI 资讯

WebForms.php 2.1 Released - DeepSeek Converted and Qwen Evaluated

WebForms.php 2.1 has been released as the PHP back-end implementation of WebForms Core 2.1. This release is different from a typical porting story. The PHP implementation was converted from the C# implementation of WebForms Core using DeepSeek, and then independently evaluated with Qwen. The process was not simply: C# → PHP It was: C# → DeepSeek conversion → manual review → Qwen evaluation → corrections → testing → release This article explains that process and some of the interesting problems that appeared during the conversion. What is WebForms.php? WebForms.php is the PHP back-end part of WebForms Core. WebForms Core is a server-driven web technology based on the Commander–Executor concept. The server generates commands that describe UI operations and execution flow. WebFormsJS , running in the browser, interprets and executes those commands. The WebForms class itself does not manipulate the browser DOM directly. It generates the WebForms Core command structure. This makes the WebForms class particularly suitable for implementation in multiple programming languages. The PHP implementation provides the same WebForms Core programming model for PHP applications. Why Convert the C# Implementation? WebForms Core already has implementations for multiple programming languages. The C# implementation is the primary reference implementation and contains a large number of methods for: DOM manipulation event management Fetch operations conditions loops state management storage browser history WebSockets SSE templates selectors Action Controls and other WebForms Core operations The WebForms class mainly generates command strings. Because of this architecture, the fundamental logic does not need to be redesigned for every language. The objective of the PHP implementation was therefore to preserve the behavior and output of the C# implementation while adapting the code to PHP conventions and language capabilities. DeepSeek Conversion I provided the C# implementation and related

2026-09-06 原文 →
AI 资讯

Stress-Testing dbx: 20 MB on the Disk, 90 Database Paths to Exercise

A database client supporting 90+ engines sounds like a dependency-management problem disguised as a UI. My late-night question was simpler: how much of that complexity does t8y2/dbx carry before the first connection? The interesting claim is its small footprint—around 20 MB—combined with desktop, CLI, Docker, AI, and MCP Server modes. That is a much different architecture from shipping one heavy client per database vendor. The real test is not today’s +420 stars; it is startup latency, resident memory, and whether an unused adapter stays out of the hot path. Under the Hood The likely execution model is a shared core with database-specific drivers around it. The desktop interface, CLI, Docker image, and MCP endpoint become different front doors to the same connection and query layers. That design has two useful consequences: Connection handling and query behavior can stay consistent across interfaces. New database support does not require duplicating authentication, result formatting, or export logic. The edge case is driver loading. If all 90+ integrations initialize eagerly, startup and memory usage will grow quickly. Lazy loading is therefore more important than the headline database count. A Minimal Measurement Pass After downloading a release binary, I used this deliberately boring check: chmod +x ./dbx /usr/bin/time -v ./dbx --help 2>&1 \ | grep -E 'Elapsed|Maximum resident' For a source checkout, the first useful inspection is: git clone https://github.com/t8y2/dbx.git cd dbx find . -maxdepth 2 \( -name 'go.mod' -o -name 'Cargo.toml' -o -name 'Dockerfile' \) -print This avoids guessing the build system and immediately exposes whether the advertised modes are separate binaries, containers, or wrappers. Trade-offs I Would Watch A compact binary does not guarantee a compact running process. TLS libraries, database drivers, schema introspection, query history, and result grids can dominate memory after startup. MongoDB and Redis also do not fit neatly into a relat

2026-09-05 原文 →
AI 资讯

IaC além do Terraform - testando infraestrutura como código

1. Código de infraestrutura também quebra Nos dois artigos anteriores desta série, vimos o OpenTofu como alternativa para provisionar infraestrutura e o Ansible para configurá-la depois de criada. Mas há uma pergunta que fica no ar em qualquer um desses fluxos: como saber, antes de rodar apply em produção, que um módulo Terraform não vai abrir uma porta que não deveria, destruir um recurso por engano, ou simplesmente ter um erro de sintaxe? Testar infraestrutura como código é tão importante quanto testar qualquer outro software — só que, diferente de uma função pura, os "efeitos colaterais" de um teste malfeito aqui podem ser uma conta de nuvem inesperada ou um serviço em produção fora do ar. Este artigo fecha a série cobrindo três camadas complementares de teste: análise estática com tflint , verificação de segurança e compliance com checkov , e testes de integração de verdade com Terratest . 2. As camadas de teste em IaC Vale pensar nessas ferramentas como camadas que rodam em momentos diferentes do ciclo de vida do código, da mais rápida/barata para a mais lenta/cara: Lint e análise estática (tflint): roda em segundos, sem precisar de credenciais de nuvem nem de rodar terraform plan . Pega erros de sintaxe, más práticas e problemas específicos de cada provider. Análise de segurança e compliance (checkov): também estática, mas focada em identificar configurações inseguras (bucket público, criptografia desabilitada, security group aberto para 0.0.0.0/0 ) comparando o código contra um catálogo de políticas. Testes de integração (Terratest): a camada mais próxima da realidade — de fato roda terraform apply num ambiente isolado, valida o resultado, e depois roda terraform destroy . Mais lento e mais caro (usa recursos reais de nuvem), mas é o único jeito de garantir que o módulo realmente funciona de ponta a ponta. Um pipeline de CI/CD maduro roda as três, nessa ordem, falhando rápido nas camadas mais baratas antes de chegar nas mais caras. 3. tflint na prática O tfli

2026-09-05 原文 →
AI 资讯

C# Concurrent Collections: A Practical Guide

Choosing a thread-safe collection is not simply a matter of replacing Dictionary<TKey, TValue> with ConcurrentDictionary<TKey, TValue> . The right choice depends on the operations you need to make atomic, the ratio of reads to writes, whether consumers must block, and whether the data can become immutable after construction. This guide explains how ordinary generic collections fail under concurrent access, then compares the main types in System.Collections.Concurrent with immutable and frozen collections. The goal is to give you enough mechanical detail to defend the choice in code review—not just a catalog of APIs. C# Concurrent Collections: Quick Selection Guide Requirement Start with Concurrent FIFO processing ConcurrentQueue<T> Concurrent LIFO processing ConcurrentStack<T> Concurrent key-based reads and updates ConcurrentDictionary<TKey, TValue> Unordered items produced and consumed by the same workers ConcurrentBag<T> Blocking or bounded producer-consumer flow BlockingCollection<T> Snapshot-style updates System.Collections.Immutable Build-once, read-many lookup data System.Collections.Frozen The table is a starting point, not a substitute for checking which compound operations must be atomic. The sections below explain the mechanics and tradeoffs behind each choice. Why C# Needs Thread-Safe Collections C# 1.0 introduced System.Collections , which includes ArrayList , Hashtable , Stack , Queue , and other collection classes. The problem is that these collections are not type-safe. They store elements as object , which can lead to type-mismatch exceptions and to performance costs from boxing and unboxing. C# 2.0 then introduced the System.Collections.Generic namespace and collection classes such as List<T> , Dictionary<TKey, TValue> , Stack<T> , and Queue<T> . These collections are type-safe, but not thread-safe. Type safety means that when you create a generic collection, you specify the type it stores as a generic type parameter. Reading an element then returns

2026-09-05 原文 →
AI 资讯

Mini book: Next-Gen Architecture Playbook: Insights and Patterns for the AI Era

This eMag examines how architects can lead with clarity in a rapidly evolving engineering world, distilling industry insights into field-tested practices for teams. Together, these stories reveal a core theme: the technology leader’s role is expanding from building systems to guiding how tech behaves and learns, while enabling engineers and organizations to bring out their best. By InfoQ

2026-09-04 原文 →
AI 资讯

# How enabling cross-origin isolation silently broke our multi-threaded WASM image compressor

A production postmortem. We shipped browser-side image compression (Rust → WASM + WebGPU), turned on cross-origin isolation for speed, and watched every format crash with compression worker crashed . Here's the root cause and the fix. The setup We built an image compressor that runs 100% in the browser — Rust compiled to WASM for the codec work, WebGPU for the heavy ML passes (background removal, denoise, watermark). No upload, so users' pixels never leave the device. Privacy is the whole selling point. For the multi-threaded code paths we rely on shared memory + atomics , which in the browser requires crossOriginIsolated . So we served the document with: Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Opener-Policy: same-origin That gives us crossOriginIsolated === true , unlocks SharedArrayBuffer , and lets the *‑threaded WASM builds actually spawn workers. The build uses a nightly toolchain ( nightly-2025-06-01 + -Z build-std ) with: RUSTFLAGS = "--cfg=... +atomics,+bulk-memory --shared-memory --import-memory" and a custom rayon handle pool ( with_turbo_pool ) instead of build_global , so we control worker lifecycle and can abort/self-heal. The incident After flipping COEP to require-corp in production, every format started crashing with the same message: compression worker crashed Not one codec — JPG, PNG, WebP, AVIF, all of them. It was a P0: the core feature was dead for every user. What made it nasty: it only reproduced under real cross-origin isolation . Local dev without COEP was fine. Staging without the header was fine. So the bug hid until it hit production traffic. Root cause The *‑threaded WASM packages spin up nested rayon workers to parallelize the codec. Under COI + COEP require-corp , those nested workers get blocked by Cross-Origin-Resource-Policy / COEP — the spawned worker script is treated as a cross-origin response without the right CORP header, so the browser refuses it. No worker → the rayon pool never initializes → the compression c

2026-09-04 原文 →
AI 资讯

Stop Timing the Happy Path

The happy path was never the bottleneck. I was timing successes and shipping a miss. Production traffic is full of misses. Would you trust a bench that never fails? An AI rewrite loves the clean try. It wraps a lookup in except KeyError. It logs the miss "for observability." It looks professional. It is also a tiny furnace. Exceptions are not cheap branches. Log formatters are not free either. I learned that the loud way. Cheap generation makes the trap faster. A model will emit a polite miss path before you blink. Technical debt used to wait for a human. Now it arrives as a helpful patch tonight. The debt is not the lookup. The debt is a story about speed with no miss mix in the graph. I needed variants, not vibes. I used MonkeyCode's free model access and free server option to draft those variants. Disclosure: This article was prepared as part of MonkeyCode's product outreach. The model proposes shapes. It does not know your miss rate. If the graph disagrees, the patch dies. The lab I actually rerun This is a pocket harness. It is not a production claim. Steal the file. Change the mix. Keep your own picture. I am not posting a trophy chart from a machine you cannot see. # miss_bench.py # Lab harness. Treat printed rows as local output, not a benchmark paper. from __future__ import annotations import logging import time import tracemalloc from typing import Callable logging . basicConfig ( level = logging . DEBUG ) log = logging . getLogger ( " hot " ) HITS = { f " user: { i } " : i for i in range ( 800 )} KEYS = [ f " user: { i } " for i in range ( 1000 )] # 20% misses on purpose def lookup_except ( key : str ) -> int | None : try : return HITS [ key ] except KeyError : log . debug ( " cache miss key=%s " , key ) return None def lookup_get_quiet ( key : str ) -> int | None : return HITS . get ( key ) def lookup_get_log ( key : str ) -> int | None : value = HITS . get ( key ) if value is None : log . debug ( " cache miss key=%s " , key ) return value def run_mix (

2026-09-04 原文 →