Prepared Queries With COUNT(*) Failing

We’re seeing problems with prepared queries failing when they reference COUNT(*). COUNT(bucketname) seems to work fine.

Error message:
"Unable to decode prepared statement - cause: Unrecognizable prepared statement - cause: JSON unmarshalling error: Keyspace not found keyspace - cause: No bucket named "

We are seeing this error using .Net SDK 2.4.0 and Couchbase Server 4.5.0.

It seems like this same issue as https://issues.couchbase.com/browse/MB-16616, but that bug shows as fixed in 4.1.1. Is it possible that the fix didn’t make it into 4.5.0?

For now we’re changing our query to not use COUNT(*), so it’s not a rush, but I thought it was worth checking out.

Thanks,
Brant

Thanks @btburnett3. Copying @prasad, @marcog

Rings a bell, but I can’t pinpoint it.
@btburnett3 could I see the plan from the prepare statement?

@marcog

This is the PREPARE output on 4.5.0:

[
  {
	"encoded_plan": "H4sIAAAJbogA/5xRXW/TMBT9K9aFhxalUz9Cm0biYaoCmzRY1RbxgKbGtS+pIbGD7YyOKfx2rttUFUi8oDzEuefc8+E8A2phJMptXXINKUAEmldIp2kyi4cSp4P5VCaDOBmNB0ksxoMZnwyHcZzgcILENjVa7o2F9BleXD5gjd8b0g6UX2KvSmmR9D//Sbpu/N5Y9TOwjqT/UrnVEg8L02i/FlSCpMwjWke804n1evk71MQv86vcP9WY9/tnGoEVen5h9K9yJQPhIQIVlMmhwza06qAbbxWlBf46lrvZaJfMp2I8m0tCv+GTq7nAy153qeepxC+8KT1NaaLdsc+K6wJD+xtV7EPyl6MQ4FaLsnHKUOlJBHfmxxlqW0IJ0QUJFk5BG/3rUpbWfEUR7Cw68t16tNXJldOrmxKMhzpsirDUe9WH9oGeCGqrHlWJBVWnfF349FwtHbV/W6+9RV7BcdmpQnPf2GO3zikF3VQ7tJQZPB7CYLnKlterjK2zu2yxYYv7jx82FIFxx05L7O3q/j3rTNmnm4zI4U+yN4yuo/0dAAD//5VKjBTIAgAA",
	"name": "68740de6-96d8-4812-84c2-7a300448e03e",
	"operator": {
	  "#operator": "Sequence",
	  "~children": [
		{
		  "#operator": "Authorize",
		  "child": {
			"#operator": "Sequence",
			"~children": [
			  {
				"#operator": "IndexCountScan",
				"covers": [
				  "cover ((`General`.`type`))",
				  "cover ((meta(`General`).`id`))"
				],
				"index": "GeneralTypes",
				"index_id": "a54db71b896c279d",
				"keyspace": "General",
				"namespace": "default",
				"spans": [
				  {
					"Range": {
					  "High": [
						"$1"
					  ],
					  "Inclusion": 3,
					  "Low": [
						"$1"
					  ]
					}
				  }
				],
				"using": "gsi"
			  },
			  {
				"#operator": "IndexCountProject",
				"result_terms": [
				  {
					"as": "result",
					"expr": "count(*)"
				  }
				]
			  }
			]
		  },
		  "privileges": {
			"default:General": 1
		  }
		},
		{
		  "#operator": "Stream"
		}
	  ]
	},
	"signature": {
	  "result": "number"
	},
	"text": "PREPARE SELECT COUNT(*) as result FROM General WHERE type = $1"
  }
]

Here is the index it’s operating against:

CREATE INDEX GeneralTypes ON General (`type`)

Thanks,
Brant

I’ve done some additional testing, and it appears that the bug is fixed in 4.5.1. So maybe it just needs some better documentation about where it’s broken and where it’s fixed?

Thanks,
Brant

Me thinks that’s MB-19692, fixed in 4.5.1, however, be aware that if you are using multiple N1QL nodes, you may run into MB-22273, which will be fixed in 4.6.2

We’re affected by this too. Can’t get in to see the detail in https://issues.couchbase.com/browse/MB-22273 - something going on with the cert - but this all sounds very familiar. We’ve had to set AdHoc true for COUNT queries.

hi @frasdav, what client r u using? and CB version?? Is it multi node setup? thx.

Hi @Prasad - we’re using 4.5.1-2844 Enterprise Edition (build-2844) on 3 Windows Server 2012 R2 nodes (although only two with query/index services enabled) in Azure and .NET SDK 2.3.10.

