Don't encode POST bodies like GitHub Copilot, use URLSearchParams
jakearchibald.com
jakearchibald.com
(cache[key] = cache[key] || fn(...args));
Will not memoize results that equal 0 or an empty string.I guess it goes to show that copying answers from stack overflow might not be the best idea, whether it's done manually or using ML.
Pairing works when you either pair two strong programmers or pair a strong programmer with a weak one. In the latter case, the main advantage is that it's also a mentoring opportunity.
Copilot has invented a pair programming situation in which your partner constantly introduces dubious code you must painstakingly verify, but is itself incapable of being mentored.
Although `in` possibly opens you up to prototype issues. JavaScript is a bundle of fun.
Collection types are prevalent in languages like Java, but JS devs had to use plain objects for years.
Those who know what to do aren't hanging around on SO because we know what we're doing and we don't have time to do other peoples' job for them.
I'm not a lawyer, but I can see the risk if code seems to be substantially copied from copyleft corpuses of code.
I'm reminded of the "9 lines of code" that was disputed in Oracle vs Google.
https://majadhondt.wordpress.com/2012/05/16/googles-9-lines/
In my testing, given a portion of the GPL licence header, Copilot is quite happy to spit out the rest of it, so I would imagine copilot bans might happen quite fast.
EDIT: Oh, and it looks like there was a whole previous discussion [1] about this yesterday!
This whole thing just sounds like a bad idea from the start. Code should be written by humans. If you find yourself repeatedly writing the same boilerplate code, use or create a library, framework, or higher-level programming language, don't rely on an AI tool to attempt to guess what you want.
Dijkstra must be rolling his grave right now.
Lots of code isn’t written by humans.
func averageRuntimeInSeconds(runs []Run) float64 {
var totalTime int
var failedRuns int
for _, run := range runs {
if run.Failed {
failedRuns++
} else {
totalTime += run.Time
}
}
averageRuntime := float64(totalTime) / float64(len(runs) - failedRuns) / 1000
return averageRuntime
}I don't know Go, but from briefly skimming some articles, I believe a standard practice would be to define the function as:
func averageRuntimeInSeconds(runs []Run) (float64, error)
and then detect the situation when all runs failed, and return an error. Alternatively, there should be a documented assumption that the function expects non-zero successful runs in its argument.A sufficiently smart ML model could probably do either. This one doesn't, and the problem of NaNs is something I'd have a good chance of missing during code review.
The "standard" Go response is what you suggest. However, it does force the caller to deal with the error condition. For Go devs, this is standard procedure and they won't mind ;)
However, if the routine is relatively trivial, and it doesn't matter too much if an error occurs (but you don't want it to panic), then handling any errors inside the routine and always returning a valid result is OK.
If this was me, I'd take this second path, and keep the single return value, but catch the special case (float64(len(runs) - failedRuns) == 0) and return zero for that.
Or you could use the panic..recover method and trap the panic and return something sensible. I tend to avoid this, though, because it can trap panics further down the call chain (not in this example, obviously) and you end up with weird bugs that are hard to catch because they're not explicit.
Your argument goes like: some biking commuters already bike too fast in crowded places, so what harm will it do to incentivise them to put an engine on their bikes so they can go even faster, even on hills?
const memoize = fn => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
return (cache[key] = cache[key] || fn(...args));
};
}
It uses js falsyness to figure out whether it can return from the cache or if it needs to invoke the wrapped function. However, js falsy is pretty dangerous. "cache[key]" will return undefined if there's no value in the cache for those arguments, but undefined is not the only falsy value. Here's the full list: https://developer.mozilla.org/en-US/docs/Glossary/FalsyMany of those values are reasonable function return values meaning your cache will simply not work for some function outputs.
The key generation is also a little problematic. Stringifying the input may produce huge strings which are then kept in memory for an indefinite period of time which creates a memory leak.
Here's the bottom line on git co-pilot. It's a huge step forward and I think everyone is going to be using tools like it in the future. There's no doubt to me that it will make good programmers way more productive. However, not-so-good programmers will become way more destructive since copilot will let them write bad, unoptimized code faster than every before.
def memoize(func):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
else:
cache[args] = func(*args)
return cache[args]
return wrapper
and why wouldn't you just use # or @functoolscache (3.9+).
@functools.lru_cache(maxsize=None)
def f(*args, **kwargs):
passParadoxically I think that the more it'll improve the more dangerous it'll become, because if the Copilot gets it right 99% of the time you're more likely to miss the 1% of the time it doesn't. It's like car autopilots in a way, the better they become the more the driver lowers their guard and the more dangerous they become.
Questions answered 10 years ago have an accepted answer that was right at the time, but it's no longer the best answer. If a better answer was made 5 years ago, it might have a chance to at least be voted higher by now, but often the current best answer is simply too new and has only a small percentage of votes compared to the others.
In a lot of ways, it's likely to be a self-reinforcing problem, same as SO: someone chooses the recommended code -- which "works" but is not the most efficient, uses deprecated API, or worse has a security vulnerability -- and this trains the algorithm to think it's a good answer and recommend it more.
Before SO, the typical way people would find answers would be to go to their favorite search engine and type their query, and search engine's heuristics were really bad for this sort of thing. If you were very lucky, you'd get a (current) reference manual, but usually you'd end up with somone new web developer who had just learned something writing a tutorial for others and it was just the blind leading the blind.
I suspect Copilot will be somewhere in-between that and the current SO copy-pasta, with the main downside being that writing bad code is now that much more easier that reviewing it.
What would be cool is if StackOverflow let you choose to move your question down in the ranking to be below someone else. That way the history of the answers is still there, but the more update answer would get the first impression.
Example:
using (var reader = new StringReader(manyLines))
{
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);
}
becomes: using var reader = new StringReader(manyLines);
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);I've seen moments in the last week where no fewer than three items on the frontpage were dealing in Copilot outrage. URLSearchParams, on the other hand, is brand new. (I wouldn't even be surprised if this were the first time the topic has made it to the frontpage, ever—if it's even been submitted for discussion at all; searches aren't disconfirming this, but it's hard to be conclusive by just filtering on submission titles.)
As for the (obnoxiously stated) claim "Umm... the article is also about Copilot", you're off by about a mile (or maybe off by an amount that we'd expect from a machine that feels like it's doing pattern matching and faking deep, human-level understandig). Copilot's relationship to the article is incidental; it uses Copilot snippets as examples. The article is about URLSearchParams and data encoding.
I blog about things that catch my interest, and the coding error in Copilot caught my interest. Usually when I do a blog post about the 'right' way to do something, it's triggered by seeing it done 'wrong' somewhere. Usually I can't point to whoever did it wrong, because it's unfair, and as a result I get a lot of replies to the post like "duhhh everyone knows this already". But in this case it's AI creating the error, so it feels fine to point to the source of the error.
Rather than jumping on a hot topic to farm hits to my blog, I'm blogging about something that caught my interest, and it caught my interest because it's a hot topic.
I'm completely fine with chasing an incidental topic, my comment was in reaction to the parent's comment about people going offtopic, while, to me, it's pretty logical that the topic is going to be the news while it's still hot.
The Copilot thing is much more intriguing IMO. It is a large and fairly high-profile product launch of a developer tool, and the headline examples given contain a variety of subtle bugs – at least four that are listed in this comment thread alone. That's likely to stimulate some interesting discussion!
In our case, let's not pretend that React will be around forever. Once the new Hotness in the JS world shows up (and i't very easily distracted by shiny things and cool names), you will need to train the models, all over again.
The pod: https://podcasts.apple.com/us/podcast/is-a-i-the-problem-or-...
Just like all of our 'natural intelligences' (each other)!
expenses.append((datetime.datetime.strptime(date,"%Y-%m-%d"),
float(value),
currency))
Parsing currency into a float. I assume the perils of that are pretty well known.Then crafting some keyword seeded code that it would scoop up and retrain on.
Would be interesting if you could get some adversarial code to be the suggestion for some notable niche.
You don't actually need to find untrained cases. Using AWS and automated VSC you can retrain existing portions that are already trained. Or farm it out to mechanical turk, like bot farms or captcha farms.
This is a huge can of worms that is being opened by allowing these sorts of random inputs to source code creation - even though there will be filters on that input being used.
Imagine if I logged in with the email "sdflhasjd@gmail.com&email=admin@service.com". Service A thinks my email is invalid, it gets passed to another service without re-encoding and then Service B thinks I'm a superadmin. Uh oh.
What makes Wikipedia work anyway is a conflation of two things:
- Volunteers keeping it correct put in more effort than people trying to sneak in lies on purpose. There are many reasons why this is a case, one of which is, there's really not much to gain trying to mess with most Wiki pages.
- Whether or not a typical person is correct about something doesn't matter much.
- In cases where being correct does matter, it's usually easy to discover you're wrong. Life isn't a quiz show, you don't lose if you answer incorrectly - you get smacked in the face by wrong results, conflicting facts, inconsistent knowledge, and you get to course-correct. You ask around, grab a textbook, and fix your facts.
The second point is big and somewhat sad: it truly does not matter whether or not a random person has an accurate view of the world. Beliefs that have noticeable or immediate impact on one's life tend to be automatically corrected (see point 3) until they're good enough - all the rest of the knowledge serves a single purpose: social grooming. It doesn't matter if a news story, or a piece of trivia, is true - as long as you can tell it to someone and have a nice conversation, it's achieved its purpose. People who care about the truth for the sake of truth are the exception, not the norm.
Back to the topic of GitHub Copilot: code does not serve a social grooming function. Pretty much all code matters at face value, because it directs machines to do things. When Copilot feeds you bad code (or you mindlessly copy stuff from StackOverflow), the result is called a bug. The way reality corrects it is by the system failing, and someone having to debug it. This is expensive, so you want to minimize that.
Second, I'm optimistic that most bugs are found before code is even committed, so people will quickly learn that generated code needs to be carefully reviewed. I don't have access to Copilot, but if I did, I presume the way I'd use it is that I'd always comment out the generated code and just use it as a quick reference.
[1]: https://en.wikipedia.org/wiki/One_Flew_Over_the_Cuckoo%27s_N... [16 times over 6 years, see https://sigma.toolforge.org/usersearch.py?name=Erik&page=One...]
Am I against AI supporting humans? Of course not! I think it's the future and holds almost infinite potential. But the way this is done matters, and this is done just so utterly wrong.
How could it be done properly? Well, let's say you have a system in place where you actually prove the correctness of your program. Then of course there is no harm in letting the AI construct the program, because you know it is correct. Or let's say you wrote the program, and now the AI helps you to prove it is correct. Or both.
Of course, when the correctness of your program does not matter in the first place, but just its output, and you happen to be able to judge the quality of the output without knowing anything about your program, then something like Github Copilot makes sense.
Now I do understand many won't do so. But they already do the same, just slower, with their current method.
I admit, there few times I copied but I can count on fingers the number of times I used something from stackoverflow in my entire career (I'm not counting situations when I read somebody's explanation, but didn't use their code, which is just an example of how it works). From posts that I see people write as if they do that daily.
Also SO is only an example. There are many sites, and I call BS anybody who doesn't Ctrl + C once in a while, be it from the docs.
And if you want others to grow, make sure your answers give knowledge without giving solutions.
Maybe it's the language you work with?
If I copy and paste React code from SO it'll 100% break my app due to incompatible abstractions, so it doesn't make any sense to do it. However if I need a complex generic Typescript utility type, copying things verbatim is usually fine.
I've never had the luxury, I mostly work on low level stuff and at best, SO is usually only helpful in pointing me in the right direction.
And still I copy paste.
* Just to clarify, I'm not saying SO is bad, but just specifically the practice of blind copy/paste without reasoning about & understanding the code you've copied. SO moderators encourage/semi-enforce descriptive answers for this reason; to add context to the solutions provided.
Even if you just limit it to people largely taking solutions wholesale from SO, I still think that it’s a good jumping off point. Of course it’s a mistake to not make any modifications or look deeper than the whatever is in the snippet, but the snippet is often much better than what a noob would come up with.
Also, it’s an opportunity for learning new patterns that you might not have come up with yourself.
I would respectfully disagree on this point. Anything that perpetuates doing this in any way will always have a negative impact on code quality. If an engineer is copying solutions wholesale, even if those solutions are robust and high-quality, that's an indicator of the approach they have to producing code on a daily basis, which is going to have a much larger overall impact than that 1 answer on SO.
SO is imo a net positive benefit to the community, but only by virtue of them doing other beneficial things that balance out with the harm of copypaste programming. But I don't buy that copypaste programming is benign.
> Also, it’s an opportunity for learning new patterns that you might not have come up with yourself.
Blind copypaste is by definition not an opportunity to learn, because you need to understand (hack/fork/adapt answers given) to learn from them.
Also why all the anti-copilot seems to think their code is great, or even well understood by themself.
I have counterexamples everywhere around me all the time for these 3 points.
Copypaste programming doesn't have to be benign in order to be better than the likely alternatives. The people who blind copy/paste are likely not producing high quality code in the first place. In which case, blind copy/paste is often an improvement.
1. Delve into the original source to see what happens (or reverse engineer the binary) -- very time consuming!
2. Guess. Maybe write some test apps to play around with it till you get it working. This used to be very common, but leads to situations like the PS2 encryption algorithm being completely broken because the devs didn't understand the IV parameter.[1]
3. Go on StackExchange and find an example of what you are trying to do, usually with some helpful discussion about the parameters.
[1] You would think security libraries would have the best documentation because it's so important to get it right and difficult for the developer to detect mistakes, but I've found the opposite to be the case. They're some of the worst offenders for just showing you a cryptic function prototype and assuming you know everything about the underlying math already. It feels like the crypto guys think if you couldn't write your own crypto library then you aren't good enough to use theirs, kind of missing the point of libraries.
I wonder, how much better could Github Copilot become by also looking that the modifications that are subsequently made to the accepted suggestions? Obviously this would go quite a bit further in terms of telemetry, and may become an issue. They would essentially be training based on non-public code at that point.
That will make it the target of a collaborative bias attack.
I think context is important. It's not inherently bad. If you are inexperienced or don't know what the code/command is doing then yes that's not ideal.
But competent developers using Stack Overflow (and all other external memory devices) appropriately to aid their workflow is perfectly valid.
I rarely copy/paste verbatim from Stack Overflow (apart from perhaps bash commands where the answer is literally the exact command I need - and in that case, why would I not use it?). But I do copy/paste, as long as I understand the code, and then adjust it accordingly.
In my experience of coaching junior devs. The number one skill I've had to train them in, above all else, is the ability to efficiently search for and find answers to their questions/unknowns quickly. (As well as digest those answers and incorporate the knowledge into their understanding - not just blind copy/paste).
I'd go as far as to say that If you are a developer in 2021 and not constantly looking up things for reference (whether to jog your memory or to quickly learn new concepts) then you're either a genius with a photographic memory, working in a very constrained domain that isn't stretching you or you're just plain doing it wrong. :-)
There's always almost some nuance that the accepted answer might be lacking or you should know about that is mentioned.
Why not? Most of the software is not built by checking the formal verification of specification but by looking into the code and having reasonable understanding that it works. Also there will be errors in the code whether we use copilot or not. Personally if I don't have an option to do a build and run and look into the output, I am reasonably sure that there is at least one bug in something like every 50 lines.
Copilot makes it a method of FIRST resort.
If I know what I'm doing, and know I should escape my inputs... but copilot barfs up a block copied from someone who didn't... now I have to retrain myself to spend time reading the suggested code for stupid shit like that versus just using my own knowledge in the first place.
That's a far cry from "i know the method name I want has 'string' in it somewhere"-style autocomplete.
You're basically importing a library of "every stupid crap anyone committed to github" and just hoping the the library functions in it are safe and reasonable. That's a crazy dependency to bring into your project if your own programming skills are above that of the median github user.
So, roughly half of programmers would be _better_ served just blindly using Copilot's suggestions then?
Personally, I find that I work with so many different things so often that I "googling" is often much quicker even than reading documentation or even searching my own existing code.
But I also have _zero_ interest in Copilot at all, so what do I know?
Even that cannot really protect me from missing things like the security implications that this blog post talks about.
In this case, I probably wouldn't have fallen for the stuff CoPilot (or an equivalent SO answer) suggested, as I learned about these kind of injection issues a long time ago, but there are certainly a lot of areas where I would fail miserably to detect subtle (security) bugs. APIs are full of subtle and often non-obvious pitfalls, and even algorithms can be, where the algorithm seemingly works except for non-obvious edge cases that you might not have considered.
Is this serious? I've never literally copy pasted from stackoverflow. I read the answer and then go write my own code. Did you seriously copy pasted an entire chunk of code and committed it to your codebase after some edits?
A tool like this has the potential to help good programmers work more quickly, but it carries the risk of acting as a crutch. A lot of people might never put in the work to become good programmers because they learn how to be just good enough at using Copilot to fake it.
In a world where there are lots and lots of people trying to gain entry in the software industry, there's a major risk of this leading to a lot of incorrect, and even dangerous code making it into production because nobody really had a look at it.
However, you seem to be making the argument that is good behavior. I say it is not. The time saved by automating the googling/copying/pasting is miniscule compared to actually understanding the context in which the code is suited and ill suited. That is the developer's work, and it isn't fed by only the code.
Developing ain't typing. It's solving problems. Most of the time the problem isn't in code. Even when it is in code, there's nuance in how to best solve it that isn't. The idea that AI is useful in understanding the real world context of the problem better than the human (who has the whole context, in code and outside of it) is naive, or disingenuous.
The code i produced during my first few years isn’t something anyone should aspire to.
Additionally you likely learned over time that most SO posts are not great but provide a good starting point.
I think that when $PROJECT lets everybody do something at a scale that was before impossible, even if it's the "same thing", it is not "the same thing".
Then when every program is eventually upgraded to this status, all of the code we run is bootstrapped through proprietary AI - including the AI itself - and it's black boxes all the way down. Programming is now an experimental science where we gather evidence, test hypotheses, press the "copilot" button and tune parameters, like evolutionary biologists studying DNA code.
That doesn't seem sustainable. It also seems like a poor cost to value ratio.
Those "prove" you see in academic paper are very specific case.
Aren't we already there outside of very specific special applications? At the very least you have to assume every library you are using and the framework you are running on is correct. Sure, that works 99.9% of the time. If your testing framework can get the rest of the code to 99.5% of the time, is the .4% that large of a deal in a case where the other .1% is not?
When we look at what the market wants, what individual people want, do they want things proven correct given the increase in cost it brings? They may say they do, but spending behavior doesn't seem to align.
pretty much every domain, if you exclude finance & industries that intersect with life and death decisions such as pharma/medicine/airlines/defense.
what’s the correct order of movie recommendation ? its easy to see that given your past netflix history, there is an obviously incorrect order. but there is no obviously correct order - any number of orderings will work. correctness is not paramount.
what’s the correct puzzle to assign to a 1400 on chess.com ? obviously there are hundreds of them that would work. correctness is not paramount.
what’s the “correct price” of a used Ford Focus ? depends on whether you are a bandit who needs the car for a rapid getaway, or whether you are the brother in law of the used car salesman, in which case the correct price is zero usd.
the sole reason why 100 million developers crowd the web programming circuit and not other gatekeeped domains is because correctness is not paramount. whether your color code is off by a shade on this browser or your pixels misaligned on that browser, its all fine so long as it somewhat works. correctness is not paramount. otherwise nothing would ship.
Note that people die if data is lost, causing companies to go bankrupt (suecide). But really, not everything has to be correct, look at Intel and AMD. They've been compromising correctness for speed for quite awhile, and we're mostly fine.
I suspect this to be the majority of code written.
I would agree with you if it was called "GitHub Self-Coding" where you are the destination clerk and letting the tool code. But that's really not the goal of the tool. Don't put it in hand of non programmers
The problem with Copilot is that it works just enough to be dangerous: it streamlines copy-pasting of unchecked code, but the code it offers has subtle bugs. It's even worse than copy-pasting from StackOverflow, because code on SO got at least a passing review by someone who understands it. Here, you get code generated from ML models. Unlike generating pictures of faces or kittens, when an occasional artifact doesn't matter much, an "artifact" in code that you won't notice will still make the code wrong.
> Don't put it in hand of non programmers
Putting it in hands of programmers isn't really any better. To make it work, you need programmers to be disciplined - more disciplined than they were when copy-pasting from SO.
It's like copying from StackOverflow while ignoring upvotes, comments, and anything but the first revision ;=)
Also the problem isn't code that's obviously wrong when you read it. The problem is when code looks OK, but is subtly wrong. Which keeps happening - as we know today, at least two examples featured on Copilot homepage have this problem. To make this work, you have to read each snippet super carefully - which defeats the whole point.
It's all well and good to say there should be something better than just discipline but there's no idiot-proof way of writing programs.
As others have pointed out, at last Stack Overflow comes with context, the ability to rate and comment on suggestions, or even have a discussion about an approach. With this you take it or leave it. Saying you should already know what you need to do and what the tradeoffs are and how to evaluate the quality of the suggestion is basically saying this should have no value to you, and any consequences are all your fault if it does.
If you're using it to create something you don't know how to do then yeah you're in for a world of disappointment.
HN seems to be of the hivemind that random Joe Nocodes will be firing up VSCode and asking it for a custom version of Uber which.. yeah is laughable and honestly seems pretty obvious that that wont work.
(But I also have no interesting in using Copilot myself, tho maybe I should try it myself now, if only on some toy side project.)
In fact, the copilot is just a normal pilot with the only difference that the pilot is also the captain on board, responsible for the police and security on board. And most of the times, companies choose who is the pilot and who is the copilot randomly on a per-flight basis.
So no, you wouldn't a copilot that gives subtly wrong information to the pilot (and vice versa)
What companies are you aware of that do this? The proper terms are "Captain" and "First Officer" and they are actual rankings within the company, not something that is randomly chosen on a flight-by-flight basis. The actual details of who does what during the flight are generally not related to the ranks ("pilot flying" and "pilot monitoring" duties can and do switch during flight) although the Captain is always the ultimate authority and will be the one to take control in tough situations because he's got more experience.
Typical (i.e. almost all) commercial flights will have a Captain sitting in the left seat and a First Officer sitting in the right seat.
Who's going to stop them? There's an army of non-programmers trying to break into the industry. You can bet they are going to get their hands on this.
How is this approach "wrong"?
Finding a bug in something which seems to be correct can be harder then writing the correct code yourself.
Especially if you might not (yet) fully understand what you are doing.
So Copilot is only a good idea if you are a experienced programmer with the discipline to put any auto generate part through a proper (ad-hoc) code review.
At the same time it looks especially appealing to someone just starting to learn coding...
Spotting bugs in code that has been generated by a GPT-3 derivative, with all the subtle mistakes that implies, is going to be even harder.
I'm kind of skeptical! I think your claim is reasonable tho so maybe I'm more skeptical of your confidence?
I'd love to read a follow-up from you after you tried using Copilot for an extended period; even (or maybe especially) if it's as bad, or worse, than you expect!
But copilot isn't even equivalent to a code review: code review is not only checking for correctness. It's also asking questions and helping the author walk through their solution by having them reconsider it. Copilot doesn't ask questions, nor can it answer them or provide a rationale.
I don't think I understand why this should be true.
- get multiple answers
- comments on the answers
- up/down votes
- explanations along side of the answer
and I still would argue you should never copy from stack overflow!! Instead understand why the answer is correct and then write your code based on that understanding, even if it produces the exact same code in the end.
Your job as a programmer is to ensure the correctness of the code you write, Copilot isn't really changing that.
If you don't have these systems in place, you're getting what you deserve. Hiring subpar talent and not having processes in place isn't Copilot's fault.
This is almost like blaming the car for an accident. If you have a shitty driver and the traffic lights aren't working, it's not your Corolla's fault.
It shouldn't be that way, but it's how people work, so we should expect it to happen. (Psychologically, if an action is very rarely rewarded, people are less likely to do it.) Even if you want to be vigilant, it will be a bit of an uphill battle to make yourself do it.
Also, checking the auto-generated code takes time. You, as an individual contributor programmer, may believe that the time is absolutely worth it, but you will need management to support that. This technology creates additional opportunities for managers to say, "Don't worry about that. Ship it." Which is another thing that really shouldn't happen but in reality does.
> Of course, when the correctness of your program does not matter in the first place, but just its output
1. There are in fact very, very few projects that try to prove their correctness. Usually, those are extremely critical or dependencies for potential critical applications. Even if a project does this they're doing it partially just for keeping ROI sane. Please correct me if I'm wrong but AFAIK, even most programs on aircraft don't use this approach, although they're definitely interested.
2. For most of the projects, the primary goal is to be useful, to be correct is at most secondary.
3. A program written by humans is not inherently correct, it's more likely to be the opposite. No matter it's written by a human or a machine, you should always write test cases to reflect the properties you care in your program. Properly tested programs written by the machine don't make it less correct than those written by a human.
I'm generally interested in Copilot, not because of the novelty it claims to be, but the value it might provide. I see it as a potentially useful tool just like IntelliSense but with greater potential.
At the end of the day, it's an AI "Pair". I've been doing pair programming for years, one of the lessons I learned is one should not assume anything just because he/her pair partner is doing it - both of them should be responsible for their program.
OpenAI leadership knows that there is just sooo much value to capture in more automation, even if it takes billions to get there. They also know, that there is sooo much money around not knowing what to do and so much excitement in the field generated by bystanders, not understanding a single thing.
Perfect setting for ride and reap.
I repeat: There is nothing open about this, the research scientists are being used in order to propel just another get rich sooner-than-later scheme (how should they know better, they are innocent scientists). Happy bulldozing what is left of society in order to generate profits and to shove the AI BS down the managerial class, because that's all just how the system works.
And, if know all that, you can exploit it, hacker.
When people make security corrections to those snippets, ideally it would learn the corrections. Perhaps even have a feature to flag a snippet as insecure, to help that process.
Copilot is imperfect, yes. But there is a large grey area between perfect and "utterly wrong"
Not on internet discussion boards.
So the problem is that Copilot will only work for 99.99% of all the code that's ever written?
I think that's OK. Most code is subtly bugger no matter where it originated from. It's always going to be up to the developer to check and test what they're committing whether it's from Copilot, a co-worker, or they wrote it themselves. I think Copilot is meant as an aid to the code writing process, not a replacement. It's not really that different to any other tool.
Plus, fortunately, most code is never subtly buggy if you look at small enough parts. If it doesn't work correctly it's very obviously wrong. As Copilot is aimed (for now) at small functions any bugs will manifest in clearly broken outputs. It's when Copilot can generate entire classes, or whole applications, that we'll need to reassess if the code it creates is actually worthwhile.
Just like Tesla’s Autopilot, this was poorly named, at a minimum.
The problem exhibited in TFA is not so different from people copy/pasting StackOverflow answers without understanding them.
If we start by assuming the developer is a "good dev", I can't imagine Copilot is going to do anything useful for them, as this isn't going to be a useful way for them to come to understand how the system they are using works, and it won't support them building abstractions to reduce boilerplate. This tool is simply not useful for them.
Which leaves us with the idea what Copilot is a tool designed for "bad devs" to be able to do less work to do the bad things they do, and while I sort of appreciate the idea of "it is worthwhile to support people who don't know what they are doing in their attempt to do the bad thing they are doing anyway", I have severe reservations about doing that with engineering... it at least needs to be marketed as that!
Otherwise, the two main things we should be doing for "bad devs" is either helping them become "good devs"--which this doesn't do for much the same reasons it isn't useful for "good devs"--or we should honestly be trying to convince them not to be a developer at this level at all (which might include building higher-abstraction systems that are easier to use and understand).
Having said that, I don't know how the much more integrated write/review/edit cycle will work in practice when using copilot. I don't think it will be the same as a junior developer/pair programming partner in any real sense. My initial reaction to copilot is negative, but I'm open to being proven wrong about it.
- The snippet you get from Copilot is generated by an DNN model. I'd think that alone should scare people. DNN models are correct on a continuous scale, not discrete. A bad pixel on a generated image, an extra comma in generated text, are considered OK. That kind of correctness framework doesn't work with code.
From what I read, Codex (the model powering Copilot) is a GPT-3 derivative. Surely you've played with GPT-3 before, you've seen the types of mistakes it makes. In my eyes, this approach just won't fly for code.
Empirically, this is false. There is an incredibly high amount of bad, incomplete, or vulnerable code on SO.
I'm not worried about it suggesting subtly wrong code. I write subtly wrong code all day every day, and sometimes I catch it, and sometimes I don't. I write tests, I use types, etc. I'll use the same tools to reduce bugs from copilot that I do for myself.
I'm not really worried at all.
I think it's an excellent idea. People who copy-paste from Stack Overflow will also copy lots of shitty code or use it incorrectly.
But those of us with a clue, have a neat prototyping system where we can modify the solution until it's coherent. It's still on us. Copilot never claimed to produce the best code. And doesn't have to. That's the whole point behind the "pair programming" metaphor.
Those are way too many words to say "never".
There was another one somewhere else on there that calculated the number of days between two dates, but assumed that all days were exactly 24 hours long and is no doubt ready to introduce a maddening bug into someone's codebase when it is used inappropriately.
Meh. This is only a problem if it's unknown text or from an external source like user input. If it's from a known, trusted source, like internal code it's fine.
The cleaning should be done on the server side, anyway, so this objection is moot. Anyone can send any kind of body. Your client is in "enemy territory". Treat everything coming from the client side as potentially dangerous.
If you take this article's advice, you might think you're safe by just using these form data or url encoding. No. Not at all. This will not save you from SQL injection attacks or whatever. Only server-side cleaning will do that.
I think this post was promoted only because it mentions copilot, to be honest. It's not good security
It holds the session keys. It decides what can or cannot happen after the user clicks on a link with some funny URL in an e-mail. It displays and processes data entered by less trustworthy users. If anyone can just make it insert random HTTP headers, this could be a problem.
Yes, the server must assume that enemy agents also exist. But it should better not deliver one to all users.
I'm guessing we have different 'threat models' in mind.
From my perspective, I know _I_ am a moral and ethical person and therefore won't "execute an action against the user's will".
But, also from my perspective, even if "that action is allowed according to the user's credentials", I can't tell, and thus my server-side code can't tell, that a 'user' is a real person or even a legitimate user of my site or app.
The comment I was replying to claimed that "The user agent is ... is not enemy territory.".
But what came to my mind on reading that was user agent's also (commonly) perform 'card testing' and 'credential stuffing' and, even if I trust that I can securely give them access to my front-end/client-side code, I have no way to know whether they're running that code. And, even if they're running my code, there's _still_ room for malicious or nefarious action on their part.
I was NOT disagreeing with this (in the comment to which I was replying):
> Yes, the server must assume that enemy agents also exist. But it should better not deliver one to all users.
We should define terms before arguing. Enemy territory is anything you do not directly control. So, as a developer, you do not know if the user's agent is running your code from your server or something compromised. Assume the worst. Anything exiting the user's agent must be cleaned.
> Executing an action against the user's will is a security issue
Non-sequitur. Unless you're saying the `text` parameter could somehow execute code? It can't.
Considering the worst reasonable scenario, that this `text` parameter is sent directly from user input: so what? It may not be great practice, but it's not a security issue. Clean it server-side, which is what should be happening anyway, which the article fails to mention.
Considering the worst unreasonable scenario: the `text` parameter is compromised by a hacker somehow. Well, you're dealing with a far worse situation than could be handled by cleaning input client-side. Better to ensure input is secure... on the server side.
But, maybe I and others here are wrong. Assume many of us do have a worrying misunderstanding of the fundamentals. For the sake of the health of the internet, step us all through this scenario where a secure server side does not save the day, but these methods do.
We all agree on that part. What's worrying here is the mentality that, once the server-side has been secured, the client can do whatever. It can be manipulated anyway, so it does not matter for security if it does validation or not.
This is wrong. As a user, I don't care if an attacker has manipulated my data on the client or on the server. As a site owner you are responsible for delivering a secure client.
Yes we should define our terms. The first term we need to define is "security". From the comments here, I'm starting to think people define it as "RCE on the server". That's a rather narrow view.
> step us all through this scenario where a secure server side does not save the day
Back to the example: maybe you're building a chat tool, and it has this sentiment-feature to help with moderation. At the very least, this bug could hide offensive content from a moderator. But you are calling POST to "/api/sentiment/" with untrusted text that can leak into other parts of the request. I haven't done the analysis, but maybe an additional form field could be set, say "learnAsPositive=true"? Or maybe you have some questionable "not a security problem" API design that re-uses the same POST endpoint for multiple things, and you could set "blockUser=true" and control the user name, or moderators can edit the message text. Or maybe it wasn't a sentiment endpoint but something more important, and the untrusted text could be the name of another user.
Is not a "narrow view" of security. Your example is not secure, period, which is fine, because that's not where security needs to happen.
Co-pilot is nothing short of amazing and a force multiplier for senior devs, despite all the denial, I’m afraid.
The same things will happens with this tech. You may argue that's where the human programmers comes in to check the code, but can you spot the almost sound code with just one letter of difference that cause the complete failure?
But I fear this is the way we head to. If it does work most of the time, majority of people accept the risk. Because, at certain point, it's indistinguishable from human error rate.
Imagine if you get get an app that uses `http-rest-api` and `http-www-crud` with `http-www-multifactor` and `http-rest-api-license-key` and you could automatically be using the latest rest API, the latest CRUD framework, the latest multifactor/whatever framework (which you'd probably pin to some standard like YubiKey so user tokens don't get invalidated regularly). The actual reference implementation could be done in pseudocode even, and ported to many languages (ok this is getting too meta). You could throw together a professional quality application in a few lines of package management. And if someone finds a bug in the code, it gets updated, and next time a release is cut you'll pull it down automatically and deploys itself.
class JsonBody extends Blob {
constructor (obj) {
super([JSON.stringify(obj)], { type : 'application/json' })
}
}
fetch(url, { method: 'POST', body: new JsonBody({ hello: 'world' }) })
That's quite handy const createJSONBlob = (obj) => new Blob([JSON.stringify(obj)], { type : 'application/json' });I think maybe we can train this further using existing linters and analyzers? At least the AI will emit far fewer lines of critically dangerous code, but we'll still have a lot of anti-pattern issues.
Maybe GPT isn't really a good fit for this kind of task. Maybe we can create a better assistant using simpler AIs. If we reduce the scope (e.g. language, framework) and programming style (e.g. OOP, code organization, design), the amount of context should be much smaller than what GPT is hoarding. This may also allow us to have some open-source programming AIs.
Isn’t the an `escape_entities` function like in old school php (haven’t used php in decades, so I don’t know how all the cool cats do it today)?
Also, URLSearchParams will set the content-type for you, and allows you to _decode_ urlencoded data.
After reading this blog article. I just now used this AI https://6b.eleuther.ai/ to do it in about an hour. Without hardly trying.
self.params = ast.literal_eval(paramString)
but it even re-wrote that part for me...
self.params = urllib.parse.parse_qs(paramString)
Analogous to Greshaw's law, if two standards are accepted in a organization, then bad standards (those with lesser intrinsic value expressed by time-effort) will replace good standards.
// get password from the database using a mysql query function fetch_password(string $username) {
And 7/10 parameters are vulnerable to SQL-injection. Here's the first:
global $mysqli;
$query = "SELECT password FROM users WHERE username = '$username'";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_assoc();
return $row['password'];
}
return false;
Here's all of them: https://paste.ubuntu.com/p/9qQ2BSnqbF/I think there's a lot of old code that perhaps should not be used by Copilot as a reference, given how some programming languages have changed quite a bit over time when it comes to the best way of doing certain things.
Will it? Maybe.
Would I count on it in all cases? No.
Also, I find it preposterous to rely on a second automated system to cancel out the mistakes the first one made.
Downvote away. You know who you are.
Also, I just checked out an old Flask/Python project from 7 years ago, updated it to use Poetry dependency management, and it all still works. A JS project that is 7 months old and unmaintained would be a dumpster fire.
Don't get me wrong, nothing against Copilot, as long as you understand the code and you know what you are doing. And yes, most devs did not know that, but they think they are the kings.
XSS?
what's the vector attack here?
where the `text` comes from?
edit. oh I see, somebody can overwrite other params, yea?
I did assume the example was client side, but it might not be. The server may be using it to avoid adding a comment to a database if it's abusive. URLSearchParams exists in Node too https://nodejs.org/api/url.html#url_class_urlsearchparams. There are fetch polyfills available, but the plan is to add it to node.
text="foo&sendPasswordTo=hacker" or text="foo&admin=1"
You can imagine a potentially dangerous parameter and value being passed.
People can already send whatever body they want to your API endpoint. Your client side cleaning won't matter
The polyfill below gives a similar example with a caveat of adding a content-type header.
It looks like it does escape at least a few ~( etc with function encode. But there are a billion emojis, unicode whatever to escape?
I've read in the past that browsers have all kinds of URL quirks, and I've seen examples that i've copied into my own code which base64 encode / decode before sending (or GET an image pixel with params).
> Why doesn't the example he criticizes use a plain text request body when it's only a single parameter anyway?
The API supports other params, namely "language" http://text-processing.com/docs/sentiment.html
> And is he seriously recommending HTTP FORM POST data as a best practice to send API request/responses when you're using JavaScript?
If the API only accepts a URL encoded body then I absolutely recommend sending a URL encoded body. If you're in control of the API endpoint, then you can pick whatever format you want.
An HTML form can send data as application/x-www-form-urlencoded, multipart/form-data, or text/plain (although that's useless in practice). If you're progressively enhancing a form, you might want to gather the data in the same format as would otherwise be submitted. You could send it in that format with JavaScript, or convert it to another format (there's a whole section about that at the end of the article).
I recommend using multipart/form-data if you need to send file data along with other values. You'll have a bad time trying to send this as JSON. This recommendation is right at the end of the article.
Ah, didn't get that context; your clarification is appreciated. Though I'm not sure kids these days care about progressive enhancement-style webdev ...
Does anyone think it's ever a good idea to post files and form data all at the same time, to the same endpoint? That right there seems like an exceptionally bad idea.
Typically I would generate signed upload URLs for clients to upload files directly to some bucket and the submitted form data would contain only pointers to those uploads.
I guess it depends on your server set up.
I don’t think so? I think sending JSON POST data is a solved problem, so to speak: everyone already knows how to do it. The evidence suggests the same is not true for form data.
That'd be a pretty great feature to add if it isn't there yet.
This is like asking, IMO, "how can humans be trusted to pilot planes, when my barista can't ride a bike?"
Now the author is pointing out that you need to encode parameters manually. Maybe this is a good case for sane defaults like we had in every HTTP client 10 years ago?
I've written articles about fetch in the past, but if I search Google for "fetch API" my stuff doesn't show up in the first few pages at least, so I don't think I really qualify for "principal advocate".
Again, it's pretty easy to look this stuff up.
Dude, could you please add a disclaimer that it's insecure no matter what unless the server-side fetch cleans data. You write very authoritatively, and might give naive devs the impression that your solutions are secure enough.