← Back to Pull requests

Fix 500 after metadata schema changes #517

Open
mgaffigan opened this pull request with 54 lines diff across 3 files
View on GitHub
mgaffigan mgaffigan commented on Oct 26, 2026 20:40 UTC
Author

Postgres would have intermittent 500 errors after a metadata column changed from one type to another. Fix that.

Closes #458
Caught during #449

Diff: 54 lines (+54 / -0) across 3 files Reviewer: NicoPiel Review duration: 25814m
All Vouch review confidence checks passed
Residual risk 0.04 = Change Risk (0.30) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.30 · 54 lines diff across 3 files
0.30
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.80 · 4 substantive comment(s)
0.80
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
85%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.240
Real PR Conversation Timeline
8 items
github-actions[bot] github-actions[bot] commented on Oct 26, 2026 20:52 UTC
Bot

Test Results


129 files  ±0  129 suites  ±0   2m 54s ⏱️ +13s
737 tests ±0  737 ✅ ±0  0 💤 ±0  0 ❌ ±0 
827 runs  ±0  821 ✅ ±0  6 💤 ±0  0 ❌ ±0 

Results for commit 2ad11006. ± Comparison against base commit fbda4743.

[test-results]:data:application/gzip;base64,H4sIAHm932oC/13MSw7CIBSF4a00jB3AxXLBzRiENiG2xfAYGfcuaGnQ4f+d5DzJ7JYpksvAQJ0GErNLXdocdHJ+q4DnAmVMdUaOra4xG/NPd/coRA+YtVt+YArBh11C3uqnBNyjXUpgh3wfRevu8NP9n/Hr6lIJAtoyRqkYkesbk2gAUSEXjHOB1moAw0erLHm9AV0ly4YJAQAA

NicoPiel NicoPiel approved these changes on Oct 27, 2026 10:54 UTC
Approved Reviewer

Approved these changes.

tonygermano tonygermano commented on code on Oct 28, 2026 22:05 UTC
Code Review
donkey/src/main/java/com/mirth/connect/donkey/server/data/jdbc/PostgresqlJdbcDao.java:1
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Mirth Corporation. All rights reserved.
+ * 
+ * http://www.mirthcorp.com
+ * 
+ * The software in this package is published under the terms of the MPL license a copy of which has
+ * been included with this distribution in the LICENSE.txt file.
+ */

chore: fix file header

