How will HHVM influence PHP?

Over the last few weeks, there’s been a slew of HHVM related news from the “We are the 98.5%” post from the HHVM team to the Our HHVM Roadmap from the Doctrine team. With the increasing excitement around HHVM, it’s becoming clear that the project is going to play an important role in the evolution of the PHP ecosystem. Even though it’s in it’s early stages, what influences will the HHVM project have on the PHP ecosystem as a whole?

Force the creation of a language spec

In contrast with other languages like Python or JavaScript, PHP has no formal language specification. There's some extended discussion on this StackOverflow thread with links to PHP internals posts but the final consensus is that there isn't a defined EBNF grammar for PHP or a "specification" for how things should work. Instead of a spec, the behavior of PHP has become defined by how the Zend interpreter works since it's been the only viable implementation of the language to date. HHVM changes this situation by introducing another run time for the language, a developer won't necessarily know if their code will be deployed on Zend or HHVM. Because of this, the community will have to develop a language specification to ensure that any language changes are implemented identically in both run times.

Willingness to introduce BC breakage

One of the hallmarks of PHP has been its strong adherence to backwards compatibility, five year old code written to target PHP4 will generally run today on PHP5+ without any modifications. This has generally been possible because changes to PHP the language didn't change behavior which would of broken previously working code. Because of this, many of PHP's long standing syntax issues haven't been fixed and changes to the standard library have been largely avoided. If HHVM emerges as an alternative runtime, some of this hesitation should be removed since if only "newer" code will run on HHVM it would be conceivable to introduce a "HHVM compat" mode into the Zend implementation which could include BC breaking syntax changes.

JIT into Zend

Just in-time compilation has been shown to dramatically increase the execution speed of interpretted programming languages and it's one of the key benefits of the HHVM interpretter. HHVM identities "hot code" which is repeatedly executed and then compiles those blocks to native code. The result of this is that those "hot code" sections execute faster since they're running native code instead of the interpreted op codes. As HHVM becomes more popular, I think we'll see cross pollination of JIT into Zend similar to how Firefox adopted JIT after Google released Chrome.

Anyway, it’s still early but the emergence of HHVM as an alternative PHP runtime will definitely have a positive influence on the PHP ecosystem. From technology sharing to increased competition, the future is bright and I’m excited to see how PHP evolves in the next few years.

SQL Join Checker, Making Sure Your Joins Are Right

Recently on a project we came across the need to generate a bunch of different reports from the database. Due to different requirements we weren’t able to use the ORM (Doctrine2 on the specific project), so we wrote the queries by hand. As we continued to build the different reports we noticed sometimes we’d typo a join, for example join something on id versus user_id. These small typos would cause the reports to still run fine, however have the incorrect data, often it was difficult to pinpoint the exact issue in the given report, as only certain conditions could reproduce the results. After a while Ashish said it’d be great if we had some sort of sanity checker to make sure the queries we were writing were going across the proper joins. To me, this was:

challenge-accepted

At first I thought about just using Regular Expressions to parse out the join parts of the SQL queries. However, I found http://code.google.com/p/php-sql-parser/ which appears to do the job. I downloaded it and wrote a class which uses it and some expressions to discover FK’s in the database. I ended up with something which, albeit not the most elegant, gets the job done. Here is an example output of it:

Checking query: select * from sf_guard_user u LEFT JOIN sf_guard_user_profile p ON u.id=p.id
                                                                                   
FK not found for u.id (sf_guard_user.id) join on p.id (sf_guard_user_profile.id)! Available mappings:
                                                                                   
     -sf_guard_user_group.group_id=>sf_guard_group.id                              
     -sf_guard_user_group.user_id=>sf_guard_user.id                                
     -sf_guard_user_permission.permission_id=>sf_guard_permission.id               
     -sf_guard_user_permission.user_id=>sf_guard_user.id                           
     -sf_guard_user_profile.user_id=>sf_guard_user.id                              
     -sf_guard_user_profile.participant_source_id=>participant_source.id           
Completed check. 

