Index: includes/session.inc
===================================================================
--- includes/session.inc	(revision 616)
+++ includes/session.inc	(working copy)
@@ -1,5 +1,5 @@
 <?php
-// $Id: session.inc,v 1.48 2008/04/16 11:35:51 dries Exp $
+// $Id: session.inc,v 1.49 2008/07/11 10:14:27 dries Exp $
 
 /**
  * @file
@@ -57,7 +57,10 @@
   global $user;
 
   // If saving of session data is disabled or if the client doesn't have a session,
-  // and one isn't being created ($value), do nothing.
+  // and one isn't being created ($value), do nothing. This keeps crawlers out of
+  // the session table. This reduces memory and server load, and gives more useful
+  // statistics. We can't eliminate anonymous session table rows without breaking
+  // the "Who's Online" block.
   if (!session_save_session() || (empty($_COOKIE[session_name()]) && empty($value))) {
     return TRUE;
   }
@@ -76,12 +79,19 @@
   else {
     db_query("UPDATE {sessions} SET uid = %d, cache = %d, hostname = '%s', session = '%s', timestamp = %d WHERE sid = '%s'", $user->uid, isset($user->cache) ? $user->cache : 0, ip_address(), $value, time(), $key);
 
-    // Last access time is updated no more frequently than once every 180 seconds.
-    // This reduces contention in the users table.
-    if ($user->uid && time() - $user->access > variable_get('session_write_interval', 180)) {
-      db_query("UPDATE {users} SET access = %d WHERE uid = %d", time(), $user->uid);
+    if (db_affected_rows()) {
+      // Last access time is updated no more frequently than once every 180 seconds.
+      // This reduces contention in the users table.
+      if ($user->uid && time() - $user->access > variable_get('session_write_interval', 180)) {
+        db_query("UPDATE {users} SET access = %d WHERE uid = %d", time(), $user->uid);
+      }
     }
   }
+  else {
+    // If this query fails, another parallel request probably got here first.
+    // In that case, any session data generated in this request is discarded.
+    @db_query("INSERT INTO {sessions} (sid, uid, cache, hostname, session, timestamp) VALUES ('%s', %d, %d, '%s', '%s', %d)", $key, $user->uid, isset($user->cache) ? $user->cache : '', ip_address(), $value, time());
+  }
 
   return TRUE;
 }