ok… thx. Check if u r hitting MB-22273, that involves restarting the query service etc. Work around is documented at : https://developer.couchbase.com/documentation/server/4.6/release-notes/relnotes.html

1 Like

In our dev environment we also see this kind of problems with COUNT-queries

  • Partially the query fails with "Unable to decode prepared statement - cause: Unrecognizable prepared statement - cause: JSON unmarshalling error: Keyspace not found keyspace - cause: No bucket named " That looks like MB-19692, but we run 4.5.1-2844 as frasdav and this issue should be closed in this version.
  • Partially we get “Repreparing statement. Index or version mismatch.”
  • Partially we also see returning a COUNT of 0 - that looks like the effect of MB-22273
  • Everything runs fine with adhoc=true

For the inexpert, that looks like a mixture of MB-22273 and MB-19692. Or can MB-22273 show several faces? But if I get the message right, prepared statements are unusable in the combination with multiple query nodes and the PHP SDK anyway, because the workaround for MB-22273 can only be used by the Java SDK. Or did I miss something?

hi @kstorch, note that MB-22273 hurts when query engines in the cluster are restarted for some reason. Btw, the fix is available in 4.6.2.

If you think the issue you are hitting is different, pls open a MB and provide exact repro steps, and any setup related details. thanks.

We are also seeing this sporadically on a brandnew 5.0.0 AprilDB with a 3 nodes cluster. Nothing was restarted.

Error in query result: [{“msg”:"Unable to decode prepared statement - cause: Unrecognizable prepared statement - cause: JSON unmarshalling error: Keyspace not found keyspace - cause: No bucket named ",“code”:4070}] status: fatal

After refreshing the page a couple of times it works again.

We also have a COUNT() query involved as we try to do some paginatin, so on every listing-page for each query we have a related count(*) query which fetches the total number of items, so that we can display something like “showing 50 of 23456 results”

Could you post actual query and index. cc @marcog, @prasad

I wil try tomorrow. Locally I on my laptop I cannot reproduce it.
On our 3nodes cluster (where we are seeing the issue) we are using Memory Optimized Indexes.

I am not aware of any more issues in that area which are not fixed in the April DP, but if you give us an idea of the query plan, @vsr1 and I can use it to go through the code.

Hi @marcog, @prasad, @vsr1,

I tried debugging it on our 3 nodes cluster today using cbq, as our code already uses the workaround by setting adhoc=true which solves the problem for the time being. Thus I used CBQ to make a prepared statement.

I connect via ssh to one node of the cluster and started cbq.

/opt/couchbase/bin # ./cbq -u=myuser -p=xxxx