Basically it will run through whatever query you give it, and make sure that the columns you are joining on are defined in the DB. If you are trying to join on a column that is defined as a constraint, it will output the part of the join that failed the check as well as what FK’s currently do exist. Another issue this may help with, is if your database is missing a constraint (FK) that should be defined it will point it out.

I wrote this really quickly, so let me know (or make a pull request) if you find any bugs. I’ve put the code up on Github. Let me know if it helps out!

PHP: Geocoding with MaxMind and nginx

Earlier this week, one of our adtech clients reached out asking if we could setup IP based geocoding for one of their applications. At a high level, what the application basically does is serve as a backend for an advertising pixel which is embedded on the sites of various publishers. When users are visiting a publisher’s site, the JS pixel makes a HTTP request to our backend from the client’s browser, receives a data payload from the backend, and then does various computations on the frontend.

What our client was looking to do was add the geocoding data into the payload that is returned by the backend. We’ve had some success with the MaxMind database in the past so we decided to investigate using that solution here as well. Initially, we implemented the geocoding using the static MaxMind database along with PHP and memcached to cache the “warmed” MaxMind PHP object. Unfortunately, using PHP presented significant performance issues at the scale we were serving requests. At an average of 20,000 requests/minute, the additional load introduced by the PHP processes serializing and deserializing the MaxMind objects would have ultimately been prohibitively expensive, even across 3 frontends.

So what’s the alternative? Turns out, there’s actually an nginx module that leverages the MaxMind database to make the geocoding data available as CGI parameters. Effectively, this lets you access the geocoding variables for the client’s IP address directly from the $_SERVER variable in PHP. Here’s how you set it up:

Depending on what your setup is, you’ll just need to enable the geoip module in ngnix by following the directions here. Once you have ngnix recompiled with the module on, you’ll need to add the configuration parameters specified into your “server” block. The final configuration step is to add the variables that you want exposed as CGI parameters. All together, you’ll need to end up making these modifications to your config files:

http {

  # .... rest of your configs

  # You can download these files from http://dev.maxmind.com/geoip/legacy/geolite/
  # These files need to be in the same directory as your config file or just use absolute paths
  geoip_country GeoIP.dat;
  geoip_city    GeoLiteCity.dat;

}

server {
  # ...rest of your configs
 
 # make the variables available in PHP 
 fastcgi_param GEO_COUNTRY_CODE $geoip_city_country_code;
 fastcgi_param GEO_CITY $geoip_city;
 fastcgi_param GEO_DMA $geoip_dma_code;
 fastcgi_param GEO_LATITUDE $geoip_latitude;
 fastcgi_param GEO_LONGITUDE $geoip_longitude;
}

Reload or restart ngnix. Then, to access the variables in PHP you can just grab them out of the $_SERVER variable like:

<?php

foreach( array("GEO_COUNTRY_CODE", "GEO_COUNTRY_CITY", "GEO_DMA", "GEO_LATITUDE", "GEO_LONGITUDE") as $key){
  echo $_SERVER[ $key ] . "\n";
}

That’s about it. From our tests, adding the geo module has a negligible effect on performance which is awesome. Of course, your mileage may vary but it’ll certainly be faster than using PHP directly.

PHP: How fast is HipHop PHP?

In the last post, we walked through how to install HipHop PHP on a Ubuntu 13.04 EC2. Well thats great but it now leads us to the question of how fast HipHop PHP actually is. The problem with “toy benchmarks” is they tend to not really capture the real performance characteristics of whatever you’re benchmarking. This is why comparing the performance of a “Hello World” app across various languages and frameworks is generally a waste of time, since its not capturing a real world scenario. Luckily, I actually have some “real world”’ish benchmarks from my PHP: Does “big-o” complexity really matter? post a couple of months ago.

Ok so great, lets checkout the repository, run the benchmark with HipHop and Zend PHP, and then marvel at how HipHop blows Zend PHP out of the water.

