Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.96) (envelope-from ) id 1vr3PY-005cTg-1O for pgsql-bugs@arkaria.postgresql.org; Sat, 14 Feb 2026 00:21:24 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.96) (envelope-from ) id 1vr3PV-00Gi0T-2o for pgsql-bugs@arkaria.postgresql.org; Sat, 14 Feb 2026 00:21:21 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.96) (envelope-from ) id 1vr3PV-00Gi0K-1q for pgsql-bugs@lists.postgresql.org; Sat, 14 Feb 2026 00:21:21 +0000 Received: from mail-dy1-x132b.google.com ([2607:f8b0:4864:20::132b]) by magus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (Exim 4.98.2) (envelope-from ) id 1vr3PS-00000000ZR6-47tn for pgsql-bugs@lists.postgresql.org; Sat, 14 Feb 2026 00:21:20 +0000 Received: by mail-dy1-x132b.google.com with SMTP id 5a478bee46e88-2b86ce04c5cso2893058eec.1 for ; Fri, 13 Feb 2026 16:21:18 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=leadboat.com; s=google; t=1771028476; x=1771633276; darn=lists.postgresql.org; h=user-agent:in-reply-to:content-transfer-encoding :content-disposition:mime-version:references:message-id:subject:cc :to:from:date:from:to:cc:subject:date:message-id:reply-to; bh=2v/w/fmFlHB8vLSmImk2TbIq31ii4h14TFmhfl0Urpo=; b=c/0bC1BEo03oOblAjB9cn+YlysR+YZ7k3sQ/+WkogwB8RCipK4Ec7NqBJCM2phSfOX ZxUBIc62gK3UXw5U/cKxj1aaQ0ZjhYcbtEbikbUllvgz6Oco4IKA2ovkIfDPsnQvaHqP 4YBdaxZg45+I8aIh3bRtjXiIyaK+xEY/PXRg4= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1771028476; x=1771633276; h=user-agent:in-reply-to:content-transfer-encoding :content-disposition:mime-version:references:message-id:subject:cc :to:from:date:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to; bh=2v/w/fmFlHB8vLSmImk2TbIq31ii4h14TFmhfl0Urpo=; b=PB492CMd8cou8X7i03zFppoVBDIXhbfmXEZH3P+PEEgccy7cIE8m7CLs+Thtek41z7 kr++X8/3JttvYYKs4cqKA1zNjPItDr0g/vaXwHU/FQZyACfKzbHrmSgk+8ukc6Vl+vvn U9pH1b+xTuIMooAXwCW2/MkRP3cDgOZBW3qJvTntbgmTywbFYOAfQ8gTSSzsmowqwqS3 EG4cplK7P2vfWi/7G+Im9ZHKvGi9E0NXtIa9oFn1rgrsA/hiCua1MmCjnCfDG7x/ApZZ ptYLETUY2xeQrOI1gVlvd5OnEXhiM63cFhwWlitQDrVnmF9uBHiNbETb4mzYBRFRfYtU QgLw== X-Forwarded-Encrypted: i=1; AJvYcCVpS6B56SD/V1L4g6W3El4Em7wjnX+CXVvWljXmU3ab1GH8VIS6WpjPwnV+ETpDkz2zITD6XCYV4D0R@lists.postgresql.org X-Gm-Message-State: AOJu0YyKo5Yc7FbgLAgOVJI1+pR00Zogm2HBfwHG7dCzBVMDCFhrKYF4 zUavjuS45PQqbKU+DTUHBcmqThvRGKf+9/SN6mqTnBPtPVjRCQ8rlW/Ls4OaqhpyJg== X-Gm-Gg: AZuq6aKBSi+TpSbbF3XvF3cwq9XXc4o7KE8Vp4H4hqMMK7RO0Zfxj1Hl3ItliWlIaRl sYB22ODDNqgX3zRKl0jt0s+TqAOGBaTMGfq3/V8svPb07PJ4pv478TnBT++plmLvIWdOnTw2O6o Sq4b00t2TVp1hehxDDMcKkSbbyTwo6SwmOpH0TBMfxBV42vsLkZfmJXYXKwb5r4FpmjCTDnbHTd UumlFgnf6F1goSoaMwDrA5UXfY2s4Erlx17QsJndADoQjufXRIuhydkjqo7UK+EsWyOWgEZyrUR rb4TwRJgC2I1BJcr41hgj/M1+Wnffh4fjmYnvEegZOkFi5w9geQPh1YjPNA/pV7LD4+TTR66k7w tto833P74du7zd6LohCja/EZtWQDAgyoeKAtUT7T4K17Yyovh2Ibh8jQvNCFKJ8r0H4NlYYkQKv 5CKDnwnSSBxHgYI49gqyh2LibrBUp/trUyxMr1VqtnWx2eSVuUIf4PD6s= X-Received: by 2002:a05:7301:6885:b0:2b8:2946:72c5 with SMTP id 5a478bee46e88-2babc4b48bcmr1527916eec.39.1771028476344; Fri, 13 Feb 2026 16:21:16 -0800 (PST) Received: from microsoft.com (c-73-15-160-255.hsd1.ca.comcast.net. [73.15.160.255]) by smtp.gmail.com with ESMTPSA id 5a478bee46e88-2bacb543d40sm463500eec.2.2026.02.13.16.21.15 (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128); Fri, 13 Feb 2026 16:21:15 -0800 (PST) Date: Fri, 13 Feb 2026 16:21:13 -0800 From: Noah Misch To: ranvis@gmail.com, pgsql-bugs@lists.postgresql.org Cc: thomas.munro@gmail.com Subject: Re: BUG #19406: substring(text) fails on valid UTF-8 toasted value in PostgreSQL 15.16 Message-ID: <20260214002113.1f.noahmisch@microsoft.com> References: <19406-9867fddddd724fca@postgresql.org> <20260213172702.71@rfd.leadboat.com> <20260213224804.2c@rfd.leadboat.com> MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="zxYKLeph1HUga/Xp" Content-Disposition: inline Content-Transfer-Encoding: 8bit In-Reply-To: <20260213224804.2c@rfd.leadboat.com> User-Agent: Mutt/2.2.12 (2023-09-09) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk --zxYKLeph1HUga/Xp Content-Type: text/plain; charset=us-ascii Content-Disposition: inline On Fri, Feb 13, 2026 at 02:48:04PM -0800, Noah Misch wrote: > On Fri, Feb 13, 2026 at 09:27:02AM -0800, Noah Misch wrote: > > On Fri, Feb 13, 2026 at 07:46:22AM +0000, PG Bug reporting form wrote: > > > After upgrading from PostgreSQL 15.15 to 15.16, substring(text) raises: > > > >ERROR: invalid byte sequence for encoding "UTF8": 0xe6 0x97 > > > on valid UTF-8 text stored in a TOAST-compressed column. > > > > > user=> select substring(data from 1 for 1) from toast_repro; > > > ERROR: 22021: invalid byte sequence for encoding "UTF8": 0xe6 0x97 > > > > Thanks for the report. That is a bug and a regression; I regret missing it > > during review. The substring operation works by taking a 4-byte slice from > > the toasted value (4 bytes being the max length of a UTF8 char in PostgreSQL), > > the finding the actual first character within those bytes. However, it > > incorrectly requires those four bytes to be a valid UTF8 string. I'll start > > on a fix. > > Attached. I may add some more tests, e.g. a toasted invalid string where the > detoasted length is less than the slice we request. Tests already covered that in particular, but I added some other tests. I think this is now ready. Review welcome. I have a Valgrind test run ongoing. --zxYKLeph1HUga/Xp Content-Type: text/plain; charset=utf-8 Content-Disposition: attachment; filename="toast-slice-mblen-v2.patch" Content-Transfer-Encoding: 8bit From: Noah Misch Fix SUBSTRING() for toasted multibyte characters. Commit 1e7fe06c10c0a8da9dd6261a6be8d405dc17c728 changed pg_mbstrlen_with_len() to ereport(ERROR) if the input ends in an incomplete character. Most callers want that. text_substring() does not. It detoasts the most bytes it could possibly need to get the requested number of characters. For example, to extract up to 2 chars from UTF8, it needs to detoast 8 bytes. In a string of 3-byte UTF8 chars, that yields 2 complete chars and 1 partial char. Fix this by replacing this pg_mbstrlen_with_len() call with a string traversal that differs by stopping upon finding as many chars as the substring could need. This also makes SUBSTRING() stop raising an encoding error if the incomplete char is past the end of the substring. This is consistent with the general philosophy of the above commit, which was to raise errors on a just-in-time basis. Before the above commit, SUBSTRING() never raised an encoding error. SUBSTRING() has long been detoasting enough for one more char than needed, because it did not distinguish exclusive and inclusive end position. Fix that incidentally. That and stopping the char count early might improve performance. Back-patch to v14 (all supported versions). Reported-by: SATŌ Kentarō Reviewed-by: FIXME Bug: #19406 Discussion: https://postgr.es/m/19406-9867fddddd724fca@postgresql.org Backpatch-through: 14 diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c index dbecd71..99a5470 100644 --- a/src/backend/utils/adt/varlena.c +++ b/src/backend/utils/adt/varlena.c @@ -133,6 +133,7 @@ static text *text_substring(Datum str, int32 start, int32 length, bool length_not_specified); +static int pg_mbcharcliplen_chars(const char *mbstr, int len, int limit); static text *text_overlay(text *t1, text *t2, int sp, int sl); static int text_position(text *t1, text *t2, Oid collid); static void text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state); @@ -586,7 +587,7 @@ text_substring(Datum str, int32 start, int32 length, bool length_not_specified) int32 S = start; /* start position */ int32 S1; /* adjusted start position */ int32 L1; /* adjusted substring length */ - int32 E; /* end position */ + int32 E; /* end position, exclusive */ /* * SQL99 says S can be zero or negative (which we don't document), but we @@ -684,11 +685,11 @@ text_substring(Datum str, int32 start, int32 length, bool length_not_specified) else { /* - * A zero or negative value for the end position can happen if the - * start was negative or one. SQL99 says to return a zero-length - * string. + * Ending at position 1, exclusive, obviously yields an empty + * string. A zero or negative value can happen if the start was + * negative or one. SQL99 says to return a zero-length string. */ - if (E < 1) + if (E <= 1) return cstring_to_text(""); /* @@ -698,11 +699,11 @@ text_substring(Datum str, int32 start, int32 length, bool length_not_specified) L1 = E - S1; /* - * Total slice size in bytes can't be any longer than the start - * position plus substring length times the encoding max length. - * If that overflows, we can just use -1. + * Total slice size in bytes can't be any longer than the + * inclusive end position times the encoding max length. If that + * overflows, we can just use -1. */ - if (pg_mul_s32_overflow(E, eml, &slice_size)) + if (pg_mul_s32_overflow(E - 1, eml, &slice_size)) slice_size = -1; } @@ -726,8 +727,10 @@ text_substring(Datum str, int32 start, int32 length, bool length_not_specified) } /* Now we can get the actual length of the slice in MB characters */ - slice_strlen = pg_mbstrlen_with_len(VARDATA_ANY(slice), - slice_len); + slice_strlen = + (slice_size == -1 ? + pg_mbstrlen_with_len(VARDATA_ANY(slice), slice_len) : + pg_mbcharcliplen_chars(VARDATA_ANY(slice), slice_len, E - 1)); /* * Check that the start position wasn't > slice_strlen. If so, SQL99 @@ -783,6 +786,35 @@ text_substring(Datum str, int32 start, int32 length, bool length_not_specified) } /* + * pg_mbcharcliplen_chars - + * Mirror pg_mbcharcliplen(), except return value unit is chars, not bytes. + * + * This mirrors all the dubious historical behavior, so it's static to + * discourage proliferation. The assertions are specific to the one caller. + */ +static int +pg_mbcharcliplen_chars(const char *mbstr, int len, int limit) +{ + int nch = 0; + int l; + + Assert(len > 0); + Assert(limit > 0); + Assert(pg_database_encoding_max_length() > 1); + + while (len > 0 && *mbstr) + { + l = pg_mblen_with_len(mbstr, len); + nch++; + if (nch == limit) + break; + len -= l; + mbstr += l; + } + return nch; +} + +/* * textoverlay * Replace specified substring of first string with second * diff --git a/src/test/regress/expected/encoding.out b/src/test/regress/expected/encoding.out index ea1f38c..cac1cb7 100644 --- a/src/test/regress/expected/encoding.out +++ b/src/test/regress/expected/encoding.out @@ -63,7 +63,13 @@ SELECT reverse(good) FROM regress_encoding; -- invalid short mb character = error SELECT length(truncated) FROM regress_encoding; ERROR: invalid byte sequence for encoding "UTF8": 0xc3 -SELECT substring(truncated, 1, 1) FROM regress_encoding; +SELECT substring(truncated, 1, 3) FROM regress_encoding; + substring +----------- + caf +(1 row) + +SELECT substring(truncated, 1, 4) FROM regress_encoding; ERROR: invalid byte sequence for encoding "UTF8": 0xc3 SELECT reverse(truncated) FROM regress_encoding; ERROR: invalid byte sequence for encoding "UTF8": 0xc3 @@ -375,7 +381,43 @@ NOTICE: MULE_INTERNAL LC2: \x908283 -> {9470595} -> \x908283 = OK t (1 row) +-- substring fetches a slice of a toasted value; unused tail of that slice is +-- an incomplete char (bug #19406) +CREATE TABLE toast_3b_utf8 (c text); +INSERT INTO toast_3b_utf8 VALUES (repeat(U&'\2026', 4000)); +SELECT SUBSTRING(c FROM 1 FOR 1) FROM toast_3b_utf8; + substring +----------- + … +(1 row) + +SELECT SUBSTRING(c FROM 4001 FOR 1) FROM toast_3b_utf8; + substring +----------- + +(1 row) + +-- diagnose incomplete char iff within the substring +UPDATE toast_3b_utf8 SET c = c || test_bytea_to_text('\xe280'); +SELECT SUBSTRING(c FROM 4000 FOR 1) FROM toast_3b_utf8; + substring +----------- + … +(1 row) + +SELECT SUBSTRING(c FROM 4001 FOR 1) FROM toast_3b_utf8; +ERROR: invalid byte sequence for encoding "UTF8": 0xe2 0x80 +-- substring needing last byte of its slice_size +ALTER TABLE toast_3b_utf8 RENAME TO toast_4b_utf8; +UPDATE toast_4b_utf8 SET c = repeat(U&'\+01F680', 3000); +SELECT SUBSTRING(c FROM 3000 FOR 1) FROM toast_4b_utf8; + substring +----------- + 🚀 +(1 row) + DROP TABLE encoding_tests; +DROP TABLE toast_4b_utf8; DROP FUNCTION test_encoding; DROP FUNCTION test_text_to_wchars; DROP FUNCTION test_mblen_func; diff --git a/src/test/regress/sql/encoding.sql b/src/test/regress/sql/encoding.sql index b9543c0..782f90f 100644 --- a/src/test/regress/sql/encoding.sql +++ b/src/test/regress/sql/encoding.sql @@ -40,7 +40,8 @@ SELECT reverse(good) FROM regress_encoding; -- invalid short mb character = error SELECT length(truncated) FROM regress_encoding; -SELECT substring(truncated, 1, 1) FROM regress_encoding; +SELECT substring(truncated, 1, 3) FROM regress_encoding; +SELECT substring(truncated, 1, 4) FROM regress_encoding; SELECT reverse(truncated) FROM regress_encoding; -- invalid short mb character = silently dropped SELECT regexp_replace(truncated, '^caf(.)$', '\1') FROM regress_encoding; @@ -212,7 +213,23 @@ INSERT INTO encoding_tests VALUES SELECT COUNT(test_encoding(encoding, description, input)) > 0 FROM encoding_tests; +-- substring fetches a slice of a toasted value; unused tail of that slice is +-- an incomplete char (bug #19406) +CREATE TABLE toast_3b_utf8 (c text); +INSERT INTO toast_3b_utf8 VALUES (repeat(U&'\2026', 4000)); +SELECT SUBSTRING(c FROM 1 FOR 1) FROM toast_3b_utf8; +SELECT SUBSTRING(c FROM 4001 FOR 1) FROM toast_3b_utf8; +-- diagnose incomplete char iff within the substring +UPDATE toast_3b_utf8 SET c = c || test_bytea_to_text('\xe280'); +SELECT SUBSTRING(c FROM 4000 FOR 1) FROM toast_3b_utf8; +SELECT SUBSTRING(c FROM 4001 FOR 1) FROM toast_3b_utf8; +-- substring needing last byte of its slice_size +ALTER TABLE toast_3b_utf8 RENAME TO toast_4b_utf8; +UPDATE toast_4b_utf8 SET c = repeat(U&'\+01F680', 3000); +SELECT SUBSTRING(c FROM 3000 FOR 1) FROM toast_4b_utf8; + DROP TABLE encoding_tests; +DROP TABLE toast_4b_utf8; DROP FUNCTION test_encoding; DROP FUNCTION test_text_to_wchars; DROP FUNCTION test_mblen_func; --zxYKLeph1HUga/Xp--