PREPARE folder2 FROM SELECT COUNT(*) from datastoreitems WHERE datastoreid = $ds AND folder = $folder;
{
    "requestID": "328a87e5-69b8-4358-92f2-1a194731d1f7",
    "signature": "json",
    "results": [
        {
            "encoded_plan": "H4sIAAAAAAAA/7RUQW/TTBT8K6tpD3G1+qR+FyQjDlVxAKm0VhLEIYqSxfviLNi75u26SqnMb0cbp23S9ABB3Ozn8Xhm3njvQbZwmvS8qZRFCkhYVRNSLF2lif+HhGuIVXCM9B4nTzcY0/eWbEGQ+FmsTKWZLNLpPuiiDSvH5kdENWxuTUUl+Uh1ZXzYwCeKSwpIoWmp2iqkWgXlg2MygWoPiZzNLdLzTv4++FU36x50HSU8Z1MrvhsXykLCWE1rpDhp+jEkvtGdb1QRszrQEDN8fNgLhUTrjS2RovQG0cvu54YUitURrM95csWqqqjCX5kfmioQQ6JwVptgXOzGYDBY7Gta/Lcz0ItEvBGn2idCWS1eAved6nH9dZIcOPhgTTCqeseubSChypKpVCGWZorCtTYMzhLMJMqImMfAkE5n3aw7ZArENWmjAv0x3fP9GHuEpn+ynG1AObuvVMReMfm2CvNo1m/QtG4i8FFY97KdB4YY3WF648Ck6s278Ka0KrRMUfDpOVLYtv5CjE4i0Dr+j/koyy9GmdieG2I4uvkoxtlVdjkRlzefrieDs0Qs2dVivxbi8/tslO0Mdd8icXH9dkv2VJfX6H4FAAD//5sFtH2zBAAA",
            "name": "folder2",
            "operator": {
                "#operator": "Sequence",
                "~children": [
                    {
                        "#operator": "Authorize",
                        "privileges": {
                            "List": [
                                {
                                    "Priv": 1,
                                    "Target": "default:datastoreitems"
                                },
                                {
                                    "Priv": 7,
                                    "Target": "default:datastoreitems"
                                }
                            ]
                        },
                        "~child": {
                            "#operator": "Sequence",
                            "~children": [
                                {
                                    "#operator": "PrimaryScan",
                                    "index": "#primary",
                                    "keyspace": "datastoreitems",
                                    "namespace": "default",
                                    "using": "gsi"
                                },
                                {
                                    "#operator": "Fetch",
                                    "keyspace": "datastoreitems",
                                    "namespace": "default"
                                },
                                {
                                    "#operator": "Parallel",
                                    "~child": {
                                        "#operator": "Sequence",
                                        "~children": [
                                            {
                                                "#operator": "Filter",
                                                "condition": "(((`datastoreitems`.`datastoreid`) = $ds) and ((`datastoreitems`.`folder`) = $folder))"
                                            },
                                            {
                                                "#operator": "InitialGroup",
                                                "aggregates": [
                                                    "count(*)"
                                                ],
                                                "group_keys": []
                                            }
                                        ]
                                    }
                                },
                                {
                                    "#operator": "IntermediateGroup",
                                    "aggregates": [
                                        "count(*)"
                                    ],
                                    "group_keys": []
                                },
                                {
                                    "#operator": "FinalGroup",
                                    "aggregates": [
                                        "count(*)"
                                    ],
                                    "group_keys": []
                                },
                                {
                                    "#operator": "Parallel",
                                    "~child": {
                                        "#operator": "Sequence",
                                        "~children": [
                                            {
                                                "#operator": "InitialProject",
                                                "result_terms": [
                                                    {
                                                        "expr": "count(*)"
                                                    }
                                                ]
                                            },
                                            {
                                                "#operator": "FinalProject"
                                            }
                                        ]
                                    }
                                }
                            ]
                        }
                    },
                    {
                        "#operator": "Stream"
                    }
                ]
            },
            "signature": {
                "$1": "number"
            },
            "text": "PREPARE folder2 FROM SELECT COUNT(*) from datastoreitems WHERE datastoreid = $ds AND folder = $folder;"
        }
    ],
    "status": "success",
    "metrics": {
        "elapsedTime": "6.107127ms",
        "executionTime": "6.065526ms",
        "resultCount": 1,
        "resultSize": 5312
    }
}
cbq> \SET -$ds 'd4d9ff0c-4478-11e7-a06f-901b0ea49fee';
cbq> \SET -$folder 'default';
cbq> EXECUTE folder2;
{
    "requestID": "ebd6544e-def5-4767-96df-a1562e676af2",
    "signature": null,
    "results": [
        {
            "$1": 0
        }
    ],
    "status": "success",
    "metrics": {
        "elapsedTime": "13.490432629s",
        "executionTime": "13.49041341s",
        "resultCount": 1,
        "resultSize": 31
    }
}
cbq> EXECUTE folder2;
{
    "requestID": "598979f3-7196-42c6-a4d8-11487ad80610",
    "errors": [
        {
            "code": 4040,
            "msg": "No such prepared statement: folder2"
        }
    ],
    "status": "fatal",
    "metrics": {
        "elapsedTime": "379.164µs",
        "executionTime": "347.507µs",
        "resultCount": 0,
        "resultSize": 0,
        "errorCount": 1
    }
}
cbq> EXECUTE folder2;
{
    "requestID": "ae8a856b-0a7e-4088-b576-dd92117cf34d",
    "errors": [
        {
            "code": 4040,
            "msg": "No such prepared statement: folder2"
        }
    ],
    "status": "fatal",
    "metrics": {
        "elapsedTime": "412.432µs",
        "executionTime": "383.518µs",
        "resultCount": 0,
        "resultSize": 0,
        "errorCount": 1
    }
}
cbq> EXECUTE folder2;
{
    "requestID": "c4e1b67a-e3cb-4038-a8b4-a3aebe1b35d1",
    "errors": [
        {
            "code": 4040,
            "msg": "No such prepared statement: folder2"
        }
    ],
    "status": "fatal",
    "metrics": {
        "elapsedTime": "381.238µs",
        "executionTime": "348.205µs",
        "resultCount": 0,
        "resultSize": 0,
        "errorCount": 1
    }
}
cbq> EXECUTE folder2;
{
    "requestID": "e5fe8253-009f-4f5d-a14d-72784da1d6de",
    "errors": [
        {
            "code": 4040,
            "msg": "No such prepared statement: folder2"
        }
    ],
    "status": "fatal",
    "metrics": {
        "elapsedTime": "203.984µs",
        "executionTime": "189.999µs",
        "resultCount": 0,
        "resultSize": 0,
        "errorCount": 1
    }
}
cbq> EXECUTE folder2;
{
    "requestID": "e0d62082-1b96-42cf-a151-d6af3aca8778",
    "signature": null,
    "results": [
        {
            "$1": 0
        }
    ],
    "status": "success",
    "metrics": {
        "elapsedTime": "13.475725202s",
        "executionTime": "13.475697058s",
        "resultCount": 1,
        "resultSize": 31
    }
}

