A PostgreSQL UPDATE can report one processed row while the nested JSONB state you asked for is still absent. The apparent contradiction disappears once four questions are separated: did the statement match a row, what value did jsonb_set return, does that value satisfy the requested document postcondition, and did the transaction commit that value so an independent reader can see it? PostgreSQL documents both sides of the behavior: jsonb_set returns its target unchanged when an earlier path step does not exist, while UPDATE command counts include matched rows whose values did not change.
This playbook qualifies only ARRAY['profile','preferences','theme']::text[], with to_jsonb('dark'::text) as the replacement. The normal policy allows an object root and existing object-valued ancestors; theme itself may be absent. A separate repair policy may create an absent profile or preferences, but must not silently convert a scalar, array, JSON null, or SQL NULL into an object.
The fixed qualification baseline is PostgreSQL server 18.7 with psql 18.7. PostgreSQL 18.7 was released on November 12, 2026; that identifies the required patch baseline and does not claim that these jsonb_set semantics were introduced in that release.
No PostgreSQL laboratory was executed for this article. Every experimental result below is therefore EXPECTED / NOT EXECUTED. The deliverable is a reviewable procedure: reproduce the missing-parent behavior, prove the controls, reject unsupported shapes, qualify explicit ancestor construction, reconcile all thirteen cases, and assign ACCEPT, REPAIR, RERUN, or HOLD without confusing a successful SQL command with a satisfied data contract.
1. Define the document postcondition before accepting UPDATE
Treat “the UPDATE worked” as an incomplete statement. Four states matter.
A processed row means PostgreSQL counted a row as updated. The PostgreSQL 18 UPDATE documentation says the command tag is UPDATE count, and that the count includes matched rows whose values did not change. The documentation also notes that BEFORE UPDATE triggers can suppress updates and alter ordinary counting assumptions; this fixture excludes triggers entirely.
A function result asks what JSONB value the SET expression produced. A desired state asks whether that value actually contains the required path and preserves the rest of the document. A committed state asks whether the transaction ended in COMMIT and whether a separate reader subsequently sees the expected complete value. UPDATE ... RETURNING exposes the new row produced by the statement, but transaction disposition remains a separate checkpoint.
The contract here is intentionally narrow:
ARRAY['profile','preferences','theme']::text[]must resolve to the JSON string "dark". Existing tenant, active, profile.name, and profile.preferences.locale members must survive when they existed beforehand. The patch must not invent name or locale when they were absent.
That distinction makes J04 and J06 essential comparisons. J04 starts without profile; the requested path remains unsatisfied even though a raw jsonb_set(..., true) expression is expected to return a valid JSONB value. J06 already contains "theme":"dark"; unchanged content is therefore exactly the desired state. “Changed” is not the acceptance criterion. “Matches the independently declared postcondition” is.
The ORM boundary is deliberately excluded. SQLAlchemy nested JSON change tracking concerns whether an application-side mutation is detected and turned into SQL; this playbook begins after SQL is already being evaluated by PostgreSQL. The neighboring article explicitly separates in-memory mutation, ORM dirty tracking, emitted SQL, and later persistence, which is a different failure surface.
EXPECTED / NOT EXECUTED: J04 should reproduce a diagnostically successful missing-parent no-change case but is not acceptable for the requested application patch. J06 should reproduce unchanged content that is acceptable because the requested state was already present.
2. Pin the PostgreSQL fixture and its ownership
Use a newly created database owned for this disposable qualification. Do not run these commands against production, a shared staging database, a replica, a pool, or a database where another writer is operating. The table is intentionally ordinary:
CREATE TABLE profiles (
id integer PRIMARY KEY,
doc jsonb
);There are no triggers, rules, generated mutation layers, ORM sessions, UPDATE ... FROM joins, background workers, or concurrent writers. The fixture has one writer and, after each committed transaction of interest, an independent ordinary reader.
PostgreSQL 18.7 is the required server patch and psql 18.7 is the required client patch. The documentation selector /docs/18/ is not runtime evidence. PostgreSQL's 18.7 release notes identify the release date as November 12, 2026 and describe it as a patch release containing fixes from 18.6; they do not establish what binary is actually running on your host.
A reproducible shell wrapper can create and capture the owned fixture:
set -euo pipefail
export LAB_DB='jsonb_set_parent_lab'
export LAB_OWNER="${PGUSER:?set PGUSER to the owned lab role}"
export ARTIFACT_DIR="$PWD/evidence-jsonb-set-18_7"
mkdir -p "$ARTIFACT_DIR"
psql --version | tee "$ARTIFACT_DIR/psql-version.txt"
sha256sum ./setup.sql ./cases.sql \
| tee "$ARTIFACT_DIR/source-sha256.txt"
createdb --owner="$LAB_OWNER" "$LAB_DB"
psql -X \
--dbname="$LAB_DB" \
--set=ON_ERROR_STOP=1 \
--file=setup.sql \
2>&1 | tee "$ARTIFACT_DIR/setup.transcript"
psql -X \
--dbname="$LAB_DB" \
--set=ON_ERROR_STOP=1 \
--file=cases.sql \
2>&1 | tee "$ARTIFACT_DIR/cases.transcript"set -o pipefail prevents tee from hiding a failing psql pipeline. The SQL files are hashed so the reviewed scripts can be tied to the captured transcript. If a package artifact or container image supplies PostgreSQL, record its actual package checksum or immutable image digest in the same evidence directory. No package or container digest is available in this article, and none is invented.
Capture the actual runtime before admitting a case
psql -X prevents startup files from being read. ON_ERROR_STOP makes script processing stop after an error instead of continuing. psql exposes startup variables including VERSION, VERSION_NAME, and numeric VERSION_NUM, and its SQLSTATE variable reports the most recent failed-query state or 00000 when no failure has occurred.
Put runtime admission at the beginning of setup.sql:
\set ECHO all
\set ON_ERROR_STOP on
\set VERBOSITY verbose
\pset pager off
\echo psql_full_version=:VERSION
\echo psql_version_num=:VERSION_NUM
SELECT (:VERSION_NUM::integer = 180007) AS psql_ok
\gset
\if :psql_ok
\echo 'psql admission: 180007'
\else
\echo 'HOLD: psql VERSION_NUM is not 180007'
\quit 3
\endif
SELECT (
current_setting('server_version_num')::integer = 180007
) AS server_ok
\gset
\if :server_ok
\echo 'server admission: 180007'
\else
\echo 'HOLD: server_version_num is not 180007'
\quit 4
\endif
SELECT
version() AS server_build,
current_setting('server_version') AS server_version,
current_setting('server_version_num') AS server_version_num,
current_database() AS database_name,
current_user AS current_user,
session_user AS session_user,
inet_server_addr() AS server_addr,
inet_server_port() AS server_port,
pg_backend_pid() AS backend_pid;
CREATE TABLE profiles (
id integer PRIMARY KEY,
doc jsonb
);There is no expected-error window in this fixture. Gate cases are rejected before an unsafe patch UPDATE is attempted; ordinary SQL errors are qualification failures, not expected observations.
A run on another patch level is not silently generalized to 18.7. Label it separately and RERUN the intended baseline.
EXPECTED / NOT EXECUTED: runtime admission requires both numeric version checks to equal 180007, plus preserved full client/server build strings and connection identity. No such runtime evidence exists in this article.
3. Freeze thirteen expectations independently of the implementation
The oracle must exist before the mutation SQL is reviewed. PostgreSQL's jsonb representation does not preserve insignificant whitespace or object-key order, so complete-document assertions should compare JSONB values semantically rather than demand byte-for-byte reproduction of the authored source text.
Freeze these authored literals:
F1 = {"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"light"}},"active":true}
F2 = {"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en"}},"active":true}
F3 = {"tenant":7,"active":true}
F4 = {"tenant":7,"profile":{"name":"Ari"},"active":true}
F5 = {"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"dark"}},"active":true}
F6 = {"tenant":7,"profile":"legacy","active":true}
F7 = {"tenant":7,"profile":{"name":"Ari","preferences":null},"active":true}
F8 = SQL NULL
F9 = []
E1 = {"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"dark"}},"active":true}
E2 = {"tenant":7,"profile":{"preferences":{"theme":"dark"}},"active":true}
E3 = {"tenant":7,"profile":{"name":"Ari","preferences":{"theme":"dark"}},"active":true}F8 is an SQL null in the doc column, not the JSON literal null. That distinction remains visible throughout admission and reconciliation.
Case / row ID | Before | Intervention | Expected full final document | Interpretation | Status |
J01 / 101 | F1 | Raw jsonb_set, true; commit | E1 | Existing leaf replaced; siblings retained | EXPECTED / NOT EXECUTED |
J02 / 102 | F2 | Raw jsonb_set, true; commit | E1 | Missing final member created | EXPECTED / NOT EXECUTED |
J03 / 103 | F2 | Raw jsonb_set, false; commit | F2 | Negative control: final member remains absent | EXPECTED / NOT EXECUTED |
J04 / 104 | F3 | Raw jsonb_set, true; commit | F3 | Missing profile prevents requested nested state | EXPECTED / NOT EXECUTED |
J05 / 105 | F4 | Raw jsonb_set, true; commit | F4 | Missing preferences prevents requested nested state | EXPECTED / NOT EXECUTED |
J06 / 106 | F5 | Raw jsonb_set, true; commit | E1 | Already satisfied; unchanged content acceptable | EXPECTED / NOT EXECUTED |
J07 / 107 | F6 | Object-only admission gate | F6 | Reject scalar ancestor; no patch UPDATE | EXPECTED / NOT EXECUTED |
J08 / 108 | F7 | Object-only admission gate | F7 | Reject JSON-null ancestor; no patch UPDATE | EXPECTED / NOT EXECUTED |
J09 / 109 | F8 | Object-only admission gate | SQL NULL | Reject SQL-null root; no patch UPDATE | EXPECTED / NOT EXECUTED |
J10 / 110 | F9 | Object-only admission gate | F9 | Reject array root; no patch UPDATE | EXPECTED / NOT EXECUTED |
J11A / 111 | F3 | Approved absent-parent repair; commit | E2 | Create only absent profile/preferences objects | EXPECTED / NOT EXECUTED |
J11B / 112 | F4 | Approved absent-parent repair; commit | E3 | Preserve profile.name; create preferences | EXPECTED / NOT EXECUTED |
J12 / 113 | F1 | Valid patch; capture E1; rollback | F1 | RETURNING candidate does not prove committed persistence | EXPECTED / NOT EXECUTED |
Seed the fixture from those literals, not by generating expected values from the transformation under test:
INSERT INTO profiles(id, doc) VALUES
(101, '{"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"light"}},"active":true}'),
(102, '{"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en"}},"active":true}'),
(103, '{"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en"}},"active":true}'),
(104, '{"tenant":7,"active":true}'),
(105, '{"tenant":7,"profile":{"name":"Ari"},"active":true}'),
(106, '{"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"dark"}},"active":true}'),
(107, '{"tenant":7,"profile":"legacy","active":true}'),
(108, '{"tenant":7,"profile":{"name":"Ari","preferences":null},"active":true}'),
(109, NULL),
(110, '[]'),
(111, '{"tenant":7,"active":true}'),
(112, '{"tenant":7,"profile":{"name":"Ari"},"active":true}'),
(113, '{"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"light"}},"active":true}');A copied RETURNING value is not an oracle. The expected file should be independently authored and versioned before case execution. J11A and J11B remain separate identities because they prove different preservation obligations.
4. Separate missing ancestors from a missing final member
The central jsonb_set rule is precise. PostgreSQL 18 documents the function as:
jsonb_set(target jsonb, path text[], new_value jsonb [, create_if_missing boolean])The final designated item may be added when create_if_missing is true, but all earlier path steps must already exist; otherwise the target is returned unchanged.
That predicts J02 differently from J04 and J05. In J02, profile and preferences already exist, while only theme is missing. The creation flag can create that final member. In J04, the first ancestor profile is absent. In J05, profile exists but preferences is absent. In both cases an earlier path step is unavailable.
Before involving UPDATE, qualify the expression directly:
SELECT id,
doc AS before,
jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
true
) AS candidate
FROM profiles
WHERE id IN (102,104,105)
ORDER BY id;EXPECTED / NOT EXECUTED: row 102 candidate equals E1; row 104 candidate equals F3; row 105 candidate equals F4.
The corresponding false-flag control is:
SELECT jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
false
)
FROM profiles
WHERE id = 103;EXPECTED / NOT EXECUTED: J03 returns F2 because the final theme member is missing and creation is disabled.
This is a shape problem, not a JSON-syntax problem. SQLite nested JSON shape validation addresses a different boundary: a syntactically valid JSON envelope whose nested value is a string instead of the required object. Here values are already stored as PostgreSQL JSONB; the question is whether the required object ancestors exist for the path operation.
JSONB subscripting assignment is intentionally excluded. PostgreSQL documents different parent-creation behavior for subscripting, including creation of missing nested structures in cases where jsonb_set would return the target unchanged. Mixing that syntax into this fixture would therefore change the operation being qualified.
Inspect each parent with existence and type evidence
Path extraction alone is insufficient as the admission test. PostgreSQL's JSON extraction operators return SQL NULL when the requested structure cannot be matched, so one failed extraction can represent different malformed or missing states.
Capture existence and type separately:
SELECT
id,
doc IS NULL AS sql_null_root,
jsonb_typeof(doc) AS root_type,
CASE
WHEN jsonb_typeof(doc) = 'object'
THEN doc ? 'profile'
END AS profile_present,
jsonb_typeof(doc -> 'profile') AS profile_type,
CASE
WHEN jsonb_typeof(doc -> 'profile') = 'object'
THEN (doc -> 'profile') ? 'preferences'
END AS preferences_present,
jsonb_typeof(doc #> '{profile,preferences}') AS preferences_type,
doc #> '{profile,preferences,theme}' AS theme_value
FROM profiles
WHERE id BETWEEN 101 AND 113
ORDER BY id;jsonb_typeof distinguishes JSON objects, arrays, strings, and JSON null values where an actual JSONB value exists. SQL NULL must still be checked separately.
EXPECTED / NOT EXECUTED: J07 reports an object root but profile_type = 'string'; J08 reports preferences_type = 'null'; J09 reports sql_null_root = true; J10 reports root_type = 'array'.
5. Reproduce one processed row with an unchanged document
J04 is the headline case. Its source document is F3:
{"tenant":7,"active":true}The writer transaction is:
BEGIN;
UPDATE profiles
SET doc = jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
true
)
WHERE id = 104
RETURNING id, doc,
doc #> '{profile,preferences,theme}' AS requested_path;
COMMIT;EXPECTED / NOT EXECUTED: one RETURNING row appears for ID 104; doc remains semantically equal to F3; requested_path is SQL NULL; the command tag is UPDATE 1; the transaction commits.
The command count is not evidence that the nested path now exists. PostgreSQL explicitly includes matched rows whose values did not change in UPDATE count. RETURNING is stronger because it exposes the resulting row, but its expected F3 value demonstrates that the application postcondition is still false. PostgreSQL has not violated the jsonb_set contract: returning the target unchanged is the documented behavior when an earlier step is absent.
After the writer finishes, use a different ordinary connection:
psql -X --dbname="$LAB_DB" --set=ON_ERROR_STOP=1 \
-c "SELECT id, doc, doc #> '{profile,preferences,theme}' AS theme
FROM profiles WHERE id = 104;"EXPECTED / NOT EXECUTED: the independent reader sees F3 and no theme path.
J05 repeats the same reasoning with only preferences absent:
BEGIN;
UPDATE profiles
SET doc = jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
true
)
WHERE id = 105
RETURNING id, doc;
COMMIT;EXPECTED / NOT EXECUTED: UPDATE 1, one RETURNING row containing F4, and an independent post-commit read of F4.
Do not import the cause from PostgreSQL update-source provenance. That article deals with a target matched by competing UPDATE ... FROM source rows and asks which source value is authoritative. This fixture has one explicitly addressed target and no FROM clause; the relevant correctness evidence is the JSONB expression result and its postcondition.
Successfully reproducing J04 or J05 proves the negative case is understood. It does not approve that behavior for an application that requires the path to become "dark".
6. Establish the leaf-creation controls
A diagnosis is weak if only the failing shape is exercised. J01 and J02 are positive comparisons; J03 is the negative control.
J01 starts from F1 and replaces an existing leaf:
BEGIN;
UPDATE profiles
SET doc = jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
true
)
WHERE id = 101
RETURNING id, doc;
COMMIT;EXPECTED / NOT EXECUTED: UPDATE 1; one returned row; the complete document equals E1. tenant = 7, active = true, profile.name = "Ari", and preferences.locale = "en" remain present.
J02 starts from F2. Both ancestors exist and are objects, but theme does not:
BEGIN;
UPDATE profiles
SET doc = jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
true
)
WHERE id = 102
RETURNING id, doc;
COMMIT;EXPECTED / NOT EXECUTED: UPDATE 1; E1 is returned and survives committed readback. This is the control that isolates what create_if_missing=true actually permits in the chosen path: creation of the missing final member when earlier steps exist. That matches PostgreSQL's documented jsonb_set contract.
Now J03 changes only the creation flag:
BEGIN;
UPDATE profiles
SET doc = jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
false
)
WHERE id = 103
RETURNING id, doc;
COMMIT;EXPECTED / NOT EXECUTED: UPDATE 1; one returned row containing F2; committed readback remains F2.
J03 can therefore pass as a diagnostic negative control while failing the desired patch contract. The point is not to maximize “green” cases. It is to ensure each green label means what the evidence actually establishes.
The replacement value also remains fixed across these controls:
SELECT to_jsonb('dark'::text);EXPECTED / NOT EXECUTED: the value is the JSONB string "dark", not a JSON object, SQL identifier, or JSON null.
7. Recognize an already-satisfied update
J06 prevents an equally dangerous simplification: rejecting every update whose final document equals its starting document.
F5 is:
{"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"dark"}},"active":true}The requested postcondition already holds. Execute the same expression:
BEGIN;
UPDATE profiles
SET doc = jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
true
)
WHERE id = 106
RETURNING id, doc;
COMMIT;EXPECTED / NOT EXECUTED: UPDATE 1; the returned document remains semantically equal to F5, which is also semantically equal to E1. An independent reader sees E1 after commit.
This is why neither before <> after nor a “changed rows” counter can be the application gate. J04 and J06 can both produce unchanged JSONB content, yet their meanings are opposite. J04 fails because the required leaf is absent. J06 succeeds because the required leaf already equals "dark" and all required siblings remain intact.
The policy must also say whether this operation is a targeted patch or complete record replacement. JSON replacement versus retained fields illustrates the broader reason: identical-looking parsing or mutation mechanics can be correct or incorrect depending on whether omitted state is supposed to survive. This PostgreSQL fixture declares a patch: unrelated existing members must survive.
PostgreSQL JSONB comparison should be semantic. JSONB does not preserve original whitespace or object-key order, so a review must not classify harmless serialization differences as sibling loss.
Require the expected state as well as change information
Use IS NOT DISTINCT FROM for assertions that must remain total even when SQL NULL is one of the authored expectations. PostgreSQL documents IS NOT DISTINCT FROM as equality with null treated as a comparable value, avoiding the unknown result ordinary = produces with SQL nulls.
For example:
SELECT
id,
doc IS NOT DISTINCT FROM
'{"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"dark"}},"active":true}'::jsonb
AS full_document_ok,
(doc #> '{profile,preferences,theme}')
IS NOT DISTINCT FROM to_jsonb('dark'::text)
AS path_ok
FROM profiles
WHERE id IN (101,102,106);EXPECTED / NOT EXECUTED: each selected row produces explicit Boolean true for both checks after its committed case.
A leaf-only check is still insufficient: a document could contain "theme":"dark" after accidentally losing tenant, active, name, or locale. Conversely, “different from before” could approve an unrelated mutation while the requested path remains wrong. Acceptance requires the independently authored complete expected state plus the path assertion and required sibling assertions.
8. Reject unsupported parent shapes before mutation
The normal mutation policy permits an object-valued root and object-valued ancestors. It does not authorize converting an existing non-object parent into a new object merely to make traversal possible.
J07 through J10 therefore make explicit admission decisions and perform no patch UPDATE.
Use a diagnostic gate such as:
SELECT
id,
CASE
WHEN doc IS NULL
THEN 'REJECT_SQL_NULL_ROOT'
WHEN jsonb_typeof(doc) <> 'object'
THEN 'REJECT_ROOT_NOT_OBJECT'
WHEN doc ? 'profile'
AND jsonb_typeof(doc -> 'profile') <> 'object'
THEN 'REJECT_PROFILE_NOT_OBJECT'
WHEN (doc ? 'profile')
AND jsonb_typeof(doc -> 'profile') = 'object'
AND (doc -> 'profile') ? 'preferences'
AND jsonb_typeof(doc #> '{profile,preferences}') <> 'object'
THEN 'REJECT_PREFERENCES_NOT_OBJECT'
ELSE 'ADMIT_SHAPE'
END AS admission
FROM profiles
WHERE id IN (107,108,109,110)
ORDER BY id;EXPECTED / NOT EXECUTED: J07 records REJECT_PROFILE_NOT_OBJECT; J08 records REJECT_PREFERENCES_NOT_OBJECT; J09 records REJECT_SQL_NULL_ROOT; J10 records REJECT_ROOT_NOT_OBJECT.
The reasons are materially different. F6 contains an existing scalar string at profile. F7 contains JSON null at preferences; that is an actual JSON value, not SQL NULL. F8 is SQL NULL in the database column. F9 is a JSON array at the document root.
Do not repair any of those conditions by silently replacing the offending value with {}. That would turn an ancestor-creation policy into destructive type coercion. If a data-contract owner wants such migration behavior, it needs a separately specified transformation and its own expected manifest.
Likewise, do not rely on informal assumptions about SQL expression evaluation order to make an unsafe branch “probably harmless.” Admission should first classify the document, then invoke mutation only for an admitted case. Explicit predicates and explicit Boolean tests make the policy reviewable. PostgreSQL's comparison documentation is particularly relevant where nullability could otherwise yield three-valued Boolean results.
Keep rejection evidence separate from skipped work
A rejected case needs its own evidence record:
Case | Before | Decision | Patch UPDATE | Status |
J07 | F6 | scalar profile rejected | not invoked | EXPECTED / NOT EXECUTED |
J08 | F7 | JSON-null preferences rejected | not invoked | EXPECTED / NOT EXECUTED |
J09 | F8 | SQL-null root rejected | not invoked | EXPECTED / NOT EXECUTED |
J10 | F9 | array root rejected | not invoked | EXPECTED / NOT EXECUTED |
Do not invent UPDATE 0 for these cases. No patch statement is supposed to run. A case disappearing because a WHERE clause filtered it out would also be insufficient by itself: without a ledger reason, the reviewer cannot distinguish deliberate rejection from forgotten coverage.
A successful rejection means the qualification procedure correctly refused unsupported input. It does not mean F6, F7, F8, or F9 is acceptable for mutation.
9. Create absent parents only under an approved policy
The repair policy differs from the normal policy in one controlled way: an ancestor may be created when it is absent. Existing object ancestors are preserved. Existing non-object ancestors remain rejection conditions.
Do not construct the expected E2 or E3 by running the repair algorithm and treating its output as truth. The expected documents were frozen independently.
For J11A, start from F3. Build candidates outer to inner:
WITH source AS (
SELECT id, doc
FROM profiles
WHERE id = 111
),
stage_profile AS (
SELECT
id,
doc AS before,
CASE
WHEN doc ? 'profile'
THEN doc
ELSE jsonb_set(doc, '{profile}', '{}'::jsonb, true)
END AS c1_profile
FROM source
),
stage_preferences AS (
SELECT
id,
before,
c1_profile,
CASE
WHEN (c1_profile -> 'profile') ? 'preferences'
THEN c1_profile
ELSE jsonb_set(
c1_profile,
'{profile,preferences}',
'{}'::jsonb,
true
)
END AS c2_preferences
FROM stage_profile
)
SELECT
id,
before,
c1_profile,
c2_preferences,
jsonb_set(
c2_preferences,
'{profile,preferences,theme}',
to_jsonb('dark'::text),
true
) AS c3_final
FROM stage_preferences;Run this only after the separate admission gate has established that the root is an object and any present profile/preferences members are objects.
EXPECTED / NOT EXECUTED: J11A stages are F3 → {"tenant":7,"profile":{},"active":true} → {"tenant":7,"profile":{"preferences":{}},"active":true} → E2.
J11B starts from F4.
EXPECTED / NOT EXECUTED: J11B preserves "name":"Ari" in every candidate stage, adds only preferences, then adds theme, producing E3. It must not invent locale.
Once the final candidate has been inspected and asserted against the independent expectation, perform one patch UPDATE:
BEGIN;
WITH admitted AS (
SELECT id, doc
FROM profiles
WHERE id = 112
AND jsonb_typeof(doc) = 'object'
AND (
NOT (doc ? 'profile')
OR jsonb_typeof(doc -> 'profile') = 'object'
)
AND (
NOT (doc ? 'profile')
OR NOT ((doc -> 'profile') ? 'preferences')
OR jsonb_typeof(doc #> '{profile,preferences}') = 'object'
)
),
c1 AS (
SELECT id,
CASE
WHEN doc ? 'profile' THEN doc
ELSE jsonb_set(doc, '{profile}', '{}'::jsonb, true)
END AS doc
FROM admitted
),
c2 AS (
SELECT id,
CASE
WHEN (doc -> 'profile') ? 'preferences' THEN doc
ELSE jsonb_set(doc, '{profile,preferences}', '{}'::jsonb, true)
END AS doc
FROM c1
),
candidate AS (
SELECT id,
jsonb_set(
doc,
'{profile,preferences,theme}',
to_jsonb('dark'::text),
true
) AS doc
FROM c2
)
UPDATE profiles AS p
SET doc = c.doc
FROM candidate AS c
WHERE p.id = c.id
RETURNING p.id, p.doc;
COMMIT;EXPECTED / NOT EXECUTED: J11B produces one RETURNING row, command tag UPDATE 1, E3, and an independent post-commit read of E3. J11A uses the same construction for ID 111 and is expected independently to produce UPDATE 1 and E2.
Do not substitute top-level object concatenation and assume it recursively preserves nested members. PostgreSQL documents jsonb || jsonb as a nonrecursive operation: when objects are concatenated, only the top-level object structure is merged. Explicit staged construction makes each preservation boundary visible.
10. Reconcile every result with the complete expected document
A qualification run is not complete when the SQL scripts stop without error. It is complete when every expected identity reconciles against captured evidence.
The external ledger should contain at least:
Field | Evidence required |
case ID | J01 through J12, with J11A and J11B distinct |
row ID | 101–113 |
policy | raw, normal gate, repair, rollback control |
before | complete authored baseline |
path | profile/preferences/theme |
parent evidence | root/profile/preferences presence and types |
replacement | JSONB "dark" |
command | exact UPDATE or explicit “no patch UPDATE” |
command result | command tag where applicable |
RETURNING | complete row result where applicable |
expected | independent complete expected document |
final readback | independent-reader document or rollback result |
path check | explicit Boolean/path value |
sibling checks | tenant, active, name, locale where applicable |
disposition | COMMIT, ROLLBACK, or rejection |
status | EXPECTED / NOT EXECUTED until actually run |
Raw cases J01–J06 are expected to produce one processed row and one returned row, including unchanged J03–J06 cases where appropriate. J12 is also expected to return a candidate before rollback. J07–J10 record rejection rather than an UPDATE count. J11A and J11B each require their own staged-candidate record and one final UPDATE.
Use semantic complete-document comparison:
SELECT
id,
doc IS NOT DISTINCT FROM
'{"tenant":7,"profile":{"name":"Ari","preferences":{"locale":"en","theme":"dark"}},"active":true}'::jsonb
AS expected_ok
FROM profiles
WHERE id = 101;EXPECTED / NOT EXECUTED: after J01 commits, expected_ok is true.
For SQL-null J09:SELECT doc IS NOT DISTINCT FROM NULL::jsonb AS expected_ok
FROM profiles
WHERE id = 109;EXPECTED / NOT EXECUTED: expected_ok is true, with no mutation attempted.
This null-safe predicate follows PostgreSQL's documented comparison semantics and prevents SQL NULL from disappearing into an unknown Boolean result.
Treat missing evidence as an unresolved case
Keep transcripts and manifests outside the database transaction. A useful layout is:
evidence-jsonb-set-18_7/
runtime.txt
connection.txt
source-sha256.txt
package-or-image-digest.txt
setup.transcript
J01.transcript
...
J11A.transcript
J11B.transcript
J12.transcript
reader-J01.transcript
...
expected-manifest.tsv
evidence-ledger.tsvThe package-or-image digest file contains an actual digest only if such an artifact was used. Otherwise record the packaging method and mark that field not applicable; do not fabricate provenance.
Filesystem evidence is important for J12: if the only record of RETURNING E1 were stored in a table inside the same transaction, the subsequent rollback could erase the very evidence meant to prove the rollback boundary.
Require exactly thirteen distinct case identities. Reject duplicate identities, missing J11A/J11B separation, absent readbacks, absent rejection reasons, or expected documents reconstructed after execution.
Only after identities and values reconcile should counts be summarized. 13 cases present is weaker than 13 independently identified cases whose complete outcomes agree with the authored manifest.
11. Prove transaction disposition with rollback and fresh readback
RETURNING proves statement-result content, not durable transaction outcome. PostgreSQL documents that an UPDATE's RETURNING data is based on the new content of the modified row. A later rollback is a separate event.
J12 isolates that boundary:
BEGIN;
UPDATE profiles
SET doc = jsonb_set(
doc,
ARRAY['profile','preferences','theme']::text[],
to_jsonb('dark'::text),
true
)
WHERE id = 113
RETURNING id, doc;
ROLLBACK;EXPECTED / NOT EXECUTED: the RETURNING row contains E1 because the candidate is valid inside the transaction. The transaction then rolls back.
The writer must finish before the independent reader starts:
psql -X --dbname="$LAB_DB" --set=ON_ERROR_STOP=1 \
-c "SELECT id, doc
FROM profiles
WHERE id = 113;"EXPECTED / NOT EXECUTED: the independent reader sees F1, not E1.
That is the required control against treating RETURNING as a commit receipt.
For committed J01, J02, J04, J05, J06, J11A, and J11B, the reader transcript must identify the same database and row ID used by the writer. Capture connection identity in the reader as well:
SELECT current_database(),
current_user,
inet_server_addr(),
inet_server_port(),
pg_backend_pid();
SELECT id, doc
FROM profiles
WHERE id = 111;EXPECTED / NOT EXECUTED: the connection metadata ties the observation to the owned fixture, and the row readback agrees with that case's committed expectation.
This lab has one writer and makes no concurrency qualification. Atomic If-Match checks for concurrent edits addresses the distinct problem of binding a stale-write precondition atomically to a database mutation. Do not infer lost-update safety from this single-writer JSONB qualification.
12. Repair the policy without erasing the failed run
When J04 or J05 demonstrates the documented missing-ancestor behavior, preserve that evidence. Do not overwrite the transcript with a repaired run and pretend the original case never existed.
There are two legitimate policy repairs.
The first is reject missing ancestors. Require an object root, an existing object profile, and an existing object preferences. The final theme may be missing because create_if_missing=true can create the final path item once the earlier steps exist. Under this policy, J04 and J05 are rejected before mutation.
The second is permit absent-ancestor creation. Admit an absent profile or preferences, but create it explicitly outer-to-inner. If either member is present with a scalar, array, or JSON-null value, reject it. J11A and J11B qualify that repair path.
Recovery should preserve revision boundaries:
Freeze the failed run's expected manifest, SQL source hash, runtime record, transcripts, and evidence ledger.
Record the policy defect: for example, “normal patch incorrectly assumed create_if_missing=true creates intermediate ancestors.”
Obtain ownership for the replacement rule from the data-contract owner.
Revise the SQL or the admission policy under a new fixture revision.
Recreate the disposable database from authored literals rather than editing the failed rows in place.
Re-run all cases whose behavior could be affected, not only J04/J05.
Reconcile complete documents and independent readbacks again.
Assign ACCEPT only to the new revision if its evidence is complete.
A compensating update issued after an already committed incorrect state is not a rollback. It is another transaction and must be represented as such in operational records.
Recheck sibling preservation after every repair
Ancestor creation is not permission to replace whole existing objects.
For J11B, this shortcut is wrong for the declared contract:
-- Do not use as the approved repair.
jsonb_set(
doc,
'{profile}',
'{"preferences":{"theme":"dark"}}'::jsonb,
true
)It would replace the existing profile value and risk losing "name":"Ari".
Instead, the repair retains the existing profile object, adds only absent preferences, then sets the leaf.
EXPECTED / NOT EXECUTED: J11B final E3 contains tenant, active, and profile.name; it contains no invented locale.
EXPECTED / NOT EXECUTED: J11A final E2 contains tenant and active, creates profile.preferences.theme, and does not invent profile.name or preferences.locale.
Sibling checks are blocking assertions, not cosmetic diagnostics. Where the baseline contains tenant, active, name, or locale, accidental loss is REPAIR/HOLD-worthy even if the final theme is correct.
Likewise, the repair must never transform J07's "profile":"legacy" or J08's JSON-null preferences into objects. Those inputs remain rejected.
Cleanup is restricted to owned fixture objects:
dropdb "$LAB_DB"EXPECTED / NOT EXECUTED: cleanup removes only the disposable database explicitly created for this qualification. Evidence files remain outside it.
13. Assign ACCEPT, REPAIR, RERUN or HOLD from evidence
The release decision follows the selected document policy, not whether PostgreSQL reproduced its documented behavior.
Decision | Use when | Required action |
ACCEPT | Required runtime is admitted; all 13 identities have complete evidence; full expected documents, path checks, sibling checks, transaction dispositions, and independent readbacks agree with the selected rejection/creation policy | Preserve evidence and approve this bounded single-writer JSONB mutation policy |
REPAIR | SQL handling is inadequate: missing parents are accidentally tolerated, required siblings are lost, unsupported parent types are coerced, or the postcondition is incomplete | Correct the policy or construction; create a new fixture revision and qualify again |
RERUN | Runtime patch differs, script/source hash changed, case evidence is incomplete/corrupted, reader identity is wrong, or capture procedure invalidates conclusions | Rebuild the disposable fixture and execute the full affected qualification under clearly labelled conditions |
HOLD | Intent is unknown, expected manifest is disputed, observations contradict documentation or authored expectations, repair ownership is absent, or evidence cannot establish transaction disposition | Stop release decision until contradiction or ownership is resolved |
A native no-change result for J04 is not deployment acceptance. It would merely confirm that the negative case behaves as predicted.
Contradictory evidence must not be rationalized away. If, for example, a verified 18.7 run shows J04 creating missing intermediate objects despite using the exact raw jsonb_set expression above, HOLD the conclusion, preserve the complete transcript and runtime provenance, and investigate the mismatch against PostgreSQL's documented rule that earlier path steps must exist.
Responsibilities should be distinct. The SQL author owns executable syntax, version gates, source hashes, candidate construction, and evidence capture. The data-contract owner decides whether missing ancestors are rejected or deliberately created and which siblings must survive. The reviewer independently checks runtime admission, thirteen-case completeness, expected-versus-final comparisons, transaction disposition, and the final decision.
For this article itself, the correct decision is HOLD for observational acceptance: no authorized PostgreSQL 18.7/psql 18.7 run occurred. All laboratory outcomes remain EXPECTED / NOT EXECUTED. The documented semantics are strong enough to define the procedure, but they are not a substitute for the requested runtime evidence.
14. Build the database judgment behind the release gate
The operational lesson is narrower than “check your UPDATE.” Treat row selection, function result, document postcondition, and committed persistence as separate evidence boundaries. PostgreSQL documents why a missing intermediate JSONB path can leave jsonb_set unchanged and why an UPDATE 1 tag can coexist with that result; the release gate must decide whether that documented behavior satisfies your own document contract.
For this fixture, the defensible policy is explicit: either reject absent parents, or create only absent object ancestors outer-to-inner while preserving existing objects and all required siblings. Reject incompatible existing shapes rather than silently coercing them.
Engineers building the broader operational disciplines behind such gates may find Refonte Learning's Database Administrator Essentials relevant to database design, SQL optimization, backup and recovery, migration, security, monitoring, and related administration foundations. The program page describes a three-month program at 12–14 hours per week, recommends basic programming knowledge, separately lists working toward a bachelor's or higher-level degree as an admission prerequisite, and describes mentorship plus Training and Internship certificates on successful completion.