$ git clone git@github.com:Setfive/setfive.github.com.git
$ cd setfive.github.com/autocomplete_test/
$ ~/dev/hiphop-php/hphp/hhvm/hhvm --hphp  -thhbc -o some_dir autocompleteBenchmark.php algorithms.php
$ ~/dev/hiphop-php/hphp/hhvm/hhvm -vRepo.Authoritative=true -vRepo.Central.Path=some_dir/hhvm.hhbc -vEval.Jit=1 autocompleteBenchmark.php
test_name, min, max, average
readMemoryScan,9.4527468681335, 9.7483551502228, 9.6144312620163
unsortedTableScan,9.2616581916809, 9.5636370182037, 9.3831548213959
sortedTableScan,4.0028560161591, 4.2003200054169, 4.1263886928558
serializednFileScan,0.12966299057007, 0.1957049369812, 0.14499731063843

$ php autocompleteBenchmark.php
test_name, min, max, average
readMemoryScan,1.1715579032898, 1.3546500205994, 1.2789875268936
unsortedTableScan,0.98337507247925, 1.0579788684845, 1.0203387260437
sortedTableScan,0.41418695449829, 0.54504704475403, 0.47947511672974
serializednFileScan,0.25355696678162, 0.31970500946045, 0.27470426559448

Wtf?

Well so that is weird, in 3 out of the 4 tests HipHop is an order of magnitude slower than Zend PHP. Clearly, something is definitely not right. I double checked the commands and everything is being run correctly. I started debugging the readMemoryScan function on HipHop specifically and it turns out that the problem function is actually str_getcsv. I decided to remove that function as well as the array_maps() since I wasn’t sure if HipHop would be able to optimize given the anonymous function being passed in. The new algorithms file is algorithms_hiphop.php which has str_getcsv replaced with an explode and array_map replaced with a loop.

Running the same benchmarks again except with the new algorithms file gives you:

$ ~/dev/hiphop-php/hphp/hhvm/hhvm -vRepo.Authoritative=true -vRepo.Central.Path=some_dir/hhvm.hhbc -vEval.Jit=1 autocompleteBenchmark.php
test_name, min, max, average
readMemoryScan,0.35798001289368, 0.43651509284973, 0.37085726261139
unsortedTableScan,0.25601601600647, 0.31864595413208, 0.27621953487396
sortedTableScan,0.12703394889832, 0.18750810623169, 0.13350143432617
serializednFileScan,0.13122606277466, 0.19621300697327, 0.15197308063507

$ php autocompleteBenchmark.php
test_name, min, max, average
readMemoryScan,0.52727389335632, 0.70799994468689, 0.64662590026855
unsortedTableScan,0.41211080551147, 0.48418807983398, 0.46322596073151
sortedTableScan,0.20118999481201, 0.2757511138916, 0.22925112247467
serializednFileScan,0.2424430847168, 0.36282706260681, 0.30896728038788

Wow. So the HipHop implementation is clearly faster but what’s even more surprising is that the Zend PHP implementation gains a significant speedup just by removing str_getcsv and array_map.

Anyway, as expected, HipHop is a faster implementation most likely due to its JIT compilation and additional optimizations that it’s able to add along the way.

Despite the speedup though, Facebook has made it clear that HipHop will only support a subset of the PHP language, notably that the dynamic features will never be implemented. At the end of the day, its not clear if HipHop will gain any mainstream penetration but hopefully it’ll push Zend to keep improving their interpreter and potentially incorporate some of HipHop’s JIT features.

Per Dan’s comment below, HHVM currently supports almost all of PHP 5.5s features.

Why is str_getcsv so slow?

Well benchmarks are all fine and well but I was curious why str_getcsv was so slow on both Zend and HipHop. Digging around, the HipHop implementation looks like:

<?php