tonygermano tonygermano commented on code on Oct 28, 2026 22:08 UTC
Code Review
donkey/src/main/java/com/mirth/connect/donkey/server/data/jdbc/PostgresqlJdbcDao.java:1
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Mirth Corporation. All rights reserved.
+ * 
+ * http://www.mirthcorp.com
+ * 
+ * The software in this package is published under the terms of the MPL license a copy of which has
+ * been included with this distribution in the LICENSE.txt file.
+ */
+
+package com.mirth.connect.donkey.server.data.jdbc;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+import org.postgresql.PGStatement;
+
+import com.mirth.connect.donkey.server.Donkey;
+import com.mirth.connect.donkey.server.channel.Statistics;
+import com.mirth.connect.donkey.server.data.StatisticsUpdater;
+import com.mirth.connect.donkey.util.SerializerProvider;
+
+public class PostgresqlJdbcDao extends JdbcDao {
+
+    public PostgresqlJdbcDao(Donkey donkey, Connection connection, QuerySource querySource, PreparedStatementSource statementSource, SerializerProvider serializerProvider, boolean encryptMessageContent, boolean encryptAttachments, boolean encryptCustomMetaData, boolean decryptData, StatisticsUpdater statisticsUpdater, Statistics currentStats, Statistics totalStats, String statsServerId) {
+        super(donkey, connection, querySource, statementSource, serializerProvider, encryptMessageContent, encryptAttachments, encryptCustomMetaData, decryptData, statisticsUpdater, currentStats, totalStats, statsServerId);
+    }
+
+    /** Excludes a statement from caching.  Required when schema changes at runtime. */
+    @Override
+    protected void disableServerSidePlanCache(PreparedStatement statement) throws SQLException {
+        statement.unwrap(PGStatement.class).setPrepareThreshold(0);

Both Claude and Gemini suggested adding this guard for safety against a non-pgjdbc driver.

        if (statement.isWrapperFor(PGStatement.class)) {
            statement.unwrap(PGStatement.class).setPrepareThreshold(0);
        }

tonygermano tonygermano commented on code on Oct 28, 2026 22:42 UTC
Code Review
donkey/src/main/java/com/mirth/connect/donkey/server/data/jdbc/JdbcDao.java:1
@@ -3094,6 +3096,14 @@ PreparedStatement prepareStatement(String queryId, String channelId) throws SQLE
         return statementSource.getPreparedStatement(queryId, localChannelId);
     }
 
+    /**
+     * Stops the driver from caching a server-side plan for one statement where the schema may have
+     * changed from query to query.
+     */
+    protected void disableServerSidePlanCache(PreparedStatement statement) throws SQLException {

Claude:

Name and javadoc describe the wrong thing. prepareThreshold=0 stops pgjdbc from using a named server-side prepared statement, along with its cached result description. It doesn't really "disable plan caching." Something like useUnnamedStatement or disableServerPrepare would keep a future Oracle or SQL Server override from implementing the wrong behaviour. The existing // do not cache this statement comment above each call now means two different things.

I had to look it up to see what prepareThreshold did, but specifies the limit where if the driver uses a client-side preparedStatement threshold number of times, then it creates a server-side prepared statement to use for future calls. Setting it to 0 instructs the client to not create the server-side prepare.

tonygermano tonygermano requested changes on Oct 29, 2026 00:34 UTC
Changes Requested Reviewer

Thanks for tracking this down. Targeting the two SELECT metadata queries is a reasonable, contained fix for #458. The changes I'm requesting are in the inline comments. Nothing below is blocking; these are suggestions and questions, roughly in order of importance.

Tests

This PR doesn't add a test, but CustomMetaDataColumnRedeployTest in #449 covers the scenario end to end, and that PR's CI runs it against both PostgreSQL configurations. Once #449 lands, that should catch a regression if a later refactor drops the disableServerSidePlanCache call.

Does that test fail every time without this fix, or only sometimes? pgjdbc only switches to a named server-side statement after the same query has run 5 times (its default prepareThreshold) on the same connection. The test reads the metadata only a few times before the redeploy, and the pool has several connections. If it is intermittent, a few extra metadata reads before the redeploy should make it fail consistently without the fix.

Force-binary connections

As I understand pgjdbc's PgStatement, a statement is only treated as one-shot (unnamed) when the threshold allows it and* force-binary transfer is off. setPrepareThreshold(0) doesn't clear the force-binary flag. That means a connection URL with prepareThreshold=-1 or forceBinary=true would still get a named server-side statement, and the "cached plan must not change result type" error would still happen. These are uncommon settings. If you can confirm the behaviour, a note in the javadoc would help.

Scope of the fix

This fixes the two queries that are known to break, but the underlying cause is more general. pgjdbc keeps named prepared statements per connection, and those statements outlive DDL on our pooled connections. Any other query whose result shape depends on D_MCMn columns could hit the same error after a metadata column is added, removed or retyped. That includes queries added later and queries from extensions. Some connection-level options would cover all of them:

  • autosave=conservative as a default for the PostgreSQL pool. pgjdbc then retries exactly this error after re-preparing the statement.

  • Evicting pooled connections, or running DEALLOCATE ALL, after addMetaDataColumn / removeMetaDataColumn.
  • I'm fine with the targeted approach for this PR. Do you think one of these is worth a follow-up issue?

    Performance

    With a threshold of 0, these two queries are parsed and planned on every execution and never switch to a named statement. getMetaDataMap runs once per message when browsing and searching messages, so this adds some overhead to a frequently used path to handle a rare schema change. I expect it's small next to the rest of the search, so I'm not asking for changes here. It's one more reason the invalidate-after-DDL options above might be the better long-term design.

    ---
    🤖 Drafted with Claude Code

    gibson9583 gibson9583 approved these changes on Oct 30, 2026 10:48 UTC
    Approved Reviewer

    Looks safe to merge.

    Reviewers
    Assignees
    mgaffigan mgaffigan
    Labels
    risk: low confidence: 85.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 29.9% (LOW) · Higher = larger blast radius
    29.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.2% · Lower = rushed or shallow review
    85.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.4% · Safe to merge
    4.4%