My observations

  • Notice that at the end I execute the Prepared Statement 6x
  • 1st time it is successful
  • 2nd-4th is error (fatal, “No such prepared statement: folder2”)
  • 6th successful again

Not sure why 4 out of 6 times the prepared statement was not found. Maybe that is also the reason what happened on the client which shows a different message, but could have this as the root cause.

SDK Java Error:

Error in query result: [{“msg”:"Unable to decode prepared statement - cause: Unrecognizable prepared statement - cause: JSON unmarshalling error: Keyspace not found keyspace - cause: No bucket named ",“code”:4070}] status: fatal

If I run the same query without Prepared Statement then it works every time.

Our Cluster Setup

  • 3 nodes (index, data, query on all nodes)
  • 5.0.0. AprilDB Community Edition (build Couchbase Server 5.0.0-2564 (EE))
  • just 1 bucket which we use
  • Memory Optimized Indexes

Just for sake of completeness the EXPLAIN for the non-prepared statement (which looks similar to me)

EXPLAIN SELECT COUNT(*) from datastoreitems WHERE datastoreid = 'd4d9ff0c-4478-11e7-a06f-901b0ea49fee' AND folder = 'default';
{
    "requestID": "a4dd2df6-ccd7-40b4-94ba-060918a86e9f",
    "signature": "json",
    "results": [
        {
            "plan": {
                "#operator": "Sequence",
                "~children": [
                    {
                        "#operator": "PrimaryScan",
                        "index": "#primary",
                        "keyspace": "datastoreitems",
                        "namespace": "default",
                        "using": "gsi"
                    },
                    {
                        "#operator": "Fetch",
                        "keyspace": "datastoreitems",
                        "namespace": "default"
                    },
                    {
                        "#operator": "Parallel",
                        "~child": {
                            "#operator": "Sequence",
                            "~children": [
                                {
                                    "#operator": "Filter",
                                    "condition": "(((`datastoreitems`.`datastoreid`) = \"d4d9ff0c-4478-11e7-a06f-901b0ea49fee\") and ((`datastoreitems`.`folder`) = \"default\"))"
                                },
                                {
                                    "#operator": "InitialGroup",
                                    "aggregates": [
                                        "count(*)"
                                    ],
                                    "group_keys": []
                                }
                            ]
                        }
                    },
                    {
                        "#operator": "IntermediateGroup",
                        "aggregates": [
                            "count(*)"
                        ],
                        "group_keys": []
                    },
                    {
                        "#operator": "FinalGroup",
                        "aggregates": [
                            "count(*)"
                        ],
                        "group_keys": []
                    },
                    {
                        "#operator": "Parallel",
                        "~child": {
                            "#operator": "Sequence",
                            "~children": [
                                {
                                    "#operator": "InitialProject",
                                    "result_terms": [
                                        {
                                            "expr": "count(*)"
                                        }
                                    ]
                                },
                                {
                                    "#operator": "FinalProject"
                                }
                            ]
                        }
                    }
                ]
            },
            "text": "SELECT COUNT(*) from datastoreitems WHERE datastoreid = 'd4d9ff0c-4478-11e7-a06f-901b0ea49fee' AND folder = 'default';"
        }
    ],
    "status": "success",
    "metrics": {
        "elapsedTime": "3.866902ms",
        "executionTime": "3.851888ms",
        "resultCount": 1,
        "resultSize": 2952
    }
}

Index is on datastoreid and folder.

CREATE INDEX Index_datastore ON datastoreitems(datastore_id, folder) USING GSI WITH {"num_replica":2}

It does look like MB-22273: could you tell me the exact build number of all of the 3 nodes?

Couchbase Server 5.0.0-2564 (EE)

All of them, I take it?