function str_getcsv(
  $input,
  $delimiter = ',',
  $enclosure = '"',
  $escape = '\\',
) {
  $args = array($delimiter, $enclosure, $escape);
  $defaults = array(',', '"', '\\');

  $args_len = count($args);
  for ($i = 0; $i < $args_len; ++$i) {
    $arg_len = strlen($args[$i]);

    // fgetcsv returns false if passed anything but a single char for its
    // last three args. str_getcsv's behavior is to truncate strings down
    // to their first char, and to turn invalid args into the default args.
    if ($arg_len === 0) {
      $args[$i] = $defaults[$i];
    } else if ($arg_len > 1) {
      $args[$i] = substr($args[$i], 0, 1);
    }
  }

  $temp = tmpfile();
  fwrite($temp, $input);
  fseek($temp, 0);
  $ret = fgetcsv($temp, 0, $args[0], $args[1], $args[2]);
  fclose($temp);
  return $ret !== false ? $ret : array(null);
}

So basically just a wrapper around fgetcsv that works by writing the string to a temporary file. I’d expect file operations to be slow but I’m still surprised they’re that slow.

Anyway, looking at the Zend implementation it’s a native C function that calls into php_fgetcsv but doesn’t use temporary files.

/* {{{ proto array str_getcsv(string input[, string delimiter[, string enclosure[, string escape]]])
Parse a CSV string into an array */
PHP_FUNCTION(str_getcsv)
{
	char *str, delim = ',', enc = '"', esc = '\\';
	char *delim_str = NULL, *enc_str = NULL, *esc_str = NULL;
	int str_len = 0, delim_len = 0, enc_len = 0, esc_len = 0;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sss", &str, &str_len, &delim_str, &delim_len, 
		&enc_str, &enc_len, &esc_str, &esc_len) == FAILURE) {
		return;
	}
	
	delim = delim_len ? delim_str[0] : delim;
	enc = enc_len ? enc_str[0] : enc;
	esc = esc_len ? esc_str[0] : esc;

	php_fgetcsv(NULL, delim, enc, esc, str_len, str, return_value TSRMLS_CC);
}
/* }}} */

