cockroach icon indicating copy to clipboard operation
cockroach copied to clipboard

Sometimes tables seem empty!

Open ZiCog opened this issue 9 years ago • 9 comments

Sometimes the following query returns zero rows despite there being 100's of thousands of rows in the table:

SELECT * FROM bank.accounts ORDER BY id DESC LIMIT 1;

This issue is under discussion on the forum here: https://forum.cockroachlabs.com/t/sometimes-my-700-000-row-table-seems-empty/900

I will add details to reproduce here in a moment....

Here we go:

Machine: amd64, 2GByte RAM, 128GB SSD.

OS: Debian GNU/Linux 9

Kernel: Linux jhctech2 4.9.0-3-amd64 #1 SMP Debian 4.9.30-2+deb9u3 (2017-08-06) x86_64 GNU/Linux

cockroachdb:

$ cockroach version Build Tag: v1.0.4 Build Time: 2017/07/27 17:54:36 Distribution: CCL Platform: linux amd64 Go Version: go1.8.3 C Compiler: gcc 6.3.0 Build SHA-1: 5b757262d33d814bda1deb2af20161a1f7749df3 Build Type: release

Node.js: v8.2.1

I start three instances of cockroach on this machine, as per the getting started instructions on the web site:

$ nohup cockroach start --certs-dir=certs --store=node1 --host=localhost --port=26257 --http-port=8080 --http-host=localhost & $ nohup cockroach start --certs-dir=certs --store=node2 --host=localhost --port=26258 --http-port=8081 --http-host=localhost --join=localhost:26257 & $ nohup cockroach start --certs-dir=certs --store=node3 --host=localhost --port=26259 --http-port=8082 --http-host=localhost --join=localhost:26257 &

I start filling up the example bank account table, 100 inserts persecond, from node.js using pg and this code:

const fs = require('fs')

const config = {
host: 'localhost',
port: 26257,
user: 'root',
database: 'bank',

// this object will be passed to the TLSSocket constructor
ssl: {
    rejectUnauthorized: false,
    ca: fs.readFileSync('/home/rsm/certs/ca.crt').toString(),
    key: fs.readFileSync('/home/rsm/certs/client.root.key').toString(),
    cert: fs.readFileSync('/home/rsm/certs/client.root.crt').toString()
}
}

const { Pool } = require('pg')

const pool = new Pool(config)

const query = {
text: 'INSERT INTO accounts(id, balance) VALUES($1, $2)',
values: [24, 666]
}

setInterval(function () {
query.values[0]++
pool.query(query, (err, res) => {
    if (err) {
    console.log(err.stack)
    } else {
    console.log(res.rows)
    }
})
}, 10)

pool.query('SELECT * FROM accounts', (err, res) => {
if (err) {
    throw err
}
console.log('accounts:', res.rows)
})

Then start querying the table for the last record using the sql shell:

root@:26257/> SELECT * FROM bank.accounts ORDER BY id DESC LIMIT 1;
+--------+---------+
|   id   | balance |
+--------+---------+
| 788130 |     666 |
+--------+---------+
(1 row)
root@:26257/> SELECT * FROM bank.accounts ORDER BY id DESC LIMIT 1;
+----+---------+
| id | balance |
+----+---------+
+----+---------+
(0 rows)
root@:26257/> SELECT * FROM bank.accounts ORDER BY id DESC LIMIT 1;
+--------+---------+
|   id   | balance |
+--------+---------+
| 875072 |     666 |
+--------+---------+
(1 row)

NOTE: The EMPTY row returned. This happens one in 20 or thrirty queries.

The following code that makes the same query produces the same error from pg.

const fs = require('fs')

const config = {
host: 'localhost',
port: 26257,
user: 'root',
database: 'bank',

  ssl: {
      rejectUnauthorized: false,
      ca: fs.readFileSync('/home/rsm/certs/ca.crt').toString(),
      key: fs.readFileSync('/home/rsm/certs/client.root.key').toString(),
      cert: fs.readFileSync('/home/rsm/certs/client.root.crt').toString()
  }
}

const { Pool } = require('pg')

const pool = new Pool(config)

let previousId = 0;

setInterval(function () {
pool.query('SELECT * FROM bank.accounts ORDER BY id DESC LIMIT 1;', (err, res) => {
    let id = 0;
    if (err) {
    throw err
    }
    if (res.rows.length < 1) {
    console.log('Error: Empty result');
    } else {
    id = res.rows[0].id
    if (id < previousId) {
        console.log('Error: Low result')
    } else {
        previousId = id
    }
    console.log(res.rows[0].id)
    }
})
}, 100)

ZiCog avatar Aug 22 '17 20:08 ZiCog

This can be reproduced on master after about a minute using kv --concurrency=1 --sequential and running the script:

while :; do
    val=$(./cockroach sql --insecure -e "SELECT k FROM test.kv ORDER BY k DESC LIMIT 1;" --format raw | grep -v '#')
    if [ -z "${val}" ]; then
	echo "empty result"
    fi
done

I'm trying to bisect where in our stack this issue is coming from. Right now I can see the ReverseScanResponse with len(br.Rows) == 0 in client.Txn, so it doesn't look like this is an issue at the sql layer.

nvb avatar Aug 22 '17 20:08 nvb

Strange, I still can't reproduce on master. Here's a slightly more sophisticated script that also doesn't reproduce an error:

lastval="0"
while :; do
    val=$(./cockroach sql --insecure -e "SELECT k FROM test.kv ORDER BY k DESC LIMIT 1;" --format raw | grep -v '#')
    if [ "${val}" -le "${lastval}" ]; then
	echo "unexpected result: ${val} <= ${lastval}"
    fi
    lastval=${val}
done

petermattis avatar Aug 22 '17 20:08 petermattis

I just modified my writer code such that it waits for an insertion query to complete before starting the next one. Similarly the read query.

The result is that I did not get an empty row result until nearly half a million rows were inserted.

I guess that my using setInterval can result in multiple queries being in flight at the same time when things are busy. Using setTimeout serializes the activity and seems to reduce the possibility of the error showing up.

write.js:

const fs = require('fs')

const config = {
  host: 'localhost',
  port: 26257,
  user: 'root',
  database: 'bank',

  ssl: {
    rejectUnauthorized: false,
    ca: fs.readFileSync('/home/rsm/certs/ca.crt').toString(),
    key: fs.readFileSync('/home/rsm/certs/client.root.key').toString(),
    cert: fs.readFileSync('/home/rsm/certs/client.root.crt').toString()
  }
}

const { Pool } = require('pg')

const pool = new Pool(config)

let id = 0

function write () {
  let query = {
    text: 'INSERT INTO accounts(id, balance) VALUES($1, $2)',
    values: [id, Math.random * 10000]
  }
  pool.query(query, (err, res) => {
    if (err) {
      console.log(err.stack)
    } else {
      console.log(res.rows)
    }
    id = id + 1
    setTimeout(write, 10)
  })
}

write()

read.js:

const fs = require('fs')

const config = {
  host: 'localhost',
  port: 26257,
  user: 'root',
  database: 'bank',

  ssl: {
    rejectUnauthorized: false,
    ca: fs.readFileSync('/home/rsm/certs/ca.crt').toString(),
    key: fs.readFileSync('/home/rsm/certs/client.root.key').toString(),
    cert: fs.readFileSync('/home/rsm/certs/client.root.crt').toString()
  }
}

const { Pool } = require('pg')

const pool = new Pool(config)

let highestId = 0

function query () {
  pool.query('SELECT * FROM bank.accounts ORDER BY id DESC LIMIT 1;', (err, res) => {
    let id = 0
    if (err) {
      console.log('Error:', err)
    } else if (res.rows.length < 1) {
      console.log('Error: Empty result')
    } else {
      id = parseInt(res.rows[0].id)
      if (id < highestId) {
        console.log('Error: Low result: highestId:', highestId, 'id:', id)
      }
      if (id > highestId) {
        highestId = id
      }
      console.log(id)
    }
    setTimeout(query, 100)
  })
}

query()


results:

. . . 470373 470378 470382 470387 470388 Error: Empty result 470393 470396 470398 470399 . . .

ZiCog avatar Aug 22 '17 20:08 ZiCog

My current theory is that we're doing something funky with MaxSpanRequestKeys when performing ReverseScans. I can't seem to reproduce this with the query SELECT * FROM bank.accounts ORDER BY id ASC LIMIT 1;. A wild guess is that it has something to do with intents counting towards the limit.

nvb avatar Aug 22 '17 20:08 nvb

I think @tschottdorf and I found the issue. The problem is in MVCCIterate, in the case where the first key that a reverse scan finds is at a future timestamp. When the mvccGetInternal attempts to seek to the next MVCC version of the key, it ends up "falling of the end of a table". The tricky part here is that if there are other tables in the keyspace after the table being scanned this won't be a problem and we will properly reverse scan again to the previous key. However, if we are at the final key in the keyspace, the version scan will send us all the way to the KeyMax, and the iterator will suddenly return iter.Valid() == false. This is not an issue for forward scans because the MVCC version scan is in the same direction as the key scan, so the iter.Valid should be false if no other versions are found and we are at the last key in the keyspace. The fix was super small, and I'm just working on a small test now. Thanks for bringing this issue to our attention @ZiCog!

I'm going to make a conjecture that the reason @petermattis was not able to repro this is that he did not have a clean cockroach-data directory, so there were keys later in the keyspace.

nvb avatar Aug 22 '17 22:08 nvb

Wow. Wish I understood any of that! Sounds like a great piece of detective work.

You are right. I was starting from totally fresh data directories whenever I ran my tests. Repeatability and all that.

Looking forward to testing your fix.

Then I'll be in a position to use cockroach on three cloud instances for a trial run but doing useful work.

ZiCog avatar Aug 22 '17 22:08 ZiCog

I'm going to make a conjecture that the reason @petermattis was not able to repro this is that he did not have a clean cockroach-data directory, so there were keys later in the keyspace.

I was rm -rf cockroach-data before each test I ran.

petermattis avatar Aug 23 '17 00:08 petermattis

PS Nice sleuthing.

petermattis avatar Aug 23 '17 00:08 petermattis

I ran my test above against a clone of master branch (commit 5a6fbddfc0bc....).

After over 1.5 million inserts the reported error did not occur.

Looks fixed to me.

ZiCog avatar Aug 24 '17 13:08 ZiCog