public function handler_read($sid) {
        try {
            if (!$record = $this->database->get_record('sessions', array('sid'=>$sid), 'id')) {
                // Let's cheat and skip locking if this is the first access,
                // do not create the record here, let the manager do it after session init.
                $this->failed = false;
                $this->recordid = null;
                $this->lasthash = sha1('');
                return '';
            }
            if ($this->recordid and $this->recordid != $record->id) {
                error_log('Second session read with different record id detected, cannot read session');
                $this->failed = true;
                $this->recordid = null;
                return '';
            }
            if (!$this->recordid) {
                // Lock session if exists and not already locked.
                $this->database->get_session_lock($record->id, $this->acquiretimeout);
                $this->recordid = $record->id;
            }
        } catch (\dml_sessionwait_exception $ex) {
            // This is a fatal error, better inform users.
            // It should not happen very often - all pages that need long time to execute
            // should close session immediately after access control checks.
            error_log('Cannot obtain session lock for sid: '.$sid);
            $this->failed = true;
            throw $ex;

        } catch (\Exception $ex) {
            // Do not rethrow exceptions here, this should not happen.
            error_log('Unknown exception when starting database session : '.$sid.' - '.$ex->getMessage());
            $this->failed = true;
            $this->recordid = null;
            return '';
        }

        // Finally read the full session data because we know we have the lock now.
        if (!$record = $this->database->get_record('sessions', array('id'=>$record->id), 'id, sessdata')) {
            // Ignore - something else just deleted the session record.
            $this->failed = true;
            $this->recordid = null;
            return '';
        }
        $this->failed = false;

        if (is_null($record->sessdata)) {
            $data = '';
            $this->lasthash = sha1('');
        } else {
            $data = base64_decode($record->sessdata);
            $this->lasthash = sha1($record->sessdata);
        }

        return $data;
    }