PHPAPI void php_fgetcsv(php_stream *stream, char delimiter, char enclosure, char escape_char, size_t buf_len, char *buf, zval *return_value TSRMLS_DC) /* {{{ */
{
	char *temp, *tptr, *bptr, *line_end, *limit;
	size_t temp_len, line_end_len;
	int inc_len;
	zend_bool first_field = 1;

	/* initialize internal state */
	php_mblen(NULL, 0);

	/* Now into new section that parses buf for delimiter/enclosure fields */

	/* Strip trailing space from buf, saving end of line in case required for enclosure field */

	bptr = buf;
	tptr = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter TSRMLS_CC);
	line_end_len = buf_len - (size_t)(tptr - buf);
	line_end = limit = tptr;

	/* reserve workspace for building each individual field */
	temp_len = buf_len;
	temp = emalloc(temp_len + line_end_len + 1);

	/* Initialize return array */
	array_init(return_value);

	/* Main loop to read CSV fields */
	/* NB this routine will return a single null entry for a blank line */

	do {
		char *comp_end, *hunk_begin;

		tptr = temp;
		inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0);
		if (inc_len == 1) {
			char *tmp = bptr;
			while (isspace((int)*(unsigned char *)tmp)) {
				tmp++;
			}
			if (*tmp == enclosure) {
				bptr = tmp;
			}
		}

		if (first_field && bptr == line_end) {
			add_next_index_null(return_value);
			break;
		}
		first_field = 0;
		/* 2. Read field, leaving bptr pointing at start of next field */
		if (inc_len != 0 && *bptr == enclosure) {
			int state = 0;

			bptr++;	/* move on to first character in field */
			hunk_begin = bptr;

			/* 2A. handle enclosure delimited field */
			for (;;) {
				switch (inc_len) {
					case 0:
						switch (state) {
							case 2:
								memcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
								tptr += (bptr - hunk_begin - 1);
								hunk_begin = bptr;
								goto quit_loop_2;

							case 1:
								memcpy(tptr, hunk_begin, bptr - hunk_begin);
								tptr += (bptr - hunk_begin);
								hunk_begin = bptr;
								/* break is omitted intentionally */

							case 0: {
								char *new_buf;
								size_t new_len;
								char *new_temp;

								if (hunk_begin != line_end) {
									memcpy(tptr, hunk_begin, bptr - hunk_begin);
									tptr += (bptr - hunk_begin);
									hunk_begin = bptr;
								}

								/* add the embedded line end to the field */
								memcpy(tptr, line_end, line_end_len);
								tptr += line_end_len;

								if (stream == NULL) {
									goto quit_loop_2;
								} else if ((new_buf = php_stream_get_line(stream, NULL, 0, &new_len)) == NULL) {
									/* we've got an unterminated enclosure,
									 * assign all the data from the start of
									 * the enclosure to end of data to the
									 * last element */
									if ((size_t)temp_len > (size_t)(limit - buf)) {
										goto quit_loop_2;
									}
									zval_dtor(return_value);
									RETVAL_FALSE;
									goto out;
								}
								temp_len += new_len;
								new_temp = erealloc(temp, temp_len);
								tptr = new_temp + (size_t)(tptr - temp);
								temp = new_temp;

								efree(buf);
								buf_len = new_len;
								bptr = buf = new_buf;
								hunk_begin = buf;

								line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter TSRMLS_CC);
								line_end_len = buf_len - (size_t)(limit - buf);

								state = 0;
							} break;
						}
						break;

					case -2:
					case -1:
						php_mblen(NULL, 0);
						/* break is omitted intentionally */
					case 1:
						/* we need to determine if the enclosure is
						 * 'real' or is it escaped */
						switch (state) {
							case 1: /* escaped */
								bptr++;
								state = 0;
								break;
							case 2: /* embedded enclosure ? let's check it */
								if (*bptr != enclosure) {
									/* real enclosure */
									memcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
									tptr += (bptr - hunk_begin - 1);
									hunk_begin = bptr;
									goto quit_loop_2;
								}
								memcpy(tptr, hunk_begin, bptr - hunk_begin);
								tptr += (bptr - hunk_begin);
								bptr++;
								hunk_begin = bptr;
								state = 0;
								break;
							default:
								if (*bptr == enclosure) {
									state = 2;
								} else if (*bptr == escape_char) {
									state = 1;
								}
								bptr++;
								break;
						}
						break;

					default:
						switch (state) {
							case 2:
								/* real enclosure */
								memcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
								tptr += (bptr - hunk_begin - 1);
								hunk_begin = bptr;
								goto quit_loop_2;
							case 1:
								bptr += inc_len;
								memcpy(tptr, hunk_begin, bptr - hunk_begin);
								tptr += (bptr - hunk_begin);
								hunk_begin = bptr;
								break;
							default:
								bptr += inc_len;
								break;
						}
						break;
				}
				inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0);
			}

		quit_loop_2:
			/* look up for a delimiter */
			for (;;) {
				switch (inc_len) {
					case 0:
						goto quit_loop_3;

					case -2:
					case -1:
						inc_len = 1;
						php_mblen(NULL, 0);
						/* break is omitted intentionally */
					case 1:
						if (*bptr == delimiter) {
							goto quit_loop_3;
						}
						break;
					default:
						break;
				}
				bptr += inc_len;
				inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0);
			}

		quit_loop_3:
			memcpy(tptr, hunk_begin, bptr - hunk_begin);
			tptr += (bptr - hunk_begin);
			bptr += inc_len;
			comp_end = tptr;
		} else {
			/* 2B. Handle non-enclosure field */

			hunk_begin = bptr;

			for (;;) {
				switch (inc_len) {
					case 0:
						goto quit_loop_4;
					case -2:
					case -1:
						inc_len = 1;
						php_mblen(NULL, 0);
						/* break is omitted intentionally */
					case 1:
						if (*bptr == delimiter) {
							goto quit_loop_4;
						}
						break;
					default:
						break;
				}
				bptr += inc_len;
				inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0);
			}
		quit_loop_4:
			memcpy(tptr, hunk_begin, bptr - hunk_begin);
			tptr += (bptr - hunk_begin);

			comp_end = (char *)php_fgetcsv_lookup_trailing_spaces(temp, tptr - temp, delimiter TSRMLS_CC);
			if (*bptr == delimiter) {
				bptr++;
			}
		}

		/* 3. Now pass our field back to php */
		*comp_end = '\0';
		add_next_index_stringl(return_value, temp, comp_end - temp, 1);
	} while (inc_len > 0);

