@neon/skills 3.0.11 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/README.md +18 -0
  2. package/package.json +5 -2
  3. package/plugin.json +1 -1
  4. package/skills/neon/SKILL.md +3 -11
  5. package/skills/neon/references/auth.md +0 -4
  6. package/skills/neon/references/function-triggers.md +1 -1
  7. package/skills/neon-functions/references/function-triggers.md +2 -2
  8. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/SKILL.md +42 -0
  9. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/backup-restore.md +372 -0
  10. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/bulk-loading.md +315 -0
  11. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/connection-pooling.md +310 -0
  12. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/hot-standby.md +221 -0
  13. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/indexing.md +318 -0
  14. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/logical-replication.md +610 -0
  15. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/major-version-upgrades.md +334 -0
  16. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/performance-diagnostics.md +553 -0
  17. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/query-optimization.md +294 -0
  18. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/query-patterns.md +566 -0
  19. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/schema-design.md +362 -0
  20. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/security-roles.md +489 -0
  21. package/vendor/github.com/neondatabase/postgres-skills/skills/postgres-best-practices/references/transaction-isolation.md +344 -0
  22. package/vendor/github.com/neondatabase/postgres-skills/source.json +6 -0
@@ -0,0 +1,344 @@
1
+ # Transaction Isolation Reference
2
+
3
+ ## Contents
4
+ - Isolation levels overview
5
+ - READ COMMITTED (default)
6
+ - REPEATABLE READ
7
+ - SERIALIZABLE
8
+ - Common pitfalls and surprises
9
+ - Choosing the right level
10
+ - Retry patterns for serialization failures
11
+
12
+ ## Isolation Levels Overview
13
+
14
+ PostgreSQL implements three isolation levels (READ UNCOMMITTED maps to READ COMMITTED):
15
+
16
+ | Level | Dirty reads | Non-repeatable reads | Phantom reads | Serialization anomalies |
17
+ |-------|-------------|---------------------|---------------|------------------------|
18
+ | READ COMMITTED | No | Yes | Yes | Yes |
19
+ | REPEATABLE READ | No | No | No | Yes |
20
+ | SERIALIZABLE | No | No | No | No |
21
+
22
+ ```sql
23
+ -- Check current isolation level
24
+ SHOW transaction_isolation; -- default: 'read committed'
25
+
26
+ -- Set for a single transaction
27
+ BEGIN ISOLATION LEVEL REPEATABLE READ;
28
+ -- ... work ...
29
+ COMMIT;
30
+
31
+ -- Set for the session
32
+ SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE;
33
+
34
+ -- Set per role or database (persistent)
35
+ ALTER ROLE myapp SET default_transaction_isolation = 'repeatable read';
36
+ ALTER DATABASE mydb SET default_transaction_isolation = 'serializable';
37
+ ```
38
+
39
+ ## READ COMMITTED (Default)
40
+
41
+ Each statement within the transaction sees a **fresh snapshot** — it sees all data committed before that statement began, including commits by other transactions that happened after the transaction started.
42
+
43
+ ### Behavior
44
+
45
+ ```sql
46
+ -- Transaction A -- Transaction B
47
+ BEGIN;
48
+ SELECT balance FROM accounts
49
+ WHERE id = 1; -- sees: 1000
50
+ BEGIN;
51
+ UPDATE accounts SET balance = 500
52
+ WHERE id = 1;
53
+ COMMIT;
54
+ SELECT balance FROM accounts
55
+ WHERE id = 1; -- sees: 500 (!)
56
+ -- The second SELECT sees B's commit
57
+ COMMIT;
58
+ ```
59
+
60
+ ### The Lost Update Problem
61
+
62
+ The most common surprise with READ COMMITTED — concurrent updates can silently overwrite each other:
63
+
64
+ ```sql
65
+ -- Transaction A -- Transaction B
66
+ BEGIN; BEGIN;
67
+ SELECT balance FROM accounts
68
+ WHERE id = 1; -- 1000
69
+ SELECT balance FROM accounts
70
+ WHERE id = 1; -- 1000
71
+
72
+ UPDATE accounts
73
+ SET balance = 1000 - 200 -- = 800
74
+ WHERE id = 1;
75
+ -- B blocks here until A commits
76
+ COMMIT;
77
+ UPDATE accounts
78
+ SET balance = 1000 - 300 -- = 700 (!)
79
+ WHERE id = 1;
80
+ COMMIT;
81
+ -- Final balance: 700
82
+ -- Expected (if serial): 500
83
+ -- A's withdrawal was lost!
84
+ ```
85
+
86
+ **Fixes for lost updates in READ COMMITTED:**
87
+
88
+ 1. **Use atomic SQL** — avoid read-then-write patterns:
89
+ ```sql
90
+ UPDATE accounts SET balance = balance - 200 WHERE id = 1;
91
+ ```
92
+ This is safe because the UPDATE re-evaluates `balance` from the latest committed row.
93
+
94
+ 2. **Use SELECT FOR UPDATE** — lock the row before reading:
95
+ ```sql
96
+ BEGIN;
97
+ SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
98
+ -- Other transactions block here until we commit
99
+ UPDATE accounts SET balance = balance - 200 WHERE id = 1;
100
+ COMMIT;
101
+ ```
102
+
103
+ 3. **Use REPEATABLE READ or SERIALIZABLE** — the second transaction gets a serialization error instead of silently overwriting.
104
+
105
+ ### UPDATE Re-evaluation
106
+
107
+ When an UPDATE in READ COMMITTED encounters a row locked by another transaction, it **waits** for the lock to release, then **re-evaluates** the WHERE clause against the newly committed row. If the row still matches, it proceeds with the update. If not, it skips the row.
108
+
109
+ This means UPDATE with complex WHERE clauses can behave unexpectedly:
110
+
111
+ ```sql
112
+ -- Transaction A -- Transaction B
113
+ BEGIN; BEGIN;
114
+ UPDATE orders
115
+ SET status = 'processing'
116
+ WHERE status = 'pending'
117
+ AND id = 42;
118
+ UPDATE orders
119
+ SET status = 'processing'
120
+ WHERE status = 'pending'
121
+ AND id = 42;
122
+ -- blocks, waiting for A...
123
+ COMMIT;
124
+ -- A committed: row 42 is now 'processing'
125
+ -- Re-evaluates: WHERE status = 'pending' → false
126
+ -- UPDATE 0 (silently skips the row)
127
+ COMMIT;
128
+ ```
129
+
130
+ ## REPEATABLE READ
131
+
132
+ The entire transaction sees a **single snapshot** taken at the start of the first non-transaction-control statement. Subsequent statements see the same data regardless of concurrent commits.
133
+
134
+ ### Behavior
135
+
136
+ ```sql
137
+ -- Transaction A -- Transaction B
138
+ BEGIN ISOLATION LEVEL
139
+ REPEATABLE READ;
140
+ SELECT balance FROM accounts
141
+ WHERE id = 1; -- sees: 1000
142
+ BEGIN;
143
+ UPDATE accounts SET balance = 500
144
+ WHERE id = 1;
145
+ COMMIT;
146
+ SELECT balance FROM accounts
147
+ WHERE id = 1; -- still sees: 1000
148
+ COMMIT;
149
+ ```
150
+
151
+ ### Serialization Errors
152
+
153
+ If a REPEATABLE READ transaction tries to update a row that was modified by a concurrent committed transaction, it fails:
154
+
155
+ ```sql
156
+ -- Transaction A -- Transaction B
157
+ BEGIN ISOLATION LEVEL
158
+ REPEATABLE READ;
159
+ SELECT * FROM accounts
160
+ WHERE id = 1;
161
+ BEGIN;
162
+ UPDATE accounts SET balance = 500
163
+ WHERE id = 1;
164
+ COMMIT;
165
+ UPDATE accounts
166
+ SET balance = balance - 200
167
+ WHERE id = 1;
168
+ -- ERROR: could not serialize access due to concurrent update
169
+ ```
170
+
171
+ This is **safer** than READ COMMITTED's silent re-evaluation — you know the operation failed and can retry.
172
+
173
+ ### What REPEATABLE READ Does NOT Prevent
174
+
175
+ REPEATABLE READ prevents non-repeatable reads and phantoms, but does not prevent all serialization anomalies. Write skew is still possible:
176
+
177
+ ```sql
178
+ -- Constraint: at least one doctor must be on-call
179
+ -- Doctor A and Doctor B are both on-call
180
+
181
+ -- Transaction A (REPEATABLE READ) -- Transaction B (REPEATABLE READ)
182
+ BEGIN; BEGIN;
183
+ SELECT count(*) FROM oncall
184
+ WHERE on_duty = true; -- 2
185
+ SELECT count(*) FROM oncall
186
+ WHERE on_duty = true; -- 2
187
+ UPDATE oncall
188
+ SET on_duty = false
189
+ WHERE doctor = 'A'; -- OK, 1 left
190
+ UPDATE oncall
191
+ SET on_duty = false
192
+ WHERE doctor = 'B'; -- OK, 1 left
193
+ COMMIT; COMMIT;
194
+ -- Both committed! No one is on-call.
195
+ ```
196
+
197
+ Use SERIALIZABLE to prevent write skew.
198
+
199
+ ## SERIALIZABLE
200
+
201
+ The strongest level. Transactions behave **as if they executed one at a time** (serially). PostgreSQL uses Serializable Snapshot Isolation (SSI) — an optimistic approach that detects conflicts during statement execution or at commit rather than acquiring heavy locks upfront.
202
+
203
+ ### Behavior
204
+
205
+ All the anomalies prevented by REPEATABLE READ are prevented, plus serialization anomalies like write skew:
206
+
207
+ ```sql
208
+ -- Same on-call scenario with SERIALIZABLE:
209
+ -- One of the two transactions will get:
210
+ -- ERROR: could not serialize access due to read/write dependencies among transactions
211
+ ```
212
+
213
+ ### Performance Characteristics
214
+
215
+ - Reads are not blocked — SSI tracks read/write dependencies optimistically
216
+ - Slightly higher overhead per transaction (dependency tracking)
217
+ - More serialization failures under contention (requires retry logic)
218
+ - Rarely impacts throughput in practice for OLTP workloads
219
+
220
+ ### When to Use SERIALIZABLE
221
+
222
+ - Financial calculations where correctness is paramount
223
+ - Constraint enforcement that spans multiple rows or tables
224
+ - Any case where "check then act" patterns must be atomic
225
+ - When the alternative is complex application-level locking
226
+
227
+ ## Common Pitfalls and Surprises
228
+
229
+ ### Pitfall: Assuming READ COMMITTED Is "Safe Enough"
230
+
231
+ READ COMMITTED is safe for individual statements but not for multi-statement read-then-write patterns. Any time you SELECT a value and then use it in a subsequent UPDATE/INSERT, you have a potential race condition.
232
+
233
+ ### Pitfall: Not Handling Serialization Failures
234
+
235
+ REPEATABLE READ and SERIALIZABLE can throw:
236
+ ```
237
+ ERROR: could not serialize access due to concurrent update
238
+ SQLSTATE: 40001
239
+ ```
240
+
241
+ **This is expected behavior, not a bug.** Applications must catch and retry.
242
+
243
+ ### Pitfall: Long Transactions in REPEATABLE READ/SERIALIZABLE
244
+
245
+ The snapshot is held for the entire transaction. Long transactions:
246
+ - Prevent VACUUM from cleaning dead rows visible to the snapshot
247
+ - Increase the chance of serialization failures (more time for conflicts)
248
+ - Hold SSI dependency information longer (memory overhead)
249
+
250
+ Keep transactions short regardless of isolation level.
251
+
252
+ ### Pitfall: Mixing Isolation Levels
253
+
254
+ If Transaction A is SERIALIZABLE but Transaction B is READ COMMITTED, you only get SERIALIZABLE guarantees for A's view of the data. B never sees uncommitted intermediate states, but it can observe newer committed states between statements and produce non-serializable outcomes. For full serializable behavior, **all participating transactions** must use SERIALIZABLE.
255
+
256
+ ### Pitfall: DDL and Isolation
257
+
258
+ DDL statements (ALTER TABLE, CREATE INDEX) always acquire strong locks regardless of isolation level. They can block and be blocked by other transactions normally.
259
+
260
+ ## Choosing the Right Level
261
+
262
+ | Scenario | Recommended level | Why |
263
+ |----------|------------------|-----|
264
+ | Simple CRUD, web apps | READ COMMITTED | Default is fine; use atomic SQL for updates |
265
+ | Balance transfers, inventory | READ COMMITTED + `SELECT FOR UPDATE` | Explicit row locking prevents lost updates |
266
+ | Reports reading consistent data | REPEATABLE READ | Snapshot consistency across multiple queries |
267
+ | Multi-row constraints, write skew | SERIALIZABLE | Only level that prevents all anomalies |
268
+ | High-contention counters | READ COMMITTED + atomic UPDATE | `UPDATE x SET n = n + 1` is inherently safe |
269
+
270
+ **Default to READ COMMITTED** and escalate only when you identify a specific anomaly your application cannot tolerate.
271
+
272
+ ## Retry Patterns for Serialization Failures
273
+
274
+ ### Application-Level Retry (Recommended)
275
+
276
+ ```python
277
+ # Python example (psycopg)
278
+ import random
279
+ import time
280
+
281
+ import psycopg
282
+ from psycopg.errors import DeadlockDetected, SerializationFailure
283
+
284
+ MAX_RETRIES = 5
285
+ BASE_DELAY_SECONDS = 0.01
286
+ MAX_DELAY_SECONDS = 0.5
287
+
288
+ for attempt in range(MAX_RETRIES):
289
+ try:
290
+ # This must be a top-level transaction, not a savepoint inside one.
291
+ with conn.transaction():
292
+ conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
293
+ conn.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
294
+ conn.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
295
+ break # success
296
+ except (SerializationFailure, DeadlockDetected):
297
+ if attempt == MAX_RETRIES - 1:
298
+ raise # give up after max retries
299
+
300
+ # Bounded exponential backoff with jitter reduces repeated collisions.
301
+ delay = min(MAX_DELAY_SECONDS, BASE_DELAY_SECONDS * (2 ** attempt))
302
+ time.sleep(random.uniform(delay / 2, delay))
303
+ ```
304
+
305
+ ### Key Retry Rules
306
+
307
+ 1. **Retry the entire transaction** — not just the failed statement
308
+ 2. **Re-run all reads and decision-making** — transaction inputs may no longer be valid after a conflict
309
+ 3. **Use a bounded retry count** — avoid infinite retry loops
310
+ 4. **Use bounded exponential backoff with jitter** — concurrent retriers should not repeatedly collide; tune the delays for the workload
311
+ 5. **Log retries and exhaustion** — frequent retries indicate contention or transaction-design problems
312
+ 6. **SQLSTATE 40001** is the error code to catch (`serialization_failure`)
313
+ 7. **SQLSTATE 40P01** is deadlock (`deadlock_detected`) — it can be retried, but also fix inconsistent lock ordering where possible
314
+ 8. **Do not publish external side effects before commit** — messages, emails, and API calls can otherwise be duplicated by a retry
315
+
316
+ PostgreSQL requires retrying the complete transaction and warns that multiple attempts may be needed. See [Serialization Failure Handling](https://www.postgresql.org/docs/current/mvcc-serialization-failure-handling.html).
317
+
318
+ ### PL/pgSQL Procedure for the Transaction Body
319
+
320
+ A PL/pgSQL function cannot retry a complete transaction. An `EXCEPTION` block rolls back only its subtransaction; retrying the block remains inside the same top-level transaction and uses the same transaction snapshot at REPEATABLE READ or SERIALIZABLE.
321
+
322
+ A procedure can encapsulate the database work, but the application should still own the complete transaction and retry loop:
323
+
324
+ ```sql
325
+ CREATE OR REPLACE PROCEDURE transfer_funds(
326
+ p_from_id int,
327
+ p_to_id int,
328
+ p_amount numeric
329
+ )
330
+ LANGUAGE plpgsql
331
+ AS $$
332
+ BEGIN
333
+ UPDATE accounts
334
+ SET balance = balance - p_amount
335
+ WHERE id = p_from_id;
336
+
337
+ UPDATE accounts
338
+ SET balance = balance + p_amount
339
+ WHERE id = p_to_id;
340
+ END;
341
+ $$;
342
+ ```
343
+
344
+ Invoke `CALL transfer_funds(...)` inside the application-managed transaction and retry that entire transaction from the application. A serialization failure can occur at commit, so a procedure cannot reliably catch every failure and restart itself.
@@ -0,0 +1,6 @@
1
+ {
2
+ "repository": "https://github.com/neondatabase/postgres-skills",
3
+ "commit": "02cbe6d880f35ad2fbbbff3cec42fa12057e011c",
4
+ "path": "skills/postgres-best-practices",
5
+ "sha256": "ec055c95c9812c5813ddbb78dc9c26d5cf40f9b071c875e33deb26a82f3d0dfa"
6
+ }