out:
	efree(temp);
	if (stream) {
		efree(buf);
	}
}
/* }}} */

Looking at the actual implementation of php_fgetcsv though its not surprising its significantly slower compared to explode().

PHP: Installing HipHop PHP on Ubuntu

A couple of weeks ago, a blog post came across /r/php titled Wow HHVM is fast…too bad it doesn’t run my code. The post is pretty interesting, it takes a look at what the test pass % is for a variety of PHP frameworks and applications. This post was actually the first time I’d heard an update about HipHop in awhile so I was naturally curious to see how the project had evolved in the last year or so.

Turns out, the project has undergone a major overhaul and is well on its way to achieving production feature parity against the Zend PHP implementation. Anyway, I decided to give installing HipHop a shot and unfortunately their installation guide seems to be a bit out of date so here’s how you do it.

Quickstart

To keep things simple, I used a 64-bit Ubuntu 13.04 AMI (https://console.aws.amazon.com/ec2/home?region=us-east-1#launchAmi=ami-e1357b88) on a small EC2. One thing to note is that HipHop will only work on 64-bit machines right now.

Once you have the EC2 running, Facebook’s instructions on GitHub are mostly accurate except that you’ll need to manually install libunwind.

# Get all the pre-reqs installed:

sudo apt-get install git-core cmake g++ libboost-dev libmysqlclient-dev \
  libxml2-dev libmcrypt-dev libicu-dev openssl build-essential binutils-dev \
  libcap-dev libgd2-xpm-dev zlib1g-dev libtbb-dev libonig-dev libpcre3-dev \
  autoconf libtool libcurl4-openssl-dev libboost-system-dev \
  libboost-program-options-dev libboost-filesystem-dev wget memcached \
  libreadline-dev libncurses-dev libmemcached-dev libbz2-dev \
  libc-client2007e-dev php5-mcrypt php5-imagick libgoogle-perftools-dev \
  libelf-dev libdwarf-dev subversion \
  libboost-regex-dev libcurl4-openssl-dev libgoogle-glog-dev libjemalloc-dev

# Get the HipHop code

mkdir dev
cd dev
export CMAKE_PREFIX_PATH=`pwd`
git clone git://github.com/facebook/hiphop-php.git

# Get libevent and build it

git clone git://github.com/libevent/libevent.git
cd libevent
git checkout release-1.4.14b-stable
cat ../hiphop-php/hphp/third_party/libevent-1.4.14.fb-changes.diff | patch -p1
./autogen.sh
./configure --prefix=$CMAKE_PREFIX_PATH
make
make install
cd ..

# Get libunwind and build it
# NOTE: You need to set a CFLAGS option or you'll hit an error - http://comments.gmane.org/gmane.comp.lib.unwind.devel/1133

wget http://download.savannah.gnu.org/releases/libunwind/libunwind-1.0.1.tar.gz
tar -zxvf libunwind-1.0.1.tar.gz
cd libunwind-1.0.1/
export CFLAGS="-U_FORTIFY_SOURCE"
./configure --prefix=$CMAKE_PREFIX_PATH
make
make install
cd ..

# Build HipHop
# NOTE: This takes a loooong time on a small EC2
cd hiphop-php
rm CMakeCache.txt
export HPHP_HOME=`pwd`
cmake .
make

After that, you can test it out by running:

ubuntu@ip-10-60-47-153:~/dev/hiphop-php$ ./hphp/hhvm/hhvm -m server -p 8080
mapping self...
mapping self took 0'00" (6052 us) wall time
loading static content...
searching all files under source root...
analyzing 29483 files under source root...
loaded 0 bytes of static content in total
loading static content took 0'00" (363272 us) wall time
page server started
all servers started

Awesome, you have HipHop running. Now just how fast is it?

Well you’ll have to check back for part 2